Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to persist an Object

 
Pramod Kumar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I need to modify a record in db, I have class with getters and setters and I am persisting this Object to db, I am able to insert data thru em.persist(user);

user is the object of that class, now I need to update the data in db I am using em.merge(user); now throwing IllegalArgumentException and think that object need to be persisted before doing update. How to persist this object.

Thanks,
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is this Hibernate we are talking about? Or another ORM?
 
Pramod Kumar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is in Hibernate EntityManager and JPA
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given this simple JPA annotated POJO:



It can be persisted to the database, updated, retrieved and deleted with the following code which focusses on the basic CRUD operations:




Is that what you were looking for?
[ October 25, 2007: Message edited by: Cameron McKenzie ]
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ouch.

In Cameron's example he is creating a SessionFactory in each method. In a production application you will want to only create it once and have the entire application share that one and only one instance. As SessionFactory objects are heavy-weight objects. Now Session objects are light-weight.

And in defense of Cameron's example, there really is only one mapped class, so the SessionFactory isn't as heavy as it would be in a real application.

Mark
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good point, Mark. There's actually a chapter in my Hibernate book that explores just that point, along with other optimizations around the SessionFactory, Session, and the Hibernate Core in general.

The example is purely for andragogical purposes. Each method is contains all of the information needed to perform the database interaction, without calling any helper classes or singleton methods or anything like that.

When you're learning, I think it's good to see as much of the plumbing as possible. In production, it's another story.

-Cameron McKenzie
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic