File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Need help in simplifying transaction based code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Need help in simplifying transaction based code" Watch "Need help in simplifying transaction based code" New topic

Need help in simplifying transaction based code

Timothy Sam
Ranch Hand

Joined: Sep 18, 2005
Posts: 746
Hi guys! I'm really doubtful about this code here but it's the only thing that works for me as of now. I wanted this to be in a single transaction but I'm not sure how to do it.

If you look at the code, you'll notice that I made an early commit, which I didn't want to do but I had no choice because I wanted to get the generated ID to be able to produce a controlId String.

You'll also notice that I made many commit statements which makes the rollback in the try-catch block useless because changes are already reflected to the database when an exception is thrown. I really want to avoid this so I want to put them all in a single transaction and rollback everything if an exception occurs. Many thanks!

SCJP 1.5 -
Mike Keith
Ranch Hand

Joined: Jul 14, 2005
Posts: 304
Hi Timothy,

The problem of obtaining a generated id before commit can be solved by issuing a flush call, so I would normally recommend that you do that, however, looking at your code I have to say (and no offence intended) that you might really want to so some more reading on JPA before going any further. I think you would find that a small investment of a day or two would really pay dividends. Pick up any book on JPA (I can recommend one ;-) that takes your fancy and learn when and how to use which EntityManager operations, etc.

Pro JPA 2: Mastering the Java Persistence API
Timothy Sam
Ranch Hand

Joined: Sep 18, 2005
Posts: 746
Thanks! It worked! I adjust my code like the following:

I can see that you have written a book? My friend whom I ask to order for me isn't with me anymore so I won't be able to get stuff on the internet anytime soon. Thanks a lot for the help BTW!
I agree. Here's the link:
subject: Need help in simplifying transaction based code
Similar Threads
persistence.xml file for MS SQL Server 2000
Value is session managed bean's attribute is nulled
Can a class be mapped to a table and be Embeddable at the same time?
JPA and Generated Key
Need help with Mapping(Annotation) and Composition