Java持久性 - 创建查询失败

时间:2014-02-06 20:00:56

标签: java jpa persistence

我正在尝试编写我的第一个JPA Web应用程序而且卡住了。我有以下代码:

@Stateless
public class TestDAO {

    @PersistenceContext(unitName="dbcon")    
    EntityManager em;

    public TestDAO() {

    }

    public TestCon getData() {
        Query qry = em.createQuery("select t from TestCon t");
        ...

最后一行失败 - “java.lang.NullPointerException”。 TestCon代码是:

@Entity
@Table(name = "testcon", schema = "C##test")
public class TestCon {


    @Id
    @Column(name = "a")
    private int a;

    @Column(name = "b", length = 20)
    private String b;

    public String getB() {
        return b;
    }
}

和persistence.xml代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 
    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_2_0.xsd">
    <persistence-unit name="dbcon" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:/jboss/datasources/OracleDS</jta-data-source>
        <class>code.TestCon</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"/>
        </properties>
     </persistence-unit>
 </persistence>

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:1)

@PersistenceContext注释仅适用于Java EE容器。您正在运行哪个应用服务器?

如果您没有运行Java EE容器而只是像Tomcat这样的servlet容器,则需要使用EntityManager创建EntityManagerFactory.createEntityManager()