如何使用JPA事务管理器而不是hibernate事务管理器?

时间:2017-03-14 09:26:15

标签: spring hibernate spring-data spring-data-jpa

我想启用我的jpa事务管理器目前我正在使用hibernate事务管理器我想使用jpa而不是hibernate,以下是我的rest.xml文件请告诉我如何在以下文件中使用它。

rest.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:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 

  xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd  
  http://www.springframework.org/schema/data/jpa 
  http://www.springframework.org/schema/data/jpa/spring-jpa.xsd


  http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa 
    http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.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:component-scan base-package="com.xptraining" />


<!-- Enable annotation driven transaction management --> 

<jpa:repositories base-package="com.xptraining.repository"/>



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

</bean> 
    <tx:annotation-driven />

<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <!-- This makes /META-INF/persistence.xml is no longer necessary -->
      <property name="packagesToScan" value="com.xptraining.model" />
      <!-- JpaVendorAdapter implementation for Hibernate EntityManager.
           Exposes Hibernate's persistence provider and EntityManager extension interface -->
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      </property>
      <property name="jpaProperties">
         <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
         </props>
      </property>
   </bean>
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/training" />
        <property name="username" value="root" />
        <property name="password" value="xpointers" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.xptraining.model.Product</value>
                <value>com.xptraining.model.Specialties</value>
                <value>com.xptraining.model.Representative</value>
                <value>com.xptraining.model.Cart</value>
                <value>com.xptraining.model.Sku</value>
                <value>com.xptraining.model.Order</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            </props>
        </property>
    </bean>
    <bean id="txManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
<!-- <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="txManager" />
</bean> -->


    <bean id="persistenceExceptionTranslationPostProcessor"
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <bean id="dataDao" class="com.xptraining.dal.impl.DataDaoImpl"></bean>
    <bean id="dataServices" class="com.xptraining.services.impl.DataServicesImpl"></bean>
    <bean id="specialtiesDao" class="com.xptraining.dal.impl.SpecialtiesDaoImpl"></bean>
    <bean id="specialtiesServices" class="com.xptraining.services.impl.SpecialtiesServicesImpl"></bean>
    <bean id="representativeDao" class="com.xptraining.dal.impl.RepresentativeDaoImpl"></bean>
    <bean id="representativeService" class="com.xptraining.services.impl.RepresentativeServiceImpl"></bean>
    <bean id="skuDao" class="com.xptraining.dal.impl.SkuDaoImpl"></bean>
    <bean id="skuServices" class="com.xptraining.services.impl.SkuervicesImpl"></bean>
    <bean id="cartDao" class="com.xptraining.dal.impl.CartDaoImpl"></bean>
    <bean id="cartServices" class="com.xptraining.services.impl.CartServiceImpl"></bean>
    <bean id="orderDao" class="com.xptraining.dal.impl.OrderDaoImpl"></bean>
    <bean id="orderServices" class="com.xptraining.services.impl.OrderServicesImpl"></bean>

</beans> 

Dal Layer

package com.xptraining.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.xptraining.model.Cart;


@Repository
public interface CartRepository extends JpaRepository<Cart, Long>
{

Cart findOneBySkuId(int skuId);
}

控制器

package com.xptraining.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xptraining.model.Cart;
import com.xptraining.model.Status;
import com.xptraining.services.CartService;
/**
 * The Cart Controller Class
 * 
 * @author Harshad Kenjale
 *
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    CartService cartServices;

    /**
     * Get All records in Cart
     *  
     * @return All Cart List
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public @ResponseBody List<Cart> getCart() {

        List<Cart> cartList = null;
        try {
            cartList = cartServices.getCartList();
if(cartList.isEmpty())
{
    System.out.println("List is empty ");
}
        } catch (Exception e) {
            e.printStackTrace();
        }

        return cartList;
    }
    /**
     * Add Cart
     * 
     * @param representative
     * @return Status
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Status addCart(@RequestBody Cart cart) {
        System.out.println("i m from jpa controller");
        try {
            cartServices.save(cart);
            return new Status(1, "Cart added Successfully !");
        } catch (Exception e) {
            // e.printStackTrace();
            return new Status(0, e.toString());
        }

    }


service Interface ---



 package com.xptraining.services;

    import java.util.List;

    import com.xptraining.model.Cart;
    /**
     * The Cart Service Layer Interface
     * 
     * @author Harshad Kenjale
     *
     */
    public interface CartService {

        public List<Cart> getCartList() throws Exception;

        public Cart save(Cart Cart) throws Exception;

        public void delete(long id) throws Exception;

    /*  public boolean updateCart(Cart cart) throws Exception;
    */
        }

service impl class

package com.xptraining.services.impl;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xptraining.model.Cart;
import com.xptraining.repository.CartRepository;
import com.xptraining.services.CartService;

/**
 * Cart Services Implementation Class
 *
 * @author Harshad Kenjale
 * 
 */
@Service
public class CartServiceImpl implements CartService {

    @Inject
    CartRepository cartRepository;


    @Override
    @Transactional
    public List<Cart> getCartList() throws Exception {
        // TODO Auto-generated method stub
        return (List<Cart>) cartRepository.findAll();
    }

    /**
     * Add Cart
     * 
     * @param cart
     * @throws Exception
     * @return Boolean
     */
    @Override
    @Transactional
    public Cart save(Cart cart) throws Exception {
        System.out.println("i m from jpa Service");

        Cart cart1 = cartRepository.save(cart);
        return cart1;
    }

错误-----------

SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/rest.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type [org.springframework.orm.jpa.JpaTransactionManager] to required type [javax.persistence.EntityManagerFactory] for property 'entityManagerFactory'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.orm.jpa.JpaTransactionManager] to required type [javax.persistence.EntityManagerFactory] for property 'entityManagerFactory': no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type [org.springframework.orm.jpa.JpaTransactionManager] to required type [javax.persistence.EntityManagerFactory] for property 'entityManagerFactory'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.orm.jpa.JpaTransactionManager] to required type [javax.persistence.EntityManagerFactory] for property 'entityManagerFactory': no matching editors or conversion strategy found
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:591)
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:603)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:216)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1486)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    ... 35 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [org.springframework.orm.jpa.JpaTransactionManager] to required type [javax.persistence.EntityManagerFactory] for property 'entityManagerFactory': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:306)
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:576)
    ... 41 more

Mar 14, 2017 4:40:14 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet mvc-dispatcher
java.lang.IllegalStateException: Cannot convert value of type [org.springframework.orm.jpa.JpaTransactionManager] to required type [javax.persistence.EntityManagerFactory] for property 'entityManagerFactory': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:306)
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:576)
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:603)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:216)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1486)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

0 个答案:

没有答案