java – Spring应用程序似乎不是持久化数据
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Spring应用程序似乎不是持久化数据,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含14755字,纯文字阅读大概需要22分钟。
内容图文
![java – Spring应用程序似乎不是持久化数据](/upload/InfoBanner/zyjiaocheng/732/f9ccbb771802468883a3bbed8cd522d3.jpg)
我正在尝试将一些内容写入我的数据库,但尽管报告“已成功完成请求”,但它仍无法正常工作.成功之后,一切似乎都运行良好,我的控制器正确地重定向我.
调试
DEBUG a.d.p.payment.PaymentServiceImpl - Requesting to persist new user'max_test@test.com'.
DEBUG a.d.p.payment.model.PaymentDAOImpl - Persisting com.app.payment.model.PaymentUser@86ceb985.
DEBUG o.s.o.j.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler - Creating new EntityManager for shared EntityManager invocation
DEBUG org.hibernate.impl.SessionImpl - opened session at timestamp: 13771737739
DEBUG o.h.e.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress
DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'redirectForm'
DEBUG o.s.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'redirectForm'; URL [/WEB-INF/jsp/redirectForm.jsp]] in DispatcherServlet with name 'payment'
DEBUG o.s.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/jsp/redirectForm.jsp] in InternalResourceView 'redirectForm'
DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
appContext.xml(根上下文)
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="username" value="test" />
<property name="password" value="test" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<!--payment_test is the name of the schema -->
<property name="url" value="jdbc:mysql://test1.com:3306/payment_test" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="payment" />
<property name="persistenceUnitManager">
<bean class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager" >
<property name="defaultDataSource" ref="dataSource" />
</bean>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<context:component-scan base-package="com.app.payment" />
<context:annotation-config />
<!-- Auto scan the components -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" />
<tx:annotation-driven />
PaymentUser
@Entity
@Table(name="PaymentUser")
public class PaymentUser {
@Id
@GeneratedValue
private int id;
...
}
PaymentService
@Transactional("transactionManager")
@Service()
public class PaymentServiceImpl implements PaymentService {
@Autowired
private PaymentDAO paymentDAO;
// ... service methods
}
付款DAO
@Repository()
public class PaymentDAOImpl implements PaymentDAO {
//@PersistenceContext(unitName="payment")
@PersistenceContext()
EntityManager em;
}
似乎它甚至没有开始交易.希望有足够的信息让某人帮助我.谢谢你的帮助.
UPDATE
获取数据工作正常.持久化(EntityManager em.persist())和删除(em.remove)不起作用.可能有正确的问题.意思是只读权限而没有写权限,但在这种情况下我应该有一个错误.
更新2
添加< aop:scoped-proxy />到我的dataSource bean,但没有变化.就像我的调试消息说的那样
DEBUG o.h.e.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress
没有交易,但我的交易应该从哪里开始?
我还检查了问题Spring: Annotation-driven Transaction Manager
但我不知道该怎么做.
新的appContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config />
<tx:annotation-driven />
<!-- Auto scan the components
<bean id="paymentDao" class="com.app.payment.model.PaymentDAOImpl" />
<bean id="paymentService" class="com.app.payment.PaymentServiceImpl" />
should do the same
-->
<context:component-scan base-package="com.appn.payment" />
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" lazy-init="false" destroy-method="close">
<aop:scoped-proxy />
<property name="username" value="user" />
<property name="password" value="pw" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://test1.com:3306/test" />
<!-- <property name="testOnBorrow" value="true" />
<property name="validationQuery" value="SELECT 1" />-->
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="payment" />
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitManager">
<bean class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager" >
<property name="defaultDataSource" ref="dataSource" />
</bean>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<!-- <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" /> -->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
<property name="packagesToScan" value="com.app.payment" />
</bean>
<tx:annotation-driven />
</beans>
更新3
试图在我的PaymentDAO em.flush()中刷新,这会导致我收到错误消息.
javax.persistence.TransactionRequiredException: no transaction is in progress at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:792)
这是:
public void flush() {
if ( !isTransactionInProgress() ) {
throw new TransactionRequiredException( "no transaction is in progress" );
}
try {
getSession().flush();
}
catch ( RuntimeException e ) {
throw convert( e );
}
}
我需要某种特殊会话吗?
还记录在我的控制器中
log.info("Is transaction active " + TransactionSynchronizationManager.isActualTransactionActive());
这导致错误…不确定为什么没有活动交易……
更新4
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Repository
public class PaymentDAOImpl implements PaymentDAO {
private final Logger log = LoggerFactory.getLogger(getClass());
//@PersistenceContext()
@PersistenceContext(unitName="payment")
EntityManager em;
@Override
public void persist(PaymentUser user) {
log.debug("Persisting {}.", user);
em.persist(user);
//em.flush();
}
@Override
public void remove(PaymentUser user) {
log.debug("Removing {}.", user);
em.remove(user);
}
@Override
public List<PaymentUser> getPaymentUsers() {
log.debug("Fetching payment users.");
return em.createQuery("FROM PaymentUser", PaymentUser.class).getResultList();
}
@Override
public PaymentUser getPaymentUserById(String userId) {
log.debug("Fetching payment users with id '{}'.",userId);
return em.createQuery(
"FROM PaymentUser WHERE userId = :userId", PaymentUser.class)
.setParameter("userId", userId).getSingleResult();
}
@Override
public void removePaymentUserById(String userId) {
log.debug("Removing payment users with id '{}'.",userId);
em.createQuery("DELETE FROM PaymentUser WHERE userId = :userId ", PaymentUser.class).
setParameter("userId", userId).executeUpdate();
}
@Override
public void mergePaymentUser(PaymentUser user) {
log.debug("Merging payment user '{}'.",user);
em.merge(user);
}
}
更新5
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springapp servlet -->
<servlet>
<servlet-name>payment</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>payment</servlet-name>
<url-pattern>/payment/*</url-pattern>
<url-pattern>/paymentExternalData</url-pattern>
<url-pattern>/paymentInternalData</url-pattern>
</servlet-mapping>
<!-- Welcome files -->
<welcome-file-list>
<welcome-file>payment.jsp</welcome-file>
<welcome-file>payment.html</welcome-file>
</welcome-file-list>
<!-- S P R I N G -->
<!-- Add Support for Spring -->
<!-- Default applicationContext location: /WEB-INF/applicationContext.xml -->
<!-- UTF-8 filter -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
更新6
支付-servlet.xml中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config />
<tx:annotation-driven />
<!-- Auto scan the components -->
<context:component-scan base-package="com.app.payment" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
appContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config />
<tx:annotation-driven />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" lazy-init="false" destroy-method="close">
<aop:scoped-proxy />
<property name="username" value="test" />
<property name="password" value="test" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://test1.com/test" />
<property name="testOnBorrow" value="true" />
<property name="validationQuery" value="SELECT 1" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="payment" />
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitManager">
<bean class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager" >
<property name="defaultDataSource" ref="dataSource" />
</bean>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
</beans>
解决方法:
确保您没有完全重复的< context:component-scan ... />两种xml配置中的元素.如果你有这个,你基本上复制了所有的bean实例.你最初拥有的是所有bean都被ContextLoaderListener加载,并且由于< tx:annotation-driven />的存在而被代理.
现在,如果你有相同的< context:component-scan ... />在你的payment-servlet.xml中,这将再次扫描所有创建另一个实例的bean,但是由于没有< tx:annotation-driven />它不会被代理,也不会应用任何交易.
现在发生的是,只要您需要一个@Service注释bean,DispatcherServlet首先会在自己的ApplicationContext中查看是否有bean来满足其需求.如果它将被使用(您当前的情况),如果没有它将查询父上下文(由ContextLoaderListener加载的那个).
您需要做的是配置ContextLoaderListener以扫描所有内容但是@Controller注释bean和DispatcherServlet仅扫描@Controller注释bean.这可以通过配置< context:component-scan ... />来完成.正确.
applicationContext.xml中
<context:component-scan base-package="com.appn.payment">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
支付-servlet.xml中
<context:component-scan base-package="com.appn.payment" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
这将为您提供事务,并且只为您的bean提供单个实例.你应该删除< tx:annotation-driven />来自payment-servlet.xml文件.
参考指南中还包含一个开放的JIRA issue.也是Spring Community Forums中解释此问题的一个主题.
内容总结
以上是互联网集市为您收集整理的java – Spring应用程序似乎不是持久化数据全部内容,希望文章能够帮你解决java – Spring应用程序似乎不是持久化数据所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。