1

我正在尝试在 Glassfish Server 上运行 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] Unable to build EntityManagerFactory

|准备应用程序时出现异常:[PersistenceUnit: Persistence] Unable to build EntityManagerFactory org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set

这是我的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>

有什么帮助吗?

4

1 回答 1

2

在第一个片段中,使用了应用程序管理的实体管理器。当您使用 注入 Entity Manager@PersistenceContext时,这将是一个Container-Managed Entity Manager,它需要一个 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

于 2013-05-25T02:01:07.060 回答