Tutorial :JPA and unique fields



Question:

I have two persistence objects in my app: Things and tags attached to things. The app can generate collections of things with tags attached. Tag objects have a unique name (it doesn't make sense to tag something twice with the same tag).

When inserting a Thing (with tag objects attached) some of these tag objects with the same name maybe already exist in the db. Now here is the part I don't recall about JPA, is there a way to tell JPA that it should not try to add the corresponding objects to the db if it violates the unique constraint? Or is there a way to do this efficiently w/o having to first fetch all objects, then merge the collection in memory and then write everything back?

I'm also wondering if it's possible to persist a whole collection at once or do I have to call persist for every object when using JPA?


Solution:1

I don't know of any way of doing this 'cleanly', neither with JPA nor with Hibernate or any other provider. You can achieve what you want with a custom SQL query though (similar to this question):

@Entity  @Table(name="tag")  @SQLInsert( sql="INSERT INTO tag(name, count) VALUES (?, ?)   ON DUPLICATE KEY UPDATE set count = count + 1")  public class Tag {}  

Now you are unfortunately bound to both Hibernate and MySQL. You can vary the sql syntax for other DB:s, and/or use stored procedures, try an update first and insert on failure etc. They all have their drawbacks, so it would be handy if JPA would support this, but alas.

Regarding you second question, JPA support persisting whole object graphs, including collections.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »