强制 Hibernate 插入而不使用 Select 语句
我正在尝试将一条新记录插入到一个我事先知道是唯一的表中。我尝试过在对象上调用 save() ,但是在执行任何 INSERT 之前会执行一堆 SELECT 语句,我不想这样做,因为我知道该对象已经是唯一的。
我正在为每笔交易打开一个新会话,我认为这是一个问题,但这是我的域的限制。有没有办法强制 Hibernate 在 INSERT 之前不执行任何 SELECT 操作?
I am attempting to insert a new record into a table that I know is unique before hand. I have tried calling save() on the object, but that does a bunch of SELECT statements before doing any INSERTs, which I don't want to do because I know the object is already unique.
I am opening a new session for each transaction, which I can see being an issue, but that is a constraint of my domain. Is there some way to force Hibernate to not do any SELECTs before it INSERTs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 persist() 方法而不是 save()。
https://forum.hibernate.org/viewtopic.php?f= 1&t=1011405
但是,与 save() 不同,persist() 不保证立即在持久化实例上设置标识符值。
https://forum.hibernate.org/viewtopic.php?f= 1&t=951275
(您可以跳到克里斯蒂安在线程中的最后一篇帖子)
You can use the persist() method rather than save().
https://forum.hibernate.org/viewtopic.php?f=1&t=1011405
However, unlike save(), persist() does not guarantee that the identifier value will be set immediately on the persisted instance.
https://forum.hibernate.org/viewtopic.php?f=1&t=951275
(and you can jump to christian's last post in the thread)
Hibernate 正在尝试确定对象是否是瞬态的,因此在
INSERT
之前执行SELECT
。您也许可以从 Hibernate OneToOne 映射在插入之前执行 select 语句;不知道为什么要避免SELECT
。或者,我记得论坛上有一篇关于覆盖 hibernate 在瞬态检查(以及乐观锁定)中使用的
version
列的帖子。当我找到这个答案时,我会编辑它。Hibernate is trying to determine if the object is transient or not, so is performing a
SELECT
beforeINSERT
. You might be able to adapt this answer from Hibernate OneToOne mapping executes select statement before insert; not sure why to avoid theSELECT
.Or, I remember a post in a forum about overriding the
version
column that hibernate uses in the transient check (and for optimistic locking). I'll edit this answer when I find it.继承 Persistable 并覆盖 isNew 如下:
Inherit Persistable and override isNew as following:
Hibernate 不会在
save()
上发出选择来查看对象是否唯一。事实上,当您调用save()
时,Hibernate 甚至不会发出插入。当您flush()
或提交事务时就会发生这种情况。您需要准确地找出选择的用途以及启动它们的原因。为了帮助缩小范围,您可以编写一个快速测试,例如查看生成的语句。
Hibernate doesn't issue a select to see if an object is unique upon a
save()
. In point of fact, Hibernate doesn't even issue an insert when you callsave()
. That happens when youflush()
or commit the transaction. You'll need to find out exactly what the selects are for and what's initiating them. To help narrow it down, you could write a quick test likeand see what statements that produces.