我正在尝试在Glassfish服务器上运行Web应用程序。当我的DAO像这样编码时,我的测试页面没有问题。我可以让所有客户在数据表上看到它们。
@Stateful
public class CustomersDao {
static EntityManagerFactory emf;
static EntityManager em;
public List<Customers> getAllCustomers() {
emf = Persistence.createEntityManagerFactory("Persistence");
em = emf.createEntityManager();
TypedQuery<Customers> query = em.createQuery("SELECT c FROM Customers c", Customers.class);
List<Customers> allCustomers = query.getResultList();
System.out.println(allCustomers);
System.out.println(allCustomers.get(0).getCountry());
return allCustomers;
}
}
但是,当我将课程改为:
时@Stateful
public class CustomersDao {
@PersistenceContext(unitName = "Persistence")
EntityManager em;
public List<Customers> getAllCustomers() {
TypedQuery<Customers> query = em.createQuery("SELECT c FROM Customers c", Customers.class);
List<Customers> allCustomers = query.getResultList();
System.out.println(allCustomers);
System.out.println(allCustomers.get(0).getCountry());
return allCustomers;
}
}
我得到: javax.persistence.PersistenceException:[PersistenceUnit:Persistence]无法构建EntityManagerFactory
|准备应用程序时出现异常:[PersistenceUnit:Persistence]无法构建EntityManagerFactory org.hibernate.HibernateException:当'hibernate.dialect'未设置时,Connection不能为null
这是我的persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Persistence">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.tugay.maythirty.model.Customers</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/sampleapplication"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="passsssss"/>
</properties>
</persistence-unit>
</persistence>
任何帮助?
答案 0 :(得分:2)
在第一个代码段中,使用了应用程序管理的实体管理器。使用@PersistenceContext
注入实体管理器时,这将是容器管理的实体管理器,它需要JTA数据源。因此,您应该在Glassfish服务器中创建一个数据源,比如名为myJtaDataSource
,然后您的persistence.xml
应如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Persistence">
<jta-data-source>myJtaDataSource</jta-data-source>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.tugay.maythirty.model.Customers</class>
</persistence-unit>
</persistence>
请看这里使用Glassfish创建数据源: http://itsolutionsforall.com/datasource_jpa.php