0

I am new to hibernate.I have a primary key value of an object and need to load an object from DB. I read that an object can be loaded using either get() or load() or using criteria API.

I am a little confused which one is better to use under which condition. Can somebody please guide me?

1
  • 2
    Posting your code so far is always helpful. Commented Jul 22, 2012 at 11:24

1 Answer 1

1

Session.get() checks if the object is already in the session. If it is, it returns it. If not, it executes a select statement to load the state of the object in the session, and returns it. It's the method that you should use by default.

Session.load() checks if the object is already in the session. If it is, it returns it. If not, it creates an uninitialized proxy and returns the proxy. It doesn't even hit the database. The first method called on the proxy will make Hibernate load the state of the object from the database, and initialize the proxy. You typically use this method when you just need a reference to an existing object, to initialize a to-one association for example.

A Criteria query or HQL query will always query the database. You wouldn't use that to do the same thing as Session.get(). It can be useful to load an object by primary key, and initialize associations that would otherwise be lazy-loaded using Session.get(). If you know that you'll need a student with all its courses, it's better to load everything in a single query than loading the student in one query, and the courses in a second one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.