Java Reference
In-Depth Information
throw e;
} finally {
manager.close();
}
}
public void delete(Long courseId) {
EntityManager manager = entityManagerFactory.createEntityManager();
EntityTransaction tx = manager.getTransaction();
try {
tx.begin();
Course course = manager.find(Course.class, courseId);
manager.remove(course);
tx.commit();
} catch (RuntimeException e) {
tx.rollback();
throw e;
} finally {
manager.close();
}
}
public Course findById(Long courseId) {
EntityManager manager = entityManagerFactory.createEntityManager();
try {
return manager.find(Course.class, courseId);
} finally {
manager.close();
}
}
public List<Course> findAll() {
EntityManager manager = entityManagerFactory.createEntityManager();
try {
Query query = manager.createQuery(
"select course from Course course");
return query.getResultList();
} finally {
manager.close();
}
}
}
The entity manager factory is built by the static method createEntityManagerFactory() of
the javax.persistence.Persistence class. You have to pass in a persistence unit name defined in
persistence.xml for an entity manager factory.
In the preceding DAO methods, you first create an entity manager from the entity manager factory.
For any operation that involves database update, such as merge() and remove() , you must start a JPA
transaction on the entity manager. For read-only operations such as find() and JPA queries, there's no
need to start a transaction. Finally, you must close an entity manager to release the resources.
Search WWH ::




Custom Search