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?