Migrating from Hibernate to JPA
From Foochal
Contents |
[edit]
Move from SessionFactory creation to entity manager factory using
Ejb3Configuration cfg = new Ejb3Configuration();
EntityManagerFactory emf = cfg.configure("/mypath/hibernate.cfg.xml")
.buildEntityManagerFactory(); //Create the entity manager factory
[edit]
Spring migration of SessionFactory, if needed
Original:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="configurationClass"> <value>org.hibernate.cfg.AnnotationConfiguration</value> </property> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> </bean>
[edit]
Migrating java code
| Old | New |
| SessionFactory.openSession() | EntityManagerFactory.createEntityManager() |
| Session.getNamedQuery() | EntityManager.createNameQuery() |
| Query.list() | Query.getResultList() |
| Query.setString() | Query.setParameter() |
| Query.uniqueResult() | Query.getSingleResult() |
| Session.saveOrUpdate() | EntityManager.persist() |
| Query.setParameterList() | Query.setParameter() |
| Session.createCriteria() | EntityManager.createQuery() |
| Session.createSQLQuery() | Session.createNativeQuery() |
| Session.update() | EntityManager.merge() |
| Session.saveOrUpdate()
http://forum.springframework.org/showthread.php?t=36064 copies the newly managed persistent state onto the object passed | EntityManager.merge()
does not copy the newly managed persistent state onto the object passed.
The merge operation is clever enough to automatically detect whether the merging of the detached instance has to result in an insert or update. |
[edit]
Migrate hibernate.cfg.xml to persistence.xml
The mapping from hibernate.cfg.xml to persistence.xml is pretty straightforward, here's a sample persistence.xml
<?xml version='1.0' encoding='utf-8'?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="manager1"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:comp/env/jdbc/MyDataSource</jta-data-source> <class> org.foochal.Employee </class> </persistence-unit> </persistence>
You need to put your persistence.xml where it can be looked up by the classpath resource name:
META-INF/persistence.xml
I had to put it in
WEB-INF/classes/META-INF/persistence.xml
..and only then the classloader was able to pick it up

