Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save hibernate object with foreign key without loading the dependent object

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?

like image 583
Richa Avatar asked Nov 15 '17 08:11

Richa


1 Answers

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.

like image 197
Maciej Kowalski Avatar answered Nov 05 '22 08:11

Maciej Kowalski