JPA and unique fields

六月ゝ 毕业季﹏ 提交于 2019-12-21 21:33:17

问题


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?


回答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.



来源:https://stackoverflow.com/questions/3275100/jpa-and-unique-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!