Display Hibernate OneToOne executes a select statement before pasting; not sure why

I set up a simple OneToOne display in my entity, but when I save the object, I see that the Select statement is executed by Hibernate just before the insert, and I don’t know why.

@Entity @Table( name = "USER" ) public class NewUser { @OneToOne @JoinColumn(name="user_status_type_id", nullable=false) private UserStatusType userStatusType; 

UserStatusType is just a read-only lookup table, so when you save a user, nothing is saved in this table.

 User u = new User(); u.setUserStatusType( new UserStatusType(101)); session.persis(u); 

But when I save the User object, the output from Hibernate reads like this:

 Hibernate: select userstatus_.user_status_type_id, userstatus_.user_status_name as user2_3_ from USER_STATUS_TYPE userstatus_ where userstatus_.user_status_type_id=? Hibernate: insert into USER (created, first_name, last_name, password, user_name, user_status_type_id) values (?, ?, ?, ?, ?, ?) 

I do not know if this is normal for Hibernate. I realized that since it was a "persist" operation, I would only see the Insert statement; unsure of the purpose for choosing.

Incorrect display?

+4
source share
1 answer

OK, I was able to get a response on the Hibernate forums. To prevent SELECT before INSERT, if you are sure that the reference string exists in the database, use Session.load () or EntityManager.getReference ().

 User u = new User(); u.setUserStatusType( session.load(UserStatusType.class, new Long(id)); session.persis(u); 

The session.load () method does not initially load anything, it simply creates a proxy for the object and avoids getting into the database. Now, if you want to access a member (other than the id field) from the class in the context of the session, then Hibernate will go to the database. In my case, I just need the primary key of the reference object for INSERT, so I avoided getting into the database.

+5
source

Source: https://habr.com/ru/post/1342474/


All Articles