JPA和独特的领域
我的应用程序中有两个持久性对象:事物和附加到事物的标签。该应用程序可以生成带有附加标签的事物集合。标签对象具有唯一的名称(使用相同标签两次标记某物是没有意义的)。
插入事物(附加标签对象)时,其中一些具有相同名称的标签对象可能已存在于数据库中。现在这是我不记得关于JPA的部分,有没有办法告诉JPA,如果它违反了唯一约束,它不应该尝试将相应的对象添加到数据库中?或者有没有一种方法可以有效地做到这一点,而不必首先获取所有对象,然后将集合合并到内存中,然后将所有内容写回?
我还想知道是否可以一次持久保存整个集合,或者在使用 JPA 时是否必须为每个对象调用 persist ?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道有什么方法可以“干净”地做到这一点,无论是使用 JPA 还是使用 Hibernate 或任何其他提供商。不过,您可以使用自定义 SQL 查询来实现您想要的效果(类似于 这个问题):
不幸的是,现在您同时绑定了 Hibernate 和 MySQL。您可以改变其他 DB:s 的 sql 语法,和/或使用存储过程,首先尝试更新并在失败时插入等。它们都有各自的缺点,因此如果 JPA 支持这一点将会很方便,但可惜。
关于第二个问题,JPA 支持持久化整个对象图,包括集合。
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):
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.