Loading an object by R4R Team

This is useful if we need to create an association to an object without actually loading it from the database. It also allows multiple instances to be loaded as a batch if batch-size is defined for the class mapping.

The load() methods of Session provide a way of retrieving a persistent instance if you know its identifier. load() takes a class object and loads the state into a newly instantiated instance of that class in a persistent state.

Student stud = (Student) session.load(Student.class, generatedId);
// you need to wrap primitive identifiers
long id = 1234;
DomesticStudent stu = (DomesticStudent) session.load( DomesticStudent.class, new Long(id) );

Alternatively, we can load state into a given instance:

Student stud = new DomesticStudent();
// load pk's state into cat
session.load( student, new Long(stuId) );
Set kittens = student.getKittens();

We need to always Be aware that load() will throw an unrecoverable exception if there is no matching database row. If the class is mapped with a proxy, load() just returns an uninitialized proxy and does not actually hit the database until you invoke a method of the proxy.

It also allows multiple instances to be loaded as a batch if batch-size is defined for the class mapping.
If you are not certain that a matching row exists, you should use the get() method which hits the database immediately and returns null if there is no matching row.

Student student = (Student) sess.get(Student.class, id);
if (student==null) {
    student = new Student();
    sess.save(student, id);
return student;

we can load an object using an SQL SELECT ... FOR UPDATE, using a LockMode.

Student student = (Student) sess.get(Student.class, id, LockMode.UPGRADE);

Any associated instances or contained collections will not be selected FOR UPDATE, unless you decide to specify lock or all as a cascade style for the association.

It is possible to re-load an object and all its collections at any time, using the refresh() method. This is useful when database triggers are used to initialize some of the properties of the object.

sess.flush(); //force the SQL INSERT
sess.refresh(student); //re-read the state (after the trigger executes)

How much does Hibernate load from the database and how many SQL SELECTs will it use? 

ans: This depends on the fetching strategy
Leave a Comment:
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!