是否可以创建通用的JpaRepository接口?

时间:2018-10-15 06:42:29

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

我已经创建了这样的界面

@Repository
public interface IJpaRepositoryCustom<T> extends JpaRepository<T,Long>{
}

和服务等级

@Service
public class LOVService<T>{
    @Autowired
    private IJpaRepositoryCustom<T> jpaRepositoryCustom;
}

但是使用上面的代码,我遇到了异常

  

严重[ContainerBackgroundProcessor [StandardEngine [Catalina]]]   org.apache.catalina.core.StandardContext.listenerStart异常   发送上下文初始化事件到类的侦听器实例   [org.springframework.web.context.ContextLoaderListener]   org.springframework.beans.factory.BeanCreationException:错误   创建名称为“ IJpaRepositoryCustom”的bean:调用init   方法失败;嵌套的异常是java.lang.IllegalArgumentException:   不是托管类型:类java.lang.Object           在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1699)           在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573)处           在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)           在org.springframework.beans.factory.support.AbstractBeanFactory.lambda $ doGetBean $ 0(AbstractBeanFactory.java:317)

还有其他方法可以创建公共JPA存储库吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以这样编辑服务:

@Service
public class LOVService{

    @Autowired
    private IJpaRepositoryCustom jpaRepositoryCustom;
}

还有您的仓库:

@Repository
public interface IJpaRepositoryCustom extends JpaRepository<YourEntityClass,Long>{
}

如果您是自动装配的,则无需将参数传递给存储库。

我希望这会有所帮助。

答案 1 :(得分:0)

当我们要将自定义方法添加到所有Spring Data JPA存储库中时,我们要做的第一件事是创建一个声明自定义方法的基本接口。

1)第一步:创建基本界面

    //Annotation to exclude repository interfaces from being picked up and thus in consequence getting an instance being created.
@NoRepositoryBean  
public interface ReadOnlyRepository<T, ID extends Serializable> extends Repository<T, ID> {

    T findOne(ID id);

    List<T> findAll();

}

2)第二步:实现基本存储库接口

public interface IUserReadOnlyRepository extends ReadOnlyRepository<User,Integer> 

{
    User findById(Integer id);

    List<User> findByName(String name);

    @Query("select u from MyUser u where u.name = ?1")
    List<User> findUserByAttributeAndValueCustomQuery(String string2);   
}

3)第三步:只需自动连线到Controller / RESTController

  @RestController
    @RequestMapping("/user")
    @CrossOrigin
    //@EnableTransactionManagement
    public class UserController {

        @Autowired
        private IUserReadOnlyRepository userReadOnlyRepository;

    @RequestMapping(value = "/getUserByIdReadOnlyRepository/{id}")
    public @ResponseBody User getUserById(@PathVariable Integer id)
    { 
        User user = userReadOnlyRepository.findById(id);
        return user;

    }

注意:这对我来说非常有用!如果需要帮助,请ping我。