我在使用Eclipse在动态Web项目中建立数据库连接时遇到了麻烦。我向Wildfly添加了一个数据源,因此standalone.xml如下所示:
<datasource jta="true" jndi-name="java:jboss/datasources/weathermonitor" pool-name="weathermonitor" enabled="true" use-ccm="true">
<connection-url>jdbc:postgresql://localhost:5432/weathermonitor</connection-url>
<driver-class>org.postgresql.Driver</driver-class>
<driver>postgres</driver>
<security>
<user-name>postgres</user-name>
<password>student</password>
</security>
<validation>
<validate-on-match>false</validate-on-match>
<background-validation>false</background-validation>
</validation>
<timeout>
<set-tx-query-timeout>false</set-tx-query-timeout>
<blocking-timeout-millis>0</blocking-timeout-millis>
<idle-timeout-minutes>0</idle-timeout-minutes>
<query-timeout>0</query-timeout>
<use-try-lock>0</use-try-lock>
<allocation-retry>0</allocation-retry>
<allocation-retry-wait-millis>0</allocation-retry-wait-millis>
</timeout>
<statement>
<share-prepared-statements>false</share-prepared-statements>
</statement>
</datasource>
<drivers>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>
<driver name="postgres" module="org.postgres">
<driver-class>org.postgresql.Driver</driver-class>
</driver>
</drivers>
</datasources>然后,在我的Eclipse项目中,我将JPA添加到项目方面,并对persistence.xml进行了如下修改:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
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">
<persistence-unit name="weathermonitor"
transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/weathermonitor</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
</properties>
</persistence-unit>
在Java类中,我尝试注入实体管理器:
@PersistenceContext(unitName = "weathermonitor")
private EntityManager em;然而,我最终得到了一个NullPointerException。
有人能告诉我我做错了什么吗?
发布于 2015-05-20 13:49:20
我找到了解决方案:我在EJB中实例化了DAO类,使用了“新”-operator,而不是使用@Inject注释注入它。
发布于 2015-05-14 17:51:42
由于您没有提到PostgreSQL JDBC驱动程序(它不包括在WildFly中),所以我怀疑您忘了将它作为一个模块安装。
https://stackoverflow.com/questions/30230351
复制相似问题