Tobia
Tobia

Reputation: 9506

Hibernate insert foreign key

I'm using hibernate to insert some rows but I don't know if I'm doing well...

My enity has a foreign key and i know its id, I can't understand if I need the referenced object or just the id. I how there is a way to do this because it is not useful getting the referenced object just for insert.

I want to do this:

en=new MyEntity();
en.setForeignVal("1");

Seems i have to do this:

en=new MyEntity();
refObj=getSession().get(RefObject.class, "1"); //unuseful
en.setForeignVal(refObj);

Upvotes: 1

Views: 1692

Answers (1)

axtavt
axtavt

Reputation: 242686

Hibernate provides a special method for this use case - load(). It returns a proxy with the given id without hitting the database:

en.setForeignVal(getSession().load(RefObject.class, "1")); 

Upvotes: 2

Related Questions