Lars Meyer
Lars Meyer

Reputation: 1

Hibernate hql and session management

this week i learned to program hibernate and i'm not shure if my approach is the right. I read a lot of articles and every hibernate article looked a bit different. I'm using Hibernate 4, is this the right approach to get Data from my database? It's currently working, but im not shure if this is the best way :) am i missing something? Are there better/cleaner ways to get the data?

    @Autowired
private SessionFactory sessionFactory;

public List<UserFigures> getKeyFigure(int userId) {

    Session session = getSessionFactoryDw().openSession();

    String hql = "from Figures " +
                "where UserID = :userId ";

    Query query = session.createQuery(hql);
    query.setParameter("userId", userId);
    List<UserFigures> res = query.list();
    session.close();
    return res;
}

Upvotes: 0

Views: 1921

Answers (1)

JB Nizet
JB Nizet

Reputation: 691645

The main problems with your code are the non-respect of Java naming conventions, the lack of transaction, and the poor session handling code.

Given your usage of @Autowired, I guess you're using Spring. You should thus use Spring session and transaction management to have a contextual session (i.e. use sessionFactory.getCurrentSession() instead of sessionFactory.openSession()), tied to the current Spring declarative transaction.

The Spring documentation has a whole chapter dedicated to Hibernate. Read it.

Also, Figures should be named Figure.

Upvotes: 3

Related Questions