Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Hibernate Insert Without Select Statements

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?

like image 559
kand Avatar asked Sep 28 '11 19:09

kand


People also ask

Why does Hibernate do a SELECT before Insert?

Hibernate is trying to determine if the object is transient or not, so is performing a SELECT before INSERT .

How do I stop Spring Data JPA from doing a select before a save ()?

The solution is to use @javax. persistence. Version on a new versionNumber column in all the tables. If you have a parent and child table then use @Version column in all the entity classes.


2 Answers

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)

like image 85
Patrick Finnegan Avatar answered Sep 20 '22 14:09

Patrick Finnegan


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.

like image 32
andyb Avatar answered Sep 16 '22 14:09

andyb