0

I was going through some old code and noticed that if I wanted to retrieve object from database I just used:

Session session=mainApp.getSessionFactory().openSession();
session.beginTransaction();
State newState=(State) session.get(State.class, state);
todoHistory.setState(newState);
session.update(todoHistory);
session.getTransaction().commit();
session.close();

Now I would use something like:

Session sess = mainApp.getSessionFactory().openSession();
System.out.println("Session opened!");
Transaction tx = null;
try {
    tx = session.beginTransaction();
    CriteriaBuilder builder = session.getCriteriaBuilder();
    CriteriaQuery<State> query = builder.createQuery(State.class);
    Root<State> root = query.from(State.class);
    query.select(root);
    List allStates = session.createQuery(query).list();
    tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback();
    System.out.println(e);
    throw e;
}
finally {
    sess.close();
    System.out.println("Session closed!");
}

Please, don't pay attention that there are no try/catch block in first code block. I'm interested if building a Criteria is needed if you want to retrieve object from database, or example from 1st block is correct? Also, if I retrieved object from database and passed it to other function can I update it there, or should retrieving and update be made only in same session?

Alyona
  • 1,682
  • 2
  • 21
  • 44
  • 2
    using `Criteria` for a simple `select all` is a total overkill. first example should work fine – XtremeBaumer Sep 04 '17 at 13:05
  • Take a look at HQL https://www.mkyong.com/hibernate/hibernate-query-examples-hql/ – Nikolaj Hansen Sep 04 '17 at 13:06
  • Using Criteria does not provide any new functionality over simple queries but the code is more object oriented and possibly more readable. Using Criteria can also have performance issues because oftentimes the generated queries are suboptimal. – dsp_user Sep 04 '17 at 13:09

0 Answers0