Java Reference
In-Depth Information
<property name="hibernate.dialect"
value="org.hibernate.dialect.DerbyDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>'
In a Java EE environment, a Java EE container is able to manage the entity manager for you and
inject it into your EJB components directly. But when you use JPA outside of a Java EE container (e.g.,
in a Java SE application), you have to create and maintain the entity manager by yourself.
Now let's implement the CourseDao interface in the jpa subpackage using JPA in a Java SE
application. Before you call JPA for object persistence, you have to initialize an entity manager factory.
The purpose of an entity manager factory is to produce entity managers for you to persist your objects.
Note To use Hibernate as the underlying JPA engine, you have to include hibernate-entitymanager.jar
and jboss-archive-browsing.jar (located in the lib/hibernate directory of the Spring installation) in your
classpath. Because Hibernate EntityManager d epends on Javassist ( http://www.jboss.org/javassis t/ ), you
also have to include javassist.jar in your classpath. If you have Hibernate installed, you should find it in the lib
directory of the Hibernate installation. Otherwise, you have to download it from its web site.
package com.apress.springenterpriserecipes.course.jpa;
...
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class JpaCourseDao implements CourseDao {
private EntityManagerFactory entityManagerFactory;
public JpaCourseDao() {
entityManagerFactory = Persistence.createEntityManagerFactory("course");
}
public void store(Course course) {
EntityManager manager = entityManagerFactory.createEntityManager();
EntityTransaction tx = manager.getTransaction();
try {
tx.begin();
manager.merge(course);
tx.commit();
} catch (RuntimeException e) {
tx.rollback();
Search WWH ::




Custom Search