Spring - JPA - 读取工作,但坚持给我没有事务性的EntityManager可用。为什么? [英] Spring - JPA - Reads work but persist give me No transactional EntityManager available. Why?

查看:80
本文介绍了Spring - JPA - 读取工作,但坚持给我没有事务性的EntityManager可用。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Spring和JPA构建一个应用程序。我的阅读功能正在工作,但当我尝试保存任何对象时,我收到了异常没有事务性的EntityManager可用



这是我的网页。 xml文件:

 <?xml version =1.0encoding =UTF-8?> 
< web-app version =2.5xmlns =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>

<! - 所有Servlet共享的Root Spring容器的定义
和Filters - >
< context-param>
< param-name> contextConfigLocation< / param-name>
< param-value> /WEB-INF/spring/root-context.xml,/WEB-INF/spring/webservices-context.xml,/WEB-INF/spring/security-context.xml< / PARAM值>

< / context-param>

<! - 创建所有Servlet和过滤器共享的Spring容器 - >
< listener>
< listener-class> org.springframework.web.context.ContextLoaderListener< / listener-class>
< / listener>

< filter>
< filter-name> springSecurityFilterChain< / filter-name>
< filter-class> org.springframework.web.filter.DelegatingFilterProxy< / filter-class>
< / filter>

< filter-mapping>
< filter-name> springSecurityFilterChain< / filter-name>
< url-pattern> / *< / url-pattern>
< / filter-mapping>

< mime-mapping>
< extension> js< / extension>
< mime-type> application / x-javascript< / mime-type>
< / mime-mapping>
< mime-mapping>
< extension>属性< / extension>
< mime-type> application / text< / mime-type>
< / mime-mapping>


<! - 处理应用程序请求 - >
< servlet>
< servlet-name> appServlet< / servlet-name>
< servlet-class> org.springframework.web.servlet.DispatcherServlet< / servlet-class>
< init-param>
< param-name> contextConfigLocation< / param-name>
< param-value> /WEB-INF/spring/appServlet/servlet-context.xml< / param-value>
< / init-param>
1< / load-on-startup>
< / servlet>

< servlet-mapping>
< servlet-name> appServlet< / servlet-name>
< url-pattern> /< / url-pattern>
< / servlet-mapping>

< / web-app>

以下是我的spring / appServlet / servlet-context.xml:

 <?xml version =1.0encoding =UTF-8?> 
< beans:beans xmlns =http://www.springframework.org/schema/mvc
xmlns:xsi =http://www.w3.org/2001/XMLSchema-instance
xmlns:beans =http://www.springframework.org/schema/beans
xmlns:context =http://www.springframework.org/schema/context
xsi:schemaLocation =http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework。 org / schema / beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org /schema/context/spring-context.xsd\">

<! - DispatcherServlet上下文:定义这个servlet的请求处理基础结构 - >

<! - 启用Spring MVC @Controller编程模型 - >
< annotation-driven />

< beans:bean id =placeholderConfigclass =org.springframework.beans.factory.config.PropertyPlaceholderConfigurer>
< beans:property name =locationvalue =classpath:resources.properties>< / beans:property>
< / beans:bean>

<! - 通过高效地提供$ {webappRoot} / resources目录中的静态资源来处理/ resources / **的HTTP GET请求 - >
< resources mapping =/ **location =$ {resources.base},$ {resources.modules},$ {resources.lib},$ {resources.apps}/> <! - extjs和Designer的资源映射到/ - >
< resources mapping =/ resources / **location =$ {resources.resources}/>

<! - 解析@Controllers为/ WEB-INF / views目录中的.jsp资源选择渲染的视图 - >
< beans:bean class =org.springframework.web.servlet.view.InternalResourceViewResolver>
< beans:property name =prefixvalue =/ WEB-INF / views //>
< beans:property name =suffixvalue =。jsp/>
< / beans:bean>

< context:component-scan base-package =com.app.webapp/>
< / beans:beans>

这是我的spring / root-context.xml:

 <?xml version =1.0encoding =UTF-8standalone =no?> 
< beans xmlns =http://www.springframework.org/schema/beans
xmlns:mvc =http://www.springframework.org/schema/mvc
xmlns:p =http://www.springframework.org/schema/pxmlns:tx =http://www.springframework.org/schema/tx
xmlns:context =http: //www.springframework.org/schema/context
xmlns:aop =http://www.springframework.org/schema/aop
xmlns:xsi =http:// www。 w3.org/2001/XMLSchema-instance
xsi:schemaLocation =http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/ spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http:// www .springframework.org / schema / mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframe work.org/schema/context/spring-context-3.0.xsd\">

<! - 根上下文:定义对所有其他Web组件可见的共享资源 - >
< context:annotation-config />

< bean id =viewResolver
class =org.springframework.web.servlet.view.InternalResourceViewResolver>
< property name =prefixvalue =/ WEB-INF / views //>
< property name =suffixvalue =。jsp/>
< / bean>

class =org.springframework.jdbc.datasource.DriverManagerDataSource
p:driverClassName =com.mysql.jdbc.Driverp :url =jdbc:mysql:// localhost / schema1
p:username =user1p:password =741147>
< / bean>

< bean id =entityManagerFactory
class =org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean>
< property name =dataSourceref =appDS/>
< property name =jpaVendorAdapter>
< bean class =org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter/>
< / property>
< / bean>

< bean id =transactionManagerclass =org.springframework.orm.jpa.JpaTransactionManager>
< property name =entityManagerFactoryref =entityManagerFactory/>
< / bean>

< tx:注解驱动的事务管理器=transactionManager/>

< bean id =persistenceExceptionTranslationPostProcessor
class =org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor/>
< context:spring-configured />
< context:annotation-config />
< / beans>

这是我的persistence.xml:

 <?xml version =1.0encoding =UTF-8?> 
< persistence version =2.0xmlns =http://java.sun.com/xml/ns/persistencexmlns:xsi =http://www.w3.org/2001/XMLSchema-实例xsi:schemaLocation =http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">
< persistence-unit name =myPUtransaction-type =JTA>
< provider> org.hibernate.ejb.HibernatePersistence< / provider>
<属性>
< property name =hibernate.dialectvalue =org.hibernate.dialect.MySQLDialect/>
< property name =hibernate.transaction.auto_close_sessionvalue =false/>
< property name =hibernate.show_sqlvalue =true/>
< property name =hibernate.format_sqlvalue =false/>
< property name =hibernate.generate_statisticsvalue =false/>
< property name =hibernate.connection.autocommitvalue =true/>
<! - < property name =hibernate.hbm2ddl.autovalue =update/> - >
< property name =hibernate.query.jpaql_strict_compliancevalue =false/>
< property name =hibernate.transaction.jta.platformvalue =org.hibernate.service.jta.platform.internal.SunOneJtaPlatform/>
< property name =hibernate.connection.driver_classvalue =com.mysql.jdbc.Driver/>
< / properties>
< / persistence-unit>
< /余辉>

这是我的DaoImpl.java:

  import java.util.ArrayList; 
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

导入javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

导入org.slf4j.Logger;
导入org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.app.webapp.data.dao.impl.GenericDaoImpl;
import com.app.webapp.data.dao.interfaces.security.IUserDao;
import com.app.webapp.data.domains.entities.Account;
import com.app.webapp.data.domains.entities.security.AccessPrivilege;
import com.app.webapp.data.domains.entities.security.ActiveSession;
import com.app.webapp.data.domains.entities.security.Process;
import com.app.webapp.data.domains.entities.security.Profile;
import com.app.webapp.data.domains.entities.security.User;
import com.app.webapp.data.exceptions.DuplicatedUserException;
import com.app.webapp.data.exceptions.UserAlreadyHasAnAccountException;
import com.app.webapp.data.exceptions.UserNotFoundException;

@Repository(userDao)
@Transactional
public class UserDaoImpl implements IUserDao {

@PersistenceContext(unitName =myPU)
protected EntityManager entityManager;

public UserDaoImpl(){
super(User.class);

$ b @Override
@Transactional(readOnly = false,propagation = Propagation.REQUIRES_NEW)
public void save(User user)throws DuplicatedUserException {
logger.info(使用用户名创建用户名:+ user.getUsername());
User foundUser = null;
logger.info(检查用户是否已经存在...);
entityManager.persist(user);
logger.info(User+ user.getUsername()+已成功保存!);


$ b $ / code $ / pre

然后持续用户的行是


javax.persistence.TransactionRequiredException:没有事务性的EntityManager可用




但我不明白为什么我可以从数据库获取数据,但我无法写入。我不知道servlet上下文中是否有任何内容,并且不与其他上下文共享。有人可以帮助我吗?

解决方案

您是否提供了 @Transactional @Service 或服务层类?如果是,请检查您的 hibernet / entityManager.jar 版本兼容性。


I am building an application with spring and JPA. My read functions are working but when i try to save any objects, i get the exception No transactional EntityManager available.

Here is my web.xml file:

<?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">

    <!-- The definition of the Root Spring Container shared by all Servlets 
        and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml,/WEB-INF/spring/webservices-context.xml,/WEB-INF/spring/security-context.xml</param-value>

    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <mime-mapping>
        <extension>js</extension>
        <mime-type>application/x-javascript</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>properties</extension>
        <mime-type>application/text</mime-type>
    </mime-mapping>


    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

Here is my spring/appServlet/servlet-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <beans:bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location" value="classpath:resources.properties"></beans:property>
    </beans:bean>

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/**" location="${resources.base},  ${resources.modules}, ${resources.lib}, ${resources.apps}" /> <!-- resource mapp for extjs and Designer to / -->
    <resources mapping="/resources/**" location="${resources.resources}" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.app.webapp" />
</beans:beans>

Here is my spring/root-context.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->
    <context:annotation-config />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="appDS"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost/schema1"
        p:username="user1" p:password="741147">
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="appDS" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="persistenceExceptionTranslationPostProcessor"
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
    <context:spring-configured />
    <context:annotation-config />
</beans>

Here is my 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="myPU" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
      <property name="hibernate.transaction.auto_close_session" value="false"/>
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.format_sql" value="false"/>
      <property name="hibernate.generate_statistics" value="false"/>
      <property name="hibernate.connection.autocommit" value="true"/>
<!--       <property name="hibernate.hbm2ddl.auto" value="update"/> -->
      <property name="hibernate.query.jpaql_strict_compliance" value="false"/>
      <property name="hibernate.transaction.jta.platform"  value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
      <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
    </properties>
  </persistence-unit>
</persistence>

Here is my DaoImpl.java:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.app.webapp.data.dao.impl.GenericDaoImpl;
import com.app.webapp.data.dao.interfaces.security.IUserDao;
import com.app.webapp.data.domains.entities.Account;
import com.app.webapp.data.domains.entities.security.AccessPrivilege;
import com.app.webapp.data.domains.entities.security.ActiveSession;
import com.app.webapp.data.domains.entities.security.Process;
import com.app.webapp.data.domains.entities.security.Profile;
import com.app.webapp.data.domains.entities.security.User;
import com.app.webapp.data.exceptions.DuplicatedUserException;
import com.app.webapp.data.exceptions.UserAlreadyHasAnAccountException;
import com.app.webapp.data.exceptions.UserNotFoundException;

    @Repository("userDao")
    @Transactional
    public class UserDaoImpl implements IUserDao {

    @PersistenceContext(unitName = "myPU")
        protected EntityManager entityManager;

        public UserDaoImpl() {
            super(User.class);
        }

        @Override
        @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
        public void save(User user) throws DuplicatedUserException {
            logger.info("Creating User with username: " + user.getUsername());
            User foundUser = null;
            logger.info("Checking if user already existis...");
            entityManager.persist(user);
            logger.info("User " + user.getUsername() + " was been saved with success!");

        }
    }

Then the line to persist user is executed, I got the exception:

javax.persistence.TransactionRequiredException: No transactional EntityManager available

But I can't understand why I can get data from db but I cannot write. I don't know if is anything in the servlet context and isn't shared with others contexts. Someone can help me?

解决方案

Have you provide the @Transactional Annotation in @Service or service layer class? if yes then check your hibernet/entityManager.jar version compatibility.

这篇关于Spring - JPA - 读取工作,但坚持给我没有事务性的EntityManager可用。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆