Java Reference
In-Depth Information
public List<Course> findAll() {
Session session = sessionFactory.openSession();
try {
Query query = session.createQuery("from Course");
return query.list();
} finally {
session.close();
}
}
}
The first step in using Hibernate is to create a Configuration object and ask it to load the Hibernate
configuration file. By default, it loads hibernate.cfg.xml from the classpath root when you call the
configure() method. Then you build a Hibernate session factory from this Configuration object. The
purpose of a session factory is to produce sessions for you to persist your objects.
In the preceding DAO methods, you first open a session from the session factory. For any operation
that involves database update, such as saveOrUpdate() and delete() , you must start a Hibernate
transaction on that session. If the operation completes successfully, you commit the transaction.
Otherwise, you roll it back if any RuntimeException happens. For read-only operations such as get()
and HQL queries, there's no need to start a transaction. Finally, you must remember to close a session
to release the resources held by this session.
You can create the following Main class to test run all the DAO methods. It also demonstrates an
entity's typical life cycle.
package com.apress.springenterpriserecipes.course;
...
public class Main {
public static void main(String[] args) {
CourseDao courseDao = new HibernateCourseDao();
Course course = new Course();
course.setTitle("Core Spring");
course.setBeginDate(new GregorianCalendar(2007, 8, 1).getTime());
course.setEndDate(new GregorianCalendar(2007, 9, 1).getTime());
course.setFee(1000);
courseDao.store(course);
List<Course> courses = courseDao.findAll();
Long courseId = courses.get(0).getId();
course = courseDao.findById(courseId);
System.out.println("Course Title: " + course.getTitle());
System.out.println("Begin Date: " + course.getBeginDate());
System.out.println("End Date: " + course.getEndDate());
System.out.println("Fee: " + course.getFee());
courseDao.delete(courseId);
}
}
Search WWH ::




Custom Search