I have a one to many relationship between BookShelf and Book. The ISBN number in the book table is a unique field. Now when i try to insert a shelf with a set of books (with same isbn numbers )i get a constraint violation exception and the records in the books table are not inserted. My problem is, the shelf record still gets inserted. Doesnt hibernate insert the one shelf record and its corresponding book records in a transaction or batch. What i want is that if the insertion in books table fails because of duplicate entry, then the record in the shelf table shud not be inserted. can any body please tell me how to achieve this.
Asked
Active
Viewed 780 times
0
-
Hibernate does what you tell it to do. Enclose your operations within a transaction and rollback it in case something goes wrong. – skuntsel Feb 25 '13 at 12:24
2 Answers
0
Read chapter Transaction and concurrency of Hibernate official documentation and employ the programmatic transaction management principles you find there (13.2.1):
Session sess = factory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
//do your database work
tx.commit();
}
catch (RuntimeException e) {
if (tx != null) tx.rollback();
throw e; // or display error message
}
finally {
sess.close();
}
Otherwise, look for container managed transactions that will handle transaction and session management for you.

skuntsel
- 11,624
- 11
- 44
- 67
0
Check your persistence.xml if you are not using JTA your transaction type should be RESOURCE_LOCAL
<persistence-unit name="PU" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>java:/comp/env/jdbc/DS</non-jta-data-source>
Check this sample
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("PU");
EntityManager em = emf.createEntityManager();
try {
em.setFlushMode(FlushModeType.COMMIT);
em.getTransaction().begin();
BookShelf bs = new BookShelf();
bs.setName("Adventure");
Book b1 = new Book();
b1.setTitle("Spider Man");
bs.addBook(b1);
Book b2 = new Book();
b2.setTitle("Spider Man"); //Duplicate
bs.addBook(b2);
em.persist(bs);
try {
em.getTransaction().commit();
} catch (Throwable t) {
t.printStackTrace();
em.getTransaction().rollback();
}
} catch (Throwable t2) {
t2.printStackTrace();
} finally {
em.close();
emf.close();
}
BookShelf.java
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "bookShelf")
private List<Book> bookList;
public void addBook(Book book) {
if (bookList == null) {
bookList = new java.util.ArrayList<Book>();
}
book.setBookShelf(this);
bookList.add(book);
}

Arun VC
- 115
- 3