gamo
gamo

Reputation: 1577

Is there any difference between createQuery and using hibernate session interface?

For example I have these line of code:

    session = getSessionFactory().getCurrentSession();
    users = session.createQuery("from Users where id=?")
            .setParameter(0, id)
            .list();

And

    session = getSessionFactory().getCurrentSession();
    users = session.get(Users.class, id);

I couldn't get clear which one is better and when should we use them?

Upvotes: 1

Views: 42

Answers (1)

StanislavL
StanislavL

Reputation: 57421

In the second case it returns instance of object Users (not list).

SO in the first case list of Users is expected.

If nothing is found the first case returns empty list but the second returns null. From Session.java

/**
 * Return the persistent instance of the given entity class with the given identifier,
 * or null if there is no such persistent instance. (If the instance is already associated
 * with the session, return that instance. This method never returns an uninitialized instance.)
 *
 * @param clazz a persistent class
 * @param id an identifier
 *
 * @return a persistent instance or null
 */
public Object get(Class clazz, Serializable id);

Upvotes: 1

Related Questions