Save hibernate object with foreign key without loading the dependent object

Richa :

When we save an object in Hibernate then we save the dependent object not as an id but with loading that object and saving it.

Ex: Employee has a department foreign key, so if we need to save the employee object then we will do something like:

saveEmployee{
emp.setName(name);
Department department = session.find(Department.class,deptid);
emp.setDepartment(department);
}

Now in case we import 1000 records and there we have deptid as a separate column in excel, then unnecessary 1000 times db will be called to fetch respective department.

Any better way to do this then Is it possible to have foreign key enforced without object-to-object mapping?

Maciej Kowalski :

Use the load method instead of find:

Department department = session.load(Department.class,deptid);

The persistence provider will only create a proxy at that point and assume that the entity physically exists on the database (there will be an error reaised if its not there to keep in mind).

Provided that all your operations are withing one transactinoal method, you will get N number of insertions without any selects.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=463505&siteId=1