JPA和独特的领域 [英] JPA and unique fields

查看:121
本文介绍了JPA和独特的领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用中有两个持久性对象:附在事物上的东西和标签。该应用程序可以生成带有标签的东西的集合。标记对象具有唯一的名称(使用相同的标记标记两次没有意义)。

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).

插入Thing(附带标记对象)时这些具有相同名称的标记对象可能已存在于db中。现在这里是我不记得有关JPA的部分,有没有办法告诉JPA如果它违反了唯一约束,它不应该尝试将相应的对象添加到db?或者有没有办法有效地做到这一点,不必首先获取所有对象,然后合并内存中的集合然后写回所有东西?

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?

我也是想知道是否有可能一次持续整个集合,或者在使用JPA时是否必须为每个对象调用持久性?

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?

推荐答案

我不知道采用JPA,Hibernate或任何其他提供商的方式干净利落。您可以通过自定义SQL查询实现所需(与这个问题):

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 {}

现在不幸的是你绑定了Hibernate和MySQL。您可以改变其他DB的sql语法:和/或使用存储过程,首先尝试更新并在失败时插入等等。它们都有它们的缺点,所以如果JPA支持这个,它会很方便,但是唉。

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.

关于第二个问题,JPA支持持久化整个对象图,包括集合。

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

这篇关于JPA和独特的领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆