休眠+"ON DUPLICATE KEY";逻辑 [英] Hibernate + "ON DUPLICATE KEY" logic

查看:109
本文介绍了休眠+"ON DUPLICATE KEY";逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据表的唯一键(由几列组成)寻找保存或更新记录的方法.

I am looking for a way to save or update records, according to the table's unique key which is composed of several columns).

我想实现与INSERT ... ON DUPLICATE KEY UPDATE相同的功能-意味着盲目保存一条记录,并让DB/Hibernate插入一条新记录,或者如果唯一键已经存在,则更新现有记录.

I want to achieve the same functionality used by INSERT ... ON DUPLICATE KEY UPDATE - meaning to blindly save a record, and have the DB/Hibernate insert a new one, or update the existing one if the unique key already exists.

我知道我可以使用@SQLInsert( sql="INSERT INTO .. ON DUPLICATE KEY UPDATE"),但是我希望不要编写自己的SQL,而让Hibernate完成这项工作. (我假设它将做得更好-否则为什么要使用Hibernate?)

I know I can use @SQLInsert( sql="INSERT INTO .. ON DUPLICATE KEY UPDATE"), but I was hoping not to write my own SQLs and let Hibernate do the job. (I am assuming it will do a better job - otherwise why use Hibernate?)

推荐答案

对我来说,这听起来并不像是一种干净的方法.最好先查看具有给定密钥的实体是否存在.如果是这样,请对其进行更新并保存,否则请创建一个新的.

This doesn't really sound like a clean approach to me. It would be better to first see if an entity with given key(s) exists. If so, update it and save it, if not create a new one.

编辑

或者考虑是否要使用merge():

Or maybe consider if merge() is what you're looking for:

  • 如果当前与会话相关联的持久性实例具有相同的标识符,则将给定对象的状态复制到持久性实例上
  • 如果当前没有与该会话关联的持久性实例,请尝试从数据库中加载它,或创建一个新的持久性实例
  • 返回持久实例
  • 给定实例未与会话关联,它保持分离

< http://docs.jboss.org/hibernate/core/3.3/reference/zh-CN/html/objectstate.html

这篇关于休眠+"ON DUPLICATE KEY";逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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