Force Hibernate Insert Without Select Statements

2020-02-01 07:21发布

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?

3条回答
劳资没心,怎么记你
2楼-- · 2020-02-01 08:06

Hibernate is trying to determine if the object is transient or not, so is performing a SELECT before INSERT. You might be able to adapt this answer from Hibernate OneToOne mapping executes select statement before insert; not sure why to avoid the SELECT.

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.

查看更多
手持菜刀,她持情操
3楼-- · 2020-02-01 08:11

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?t=951275

查看更多
Viruses.
4楼-- · 2020-02-01 08:14

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 call save(). That happens when you flush() 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 like

Session session = openSession();
Transaction tx = session.beginTransaction();
session.save(myObject);
tx.commit();

and see what statements that produces.

查看更多
登录 后发表回答