我有一個需要訪問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
這裏是RESTful服務:
@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>
任何幫助,將不勝感激
我會檢查數據庫連接。您是否可以使用任何其他JDBC工具(如DbVisualizer)從與應用程序相同的機器連接到數據庫? – DRCB
我目前在同一臺機器上運行應用程序並且能夠連接。我最初使用eclipse嚮導進行設置(並且仍可以ping數據庫)。奇怪的部分是,它甚至不像它試圖連接到正確的數據庫。它試圖連接1527端口(我相信這是德比)。我還檢查了發佈時,persistence.xml文件存在於'/ WEB-INF/classes/META-INF' –
哪個應用服務器?你在服務器配置中配置了數據源嗎? – zeller