[英]Hibernate, how to avoid duplicates?
my table has 3 columns: ID, City, District. 我的表有3列:ID,City,District。
My web service give in input a list of couples (City, District). 我的网络服务输入一对夫妇(城市,区)的列表。 I need to avoid couples (City, District) duplicates.
我需要避免情侣(城市,区)重复。
How can I achieve this result? 我怎样才能达到这个效果? I can't use session.saveOrUpdate() because due to a different ID, all the records seems always different.
我不能使用session.saveOrUpdate(),因为由于ID不同,所有记录似乎总是不同。
Please help me. 请帮我。
Thank you. 谢谢。
The comment suggests what you should do 评论建议你应该做什么
CONSTRAINT city_district_unique UNIQUE (city, district)
create a UNIQUE constraint for the fields. 为字段创建一个UNIQUE约束。 This can also be done with JPA annotations when you want to create the table with Hibernate
当您想要使用Hibernate创建表时,也可以使用JPA注释完成此操作
@Table(name = "yourtable", uuniqueConstraints = {@UniqueConstraint(columnNames = "subject"), ... })
When inserting, you should catch the Exception from the violation of the above constraint and handle it properly, like re-running the insert with changed parameters or ignore it at all. 插入时,您应该从违反上述约束的过程中捕获异常并正确处理它,例如重新运行带有更改参数的插入或根本不用它。 Even better, check your data befor it gets to Hibernate to avoid the invalid inserts beforehand.
更好的是,检查你的数据是否得到Hibernate以避免事先无效的插入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.