【发布时间】:2015-07-09 09:14:14
【问题描述】:
我正在尝试在 Java SE 应用程序中使用 Hibernate 开始使用 ORM。我读过现代方法是使用 JPA,然后使用 Hibernate 作为持久性提供程序。但是,我的 EntityManager 为空:
依赖:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
</dependency>
实体:
annotated with annotations form javax.persistence
使用数据库:
public class PersistenceManager {
private static EntityManagerFactory emFactory;
private PersistenceManager() {
emFactory = Persistence.createEntityManagerFactory("pers-unit"); // defined in a persistence.xml
}
public static EntityManager getEntityManager() {
return emFactory.createEntityManager();
}
public static void close() {
emFactory.close();
}
}
然后:
String sql = "SELECT m FROM table m WHERE m.id = :id";
EntityManager em = PersistenceManager.getEntityManager();
em.getTransaction().begin();
Query q = em.createQuery(sql);
q.setParameter("id", key);
Content result = (Content) q.getSingleResult();
em.getTransaction().commit();
em.close();
PersistenceManager.close();
return result;
persistence.xml:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="pers-unit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/dbdb" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="validate" />
</properties>
</persistence-unit>
</persistence>
这是现在的方法吗?我看到的大多数教程都使用 SessionFactory 和 hibernate 中的事务。
我看了 2014 年的一本书,它使用了这个:
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistryBuilder srBuilder = new ServiceRegistryBuilder();
srBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = srBuilder.buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
其中已经有一些已弃用的代码。
这样做的方法是什么?
【问题讨论】: