我有一个需要访问MySQL数据库的JAX-RS restful服务。我试图使用CDI和实体管理器来做到这一点。但是,当我发布应用程序时,似乎正在使用不正确的持久性单元(它正在尝试连接端口1527而不是3306)。
try / catch捕获的异常是:
javax.servlet.ServletException:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504):
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception:
java.sql.SQLException:
Error in allocating a connection. Cause: Connection could not be allocated because:
java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
Error Code: 0
这是宁静的服务:
@Path("/databases")
@Stateless
public class DatabaseResource {
@PersistenceUnit(unitName = "beta.example.services")
EntityManagerFactory entityManagerFactory;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response list() {
try {
EntityManager entityManager = entityManagerFactory.createEntityManager();
Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
return Response.ok().build();
} catch (SchemaCrawlerException e) {
return Response.status(500).entity(e.getMessage()).build();
}
}
}
持久性单元(位于src / META-INF中):
<?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="beta.example.services">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/" />
<property name="javax.persistence.jdbc.user" value="test" />
<property name="javax.persistence.jdbc.password" value="test" />
</properties>
</persistence-unit>
</persistence>
任何帮助将不胜感激
答案 0 :(得分:2)
好的,可以在两种模式下配置持久性单元:RESOURCE_LOCAL和JTA 例如:
<persistence-unit name="beta.example.services" transaction-type="JTA">
VS
<persistence-unit name="beta.example.services" transaction-type="RESOURCE_LOCAL">
JTA是默认值。只有在使用“RESOURCE_LOCAL”时才会读取“javax.persistence.jdbc。*”之类的属性。使用JTA时,将使用glassfish的事务管理器。这意味着在这种情况下,您必须指定JNDI名称,如下所示:
<jta-data-source>youJNDIName</jta-data-source>
我认为可能会发生的是你使用默认的“JTA”事务类型,但由于你没有指定任何jta-datasource,它可能会尝试使用glassfish默认值(指向derby)。
Persistence unit as RESOURCE_LOCAL or JTA?
http://openejb.apache.org/jpa-concepts.html
看看你如何使用实体管理器,将transaction-type设置为RESOURCE_LOCAL似乎是你的解决方案。