JPA and unique fields

I have two persistence objects in my application: Things and tags attached to things. An application can create collections of things with attached tags. Tag objects have a unique name (it makes no sense to mark something twice with the same tag).

When pasting Thing (with tags attached), some of these tag objects with the same name may already exist in db. Now here is the part that I don’t remember about JPA, is there a way to tell JPA that it should not try to add appropriate objects to db if it violates a unique constraint? Or is there a way to do this efficiently without having to first retrieve all the objects, then combine the collection in memory and then write everything back?

I am also wondering if it is possible to immediately save the whole collection or do I need to call persist for each object when using JPA?

+2
source share
1 answer

I don’t know how to do this “cleanly”, neither with JPA, nor with Hibernate, nor with any other provider. You can achieve what you want with a special 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, unfortunately, you are associated with both Hibernate and MySQL. You can change the sql syntax for other databases: s and / or use stored procedures, try updating first, insert a crash, etc. Everyone has their drawbacks, so it would be convenient if the JPA support this, but alas.

, JPA , .

+1

All Articles