简体   繁体   中英

How i can inject dependencies for spring data jpa?

I am creating Rest + Spring + Jpa demo , all are ok but when i am going to inject dependencies of CartRepository extends JpaRepository that time it shows me following error ,

    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cartServices': Unsatisfied dependency expressed through field 'cartRepository': No qualifying bean of type [com.xptraining.repository.CartRepository] found for dependency [com.xptraining.repository.CartRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xptraining.repository.CartRepository] found for dependency [com.xptraining.repository.CartRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}

My Bean Class -------------->>>

package com.xptraining.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "cart")
public class Cart {

    @Id
    @GeneratedValue
    @Column(name = "cart_id")
    private long cartId;

    @Column(name = "sku_id")
    private String skuId;

    @Column(name = "representative_id")
    private String representativeId;

    @Column(name = "quantity")
    private int quantity;

    @Column(name = "prize")
    private int prize;


    public long getCartId() {
        return cartId;
    }

    public void setCartId(long cartId) {
        this.cartId = cartId;
    }

    public String getSkuId() {
        return skuId;
    }

    public void setSkuId(String skuId) {
        this.skuId = skuId;
    }

    public String getRepresentativeId() {
        return representativeId;
    }

    public void setRepresentativeId(String representativeId) {
        this.representativeId = representativeId;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int getPrize() {
        return prize;
    }

    public void setPrize(int prize) {
        this.prize = prize;
    }




}


My Controller-------->>>

    @Controller


    @RequestMapping("/cart")
    public class CartController {



        @Autowired
        CartService cartServices;
        @RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
        public @ResponseBody Status addCart(@RequestBody Cart cart) {
            try {
                cartServices.addCart(cart);
                return new Status(1, "Cart added Successfully !");
            } catch (Exception e) {
                // e.printStackTrace();
                return new Status(0, e.toString());
            }

        }
        @RequestMapping(value = "delete/{id}", method = RequestMethod.DELETE)
        public @ResponseBody Status deleteCart(@PathVariable("id") long id) {

            try {
                cartServices.deleteCart(id);
                return new Status(1, "Cart deleted Successfully !");
            } catch (Exception e) {
                return new Status(0, "Record is not Found ");
            }

        }

        my service Impl class--------------->>>

    @Transactional
    public class CartServiceImpl implements CartService {


        @Inject
        CartRepository cartRepository;

        @Override
        public Cart addCart(Cart cart) throws Exception {
            // TODO Auto-generated method stub
            return cartRepository.save(cart);
        }
        @Override
        public void deleteCart(long id) throws Exception {
            // TODO Auto-generated method stub
            cartRepository.delete(id);
        }
    }


    My Repository------------------->>>>

    package com.xptraining.repository;

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


    @Repository
    @Transactional
    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.controller" />
      <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="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>

CartDaoImpl----------------->>>>>>

package com.xptraining.dal.impl;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.xptraining.dal.CartDao;
import com.xptraining.model.Cart;
/**
 * Cart DAL Implementation Class
 *
 * @author Harshad Kenjale
 * 
 */
public class CartDaoImpl implements CartDao {

    @Autowired
    SessionFactory sessionFactory;

    Session session = null;
    Transaction tx = null;

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

    @SuppressWarnings("unchecked")
    @Override
    public List<Cart> getCartList() throws Exception {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        List<Cart> cartList = session.createCriteria(Cart.class).list();
        tx.commit();
        session.close();
        return cartList;
    }

    /**
     * Add Cart
     * 
     * @param Cart
     * @throws Exception
     * @return boolean TRUE or FALSE
     */
    @Override
    public boolean addCart(Cart cart) throws Exception {
        // TODO Auto-generated method stub
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        session.save(cart);
        tx.commit();
        session.close();

        return false;
    }

    /**
     * Delete Cart
     * 
     * @param id
     *            Cart id
     * @throws Exception
     * @return boolean TRUE or FALSE
     */
    @Override
    public boolean deleteCart(long id) throws Exception {
        session = sessionFactory.openSession();
        Object o = session.load(Cart.class, id);
        tx = session.getTransaction();
        session.beginTransaction();
        session.delete(o);
        tx.commit();
        return false;
    }

    /**
     * Update Cart
     * 
     * @param Cart
     * @throws Exception
     * @return boolean TRUE or FALSE
     */
    @Override
    public boolean updateCart(Cart cart) throws Exception {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        session.saveOrUpdate(cart);
        tx.commit();
        session.close();

        return false;
    }
}

The issue is here:

You are trying to pass sessionFactory to entity-manager-factory-ref . This is causing the error as :

 Error creating bean with name '(inner bean)#542901d0': Unsatisfied dependency expressed through method 'createSharedEntityManager' parameter 0: Could not convert argument value of type [org.hibernate.internal.SessionFactoryImpl] to required type [javax.persistence.EntityManagerFactory]: Failed to convert value of type [org.hibernate.internal.SessionFactoryImpl] to required type [javax.persistence.EntityManagerFactory]; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.hibernate.internal.SessionFactoryImpl] to required type [javax.persistence.EntityManagerFactory]: no matching editors or conversion strategy found

To solve the issue, change your configuration file like this:

Add this bean declaration:

<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>
         </props>
      </property>
   </bean>

Then change the jpa repositories tag to point to this bean:

  <jpa:repositories base-package="com.xptraining.repository"
                  entity-manager-factory-ref="entityManagerFactoryBean"
                  transaction-manager-ref="txManager"/>

This should solve your issue.

To solve Hibernate validator issue, add this to your pom.xml file:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.0.Final</version>
    </dependency>

You can enable transactions in XML like this:

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

I believe you are missing jpa:repositories tag in you rest.xml file. This helps in looking up Spring Data repositories.

Assuming your repositories are in package com.acme.repositories the tag looks like

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

Refer to http://docs.spring.io/spring-data/jpa/docs/1.4.1.RELEASE/reference/html/jpa.repositories.html for more info.

Go with this config:

<jpa:repositories base-package="com.xptraining.repository"
                  entity-manager-factory-ref="sessionFactory"
                  transaction-manager-ref="txManager"/>

See carefully the sessionFactory and txManager .

Your current project structure is not valid. It should be

src 
  +- main
      +- java
         +- com
            +- xptraining
               +- config
               +- controller
               +- dal
               +- model
               +- repository
               +- services
  +- resources
  +- webapp
      +- META-INF
      +- WEB-INF

Please correct your project structure and build it again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM