如何使用jpa Repository的save方法保存数据

时间:2017-03-14 04:58:28

标签: java spring hibernate spring-data-jpa

在将实体从服务实现类添加到Repository接口时,它显示成功消息但数据未插入数据库我从JpaRepository接口调用save(entity)方法。它没有显示任何错误消息,而是显示记录插入成功消息。

控制器--->>。

@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());
        }

    }

服务已实施类------&gt;&gt;&gt;&gt;

@Service
public class CartServiceImpl implements CartService {


    @Inject
    CartRepository cartRepository;


    /**
     * Get All Cart
     * 
     * @throws Exception
     * @return All Cart List
     */

    @Override
    @Transactional
    public List<Cart> getCartList() throws Exception {
        // TODO Auto-generated method stub
        return 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;
    }

存储库接口--------&gt;&gt;&gt;&gt;

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>
{


}

Web.xml中

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>xptraining</display-name>
  <servlet>
  <servlet-name>mvc-dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/rest.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>mvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

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

 <context:component-scan base-package="com.xptraining" />
  <jpa:repositories base-package="com.xptraining.repository"
                  entity-manager-factory-ref="entityManagerFactoryBean"
                  transaction-manager-ref="txManager"/>
 <!--  <jpa:repositories base-package="com.xptraining.repository"></jpa:repositories> -->
<!-- <jpa:repositories base-package="com.xptraining.repository"
                  entity-manager-factory-ref="cartRepository"
                  transaction-manager-ref="transactionManager"/>  -->

    <mvc: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="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>

@My控制台,当我调用save方法

10:48:55.219 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'mvc-dispatcher' processing POST request for [/xptraining/cart/create]
10:48:55.220 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /cart/create
10:48:55.220 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public com.xptraining.model.Status com.xptraining.controller.CartController.addCart(com.xptraining.model.Cart)]
10:48:55.220 [http-nio-8080-exec-10] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'cartController'
10:48:55.220 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Read [class com.xptraining.model.Cart] as "application/json" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@48e069ed]
i m from jpa controller
i m from jpa Service
10:48:55.220 [http-nio-8080-exec-10] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
10:48:55.220 [http-nio-8080-exec-10] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@23b8bcb1 updates=org.hibernate.engine.spi.ExecutableList@2d7f56b6 deletions=org.hibernate.engine.spi.ExecutableList@2940d7c1 orphanRemovals=org.hibernate.engine.spi.ExecutableList@6c425c8d collectionCreations=org.hibernate.engine.spi.ExecutableList@a793880 collectionRemovals=org.hibernate.engine.spi.ExecutableList@5d64159f collectionUpdates=org.hibernate.engine.spi.ExecutableList@72b52f2d collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@c6da3c2 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] for Hibernate transaction
10:48:55.220 [http-nio-8080-exec-10] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@23b8bcb1 updates=org.hibernate.engine.spi.ExecutableList@2d7f56b6 deletions=org.hibernate.engine.spi.ExecutableList@2940d7c1 orphanRemovals=org.hibernate.engine.spi.ExecutableList@6c425c8d collectionCreations=org.hibernate.engine.spi.ExecutableList@a793880 collectionRemovals=org.hibernate.engine.spi.ExecutableList@5d64159f collectionUpdates=org.hibernate.engine.spi.ExecutableList@72b52f2d collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@c6da3c2 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
10:48:55.220 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Obtaining JDBC connection
10:48:55.220 [http-nio-8080-exec-10] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/training]
10:48:55.223 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Obtained JDBC connection
10:48:55.223 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.transaction.spi.AbstractTransactionImpl - begin
10:48:55.223 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - initial autocommit status: true
10:48:55.223 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - disabling autocommit
10:48:55.223 [http-nio-8080-exec-10] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection@5c26bcfd]
10:48:55.224 [http-nio-8080-exec-10] DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils - Opening JPA EntityManager
10:48:55.224 [http-nio-8080-exec-10] DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils - Registering transaction synchronization for JPA EntityManager
10:48:55.224 [http-nio-8080-exec-10] DEBUG org.hibernate.loader.Loader - Loading entity: [com.xptraining.model.Cart#1]
10:48:55.224 [http-nio-8080-exec-10] DEBUG org.hibernate.SQL - select cart0_.cart_id as cart_id1_0_0_, cart0_.prize as prize2_0_0_, cart0_.quantity as quantity3_0_0_, cart0_.representative_id as represen4_0_0_, cart0_.sku_id as sku_id5_0_0_ from cart cart0_ where cart0_.cart_id=?
10:48:55.224 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Obtaining JDBC connection
10:48:55.224 [http-nio-8080-exec-10] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/training]
10:48:55.226 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Obtained JDBC connection
10:48:55.226 [http-nio-8080-exec-10] DEBUG org.hibernate.loader.Loader - Result set row: 0
10:48:55.226 [http-nio-8080-exec-10] DEBUG org.hibernate.loader.Loader - Result row: EntityKey[com.xptraining.model.Cart#1]
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.internal.TwoPhaseLoad - Resolving associations for [com.xptraining.model.Cart#1]
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.internal.TwoPhaseLoad - Done materializing entity [com.xptraining.model.Cart#1]
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.hibernate.loader.Loader - Done entity load
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Releasing JDBC connection
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Released JDBC connection
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Initiating transaction commit
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@23b8bcb1 updates=org.hibernate.engine.spi.ExecutableList@2d7f56b6 deletions=org.hibernate.engine.spi.ExecutableList@2940d7c1 orphanRemovals=org.hibernate.engine.spi.ExecutableList@6c425c8d collectionCreations=org.hibernate.engine.spi.ExecutableList@a793880 collectionRemovals=org.hibernate.engine.spi.ExecutableList@5d64159f collectionUpdates=org.hibernate.engine.spi.ExecutableList@72b52f2d collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@c6da3c2 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.transaction.spi.AbstractTransactionImpl - committing
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - committed JDBC Connection
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction - re-enabling autocommit
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@23b8bcb1 updates=org.hibernate.engine.spi.ExecutableList@2d7f56b6 deletions=org.hibernate.engine.spi.ExecutableList@2940d7c1 orphanRemovals=org.hibernate.engine.spi.ExecutableList@6c425c8d collectionCreations=org.hibernate.engine.spi.ExecutableList@a793880 collectionRemovals=org.hibernate.engine.spi.ExecutableList@5d64159f collectionUpdates=org.hibernate.engine.spi.ExecutableList@72b52f2d collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@c6da3c2 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] after transaction
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Releasing JDBC connection
10:48:55.227 [http-nio-8080-exec-10] DEBUG org.hibernate.engine.jdbc.internal.LogicalConnectionImpl - Released JDBC connection
10:48:55.228 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Written [com.xptraining.model.Status@788e053b] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@48e069ed]
10:48:55.228 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'mvc-dispatcher': assuming HandlerAdapter completed request handling
10:48:55.228 [http-nio-8080-exec-10] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request

2 个答案:

答案 0 :(得分:0)

您是否在rest.xml中添加了以下行

<repositories base-package="com.acme.repositories" />

如果没有尝试添加以上行。它将设置Spring为这些接口创建代理实例。

答案 1 :(得分:0)

您已在rest.xml中定义了Hibernate Session工厂和JPA实体管理器。只使用一个。请参阅以下答案。

Saving entity in repository does not work SPRING