JPA and unique fields

社会主义新天地 提交于 2019-12-04 16:39:21
Alexander Torstling

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.

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