Hibernate persist entity without fetching association object. just by id

“Can I persist car record without fetching user?”

Yes, that’s one of the good sides of Hibernate proxies:

User user = entityManager.getReference(User.class, userId); // session.load() for native Session API  
Car car = new Car();
car.setUser(user);

The key point here is to use EntityManager.getReference:

Get an instance, whose state may be lazily fetched.

Hibernate will just create the proxy based on the provided id, without fetching the entity from the database.

“If I use session.createSQLQuery(“insert into …..values()”) will the Hibernate’s batch insert work fine?”

No, it will not. Queries are executed immediately.

Leave a Comment