我使用的是GlassFish 4,Spring和PostgreSQL。我想将一个实体保存到数据库,但是当我尝试时,我得到一个例外:
javax.transaction.RollbackException:标记为回滚的事务。 at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:445) at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:854) at com.sun.enterprise.transaction.UserTransactionImpl.commit(UserTransactionImpl.java:212) 在org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1021) 在org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761) 在org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730) 在org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:485) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) 在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) 在org.springframework.aop.framework.CglibAopProxy $ DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653) at com.amleto.server.services.controllers.AmletoController $$ EnhancerBySpringCGLIB $$ 6d3cf30.facebookDebug() at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在java.lang.reflect.Method.invoke(Method.java:601) 在org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) 在org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) 在org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111) 在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806) 在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729) 在org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) 在org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) 在org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) 在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) 在org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) 在javax.servlet.http.HttpServlet.service(HttpServlet.java:687) 在org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) 在javax.servlet.http.HttpServlet.service(HttpServlet.java:790) 在org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) 在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344) 在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) 在org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85) 在org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) 在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) 在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160) 在org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734) 在org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673) 在com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) 在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174) 在org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415) 在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282) at com.sun.enterprise.v3.services.impl.ContainerMapper $ HttpHandlerCallable.call(ContainerMapper.java:459) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167) 在org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201) 在org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175) 在org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235) 在org.glassfish.grizzly.filterchain.ExecutorResolver $ 9.execute(ExecutorResolver.java:119) 在org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284) 在org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201) 在org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133) 在org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112) 在org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) 在org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561) 在org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112) 在org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117) 在org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access $ 100(WorkerThreadIOStrategy.java:56) 在org.glassfish.grizzly.strategies.WorkerThreadIOStrategy $ WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137) 在org.glassfish.grizzly.threadpool.AbstractThreadPool $ Worker.doWork(AbstractThreadPool.java:565) 在org.glassfish.grizzly.threadpool.AbstractThreadPool $ Worker.run(AbstractThreadPool.java:545) 在java.lang.Thread.run(Thread.java:722)
实际上这对我来说毫无意义。我甚至不知道在哪里看,因为这个消息不是很具描述性。你知道如何检索这个例外的更多信息吗?或者是什么原因可以调用它?
的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="amleto-server-model" transaction-type="JTA">
<jta-data-source>jdbc/amleto</jta-data-source>
<class>com.amleto.server.model.entities.FacebookDebug</class>
<properties>
<property name="openjpa.jdbc.Schema" value="public"/>
<property name="openjpa.TransactionMode" value="managed" />
<property name="openjpa.ConnectionFactoryMode" value="managed" />
<property name="openjpa.jdbc.DBDictionary" value="postgres" />
<!-- Log all queries performed against the database. -->
<!-- Do not use in production, this will generate a lot of output. -->
<property name="openjpa.Log" value="SQL=TRACE"/>
</properties>
</persistence-unit>
AmletoController.java:
package com.amleto.server.services.controllers;
import java.sql.Timestamp;
import java.util.GregorianCalendar;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.amleto.server.model.entities.FacebookDebug;
import com.amleto.server.services.utils.SharedEntityManager;
@Controller
public class AmletoController {
@Autowired
SharedEntityManager entityManager;
@Transactional
@ResponseBody
@RequestMapping(value = "/facebookDebug", method=RequestMethod.GET)
public String facebookDebug(@RequestParam(value="action", required=true) String action,
@RequestParam(value="userId", required=true) String userId) {
FacebookDebug fb = new FacebookDebug();
fb.setAction(action);
fb.setUserId(userId);
GregorianCalendar dateCreate = new GregorianCalendar();
fb.setDateCreate(new Timestamp(dateCreate.getTimeInMillis()));
entityManager.getEntityManager().persist(fb);
/*
int returnValue = entityManager.getEntityManager().createNativeQuery("insert into facebook_debug (action, user_id, date_create) values(?,?,current_timestamp)")
.setParameter("1", action)
.setParameter("2", userId)
.executeUpdate();
*/
return "why it doesn't work?";
}
}
FacebookDebug.java:
package com.amleto.server.model.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
/**
* The persistent class for the facebook_debug database table.
*
*/
@Entity
@Table(name="facebook_debug")
@NamedQuery(name="FacebookDebug.findAll", query="SELECT f FROM FacebookDebug f")
public class FacebookDebug implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="facebook_debug_id")
private Integer facebookDebugId;
private String action;
@Column(name="date_create")
private Timestamp dateCreate;
@Column(name="user_id")
private String userId;
public FacebookDebug() {
}
public Integer getFacebookDebugId() {
return this.facebookDebugId;
}
public void setFacebookDebugId(Integer facebookDebugId) {
this.facebookDebugId = facebookDebugId;
}
public String getAction() {
return this.action;
}
public void setAction(String action) {
this.action = action;
}
public Timestamp getDateCreate() {
return this.dateCreate;
}
public void setDateCreate(Timestamp dateCreate) {
this.dateCreate = dateCreate;
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
SharedEntityManager.java:
package com.amleto.server.services.utils;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SharedEntityManager implements ApplicationContextAware {
private static ApplicationContext _appCtx;
@PersistenceContext(name="amleto-server-model")
private EntityManager em;
private static SharedEntityManager instance;
public static SharedEntityManager getInstance() {
if(instance == null) {
instance = new SharedEntityManager();
}
return instance;
}
public EntityManager getEntityManager() {
if(this.em == null) {
this.em = _appCtx.getBean(EntityManager.class);
}
return this.em;
}
@Override
public void setApplicationContext(ApplicationContext appCtx) throws BeansException {
_appCtx = appCtx;
}
}
服务器上的JDBC连接池似乎正常工作(ping成功)。我甚至能够使用此连接从项目中的表生成JPA权限。 PS。注释代码(本机查询)会产生此错误:
org.postgresql.util.PSQLException:错误:关系&#34; facebook_debug&#34;不存在
但这个实体存在。我的数据库中的所有名称都是小写的,实体映射看起来没问题。可能是模式选择存在问题,但在配置中看起来还不错。
将此属性添加到persistence.xml后:
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
我回到了上面的堆栈跟踪中的事务回滚异常。将额外的配置添加到GlassFish日志配置后,我在异常之前获得了跟踪堆栈跟踪:
[2015-09-21T18:36:15.256 + 0200] [glassfish 4.1] [CONFIG] [] [org.eclipse.persistence.session.file:/ C:/ glassfish4 /的glassfish /域/域2 / eclipseApps /阿姆莱托服务器耳/阿姆莱托-服务器的服务-ws_war / WEB-INF / LIB /阿姆莱托 - 服务器模型-0.1.0-SNAPSHOT.jar_amleto - 服务器 - model.connection] [tid:_ThreadID = 27 _ThreadName = http-listener-1(2)] [timeMillis: 1442853375256] [levelValue:700] [[连接(DatabaseLogin( platform =&gt; PostgreSQLPlatform用户名=&gt; &#34;&#34;连接器=&GT; JNDIConnector datasource name =&gt; null))]]
[2015-09-21T18:36:15.261 + 0200] [glassfish 4.1] [CONFIG] [] [org.eclipse.persistence.session.file:/ C:/ glassfish4 /的glassfish /域/域2 / eclipseApps /阿姆莱托服务器耳/阿姆莱托-服务器的服务-ws_war / WEB-INF / LIB /阿姆莱托 - 服务器模型-0.1.0-SNAPSHOT.jar_amleto - 服务器 - model.connection] [tid:_ThreadID = 27 _ThreadName = http-listener-1(2)] [timeMillis: 1442853375261] [levelValue:700] [[已连接: ?JDBC:在PostgreSQL://本地主机/阿姆莱托日志级别= 0&安培; prepareThreshold = 5&安培; preparedStatementCacheQueries = 256&安培; preparedStatementCacheSizeMiB = 5&安培; defaultRowFetchSize = 0&安培; binaryTransfer =真安培;兼容= 9.4&安培; readOnly的=假安培; binaryTransferEnable =安培; binaryTransferDisable =安培; unknownLength = 2147483647&安培; logUnclosedConnections =假安培; disableColumnSanitiser =假安培; TCPKEEPALIVE =假安培; loginTimeout = 0&安培; connectTimeout = 0&安培;了socketTimeout = 0&安培; receiveBufferSize = -1&安培; sendBufferSize = -1&安培; useSpnego =假安培; gsslib =汽车&安培; sspiServiceClass = POSTGRES&安培; allowEncodingChanges =假安培; targetServerType =任何&安培; loadBalanceHosts =真安培; hostRecheckSeconds = 10 用户:postgres数据库:PostgreSQL版本:9.4.4驱动程序:PostgreSQL 本机驱动程序版本:PostgreSQL 9.4 JDBC4(build 1202)]]
[2015-09-21T18:36:15.582 + 0200] [glassfish 4.1] [INFO] [] [org.eclipse.persistence.session.file:/ C:/ glassfish4 /的glassfish /域/域2 / eclipseApps /阿姆莱托服务器耳/阿姆莱托-服务器的服务-ws_war / WEB-INF / LIB /阿姆莱托 - 服务器模型-0.1.0-SNAPSHOT.jar_amleto - 服务器 - model.connection] [tid:_ThreadID = 27 _ThreadName = http-listener-1(2)] [timeMillis: 1442853375582] [levelValue:800] [[ 文件:/ C:/glassfish4/glassfish/domains/domain2/eclipseApps/amleto-server-ear/amleto-server-services-ws_war/WEB-INF/lib/amleto-server-model-0.1.0-SNAPSHOT.jar_amleto-服务器模型 登录成功]]
[2015-09-21T18:36:15.858 + 0200] [glassfish 4.1] [FINE] [] [org.eclipse.persistence.session.file:/ C:/ glassfish4 /的glassfish /域/域2 / eclipseApps /阿姆莱托服务器耳/阿姆莱托-服务器的服务-ws_war / WEB-INF / LIB /阿姆莱托 - 服务器模型-0.1.0-SNAPSHOT.jar_amleto - 服务器 - model.sql] [tid:_ThreadID = 27 _ThreadName = http-listener-1(2)] [timeMillis: 1442853375858] [levelValue:500] [[插入facebook_debug (action,user_id,date_create)值(?,?,current_timestamp)bind =&gt; [2个参数绑定]]]
答案 0 :(得分:0)
我猜这个问题是由无法找到的表引起的,但目前我没有看到确切的原因。
您可以尝试以下操作:
在persistence.xml
:
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
它应该指示OpenJPA创建不存在的表。也许这会告诉你,桌子应该在哪里。
更新#1:
您可以尝试打印嵌套异常堆栈跟踪,如下所示:
try {
entityManager.getEntityManager().persist(fb);
} catch (Exception x) {
if (x.getCause() != null) {
x.getCause().printStackTrace();
if (x.getCause().getCause() != null) {
x.getCause().getCause().printStackTrace();
}
}
}