Tuesday, April 27, 2010

EntityManager methods to save Beans

People asked: Why there is two different methods to save jpa entities.Something like EntityManager.save(anyKindOfEntityBean) ?

Lets have a look at what we have actually
EntityManager.persists (newEntityBean) : creates a new entity using sql insert.If entity already exists in the database you will get a Unique Contraint Violation.

EntityManager.merge (anyKindOfEntityBean) : It creates if not exists.It updates if exists.


Because when you really want to create new entity and you want to be 100% sure it is
new, you use #persist and if that object actually exists, the #persist
will throw an exception.

With #merge, you would have to query database first to make sure.

Briefly If you don't care about objects are really new or not you can use merge of course.

But..Don't you think that it is a bit dangerous? ;)

No comments:

Post a Comment