zoukankan      html  css  js  c++  java
  • Springboot应用中@EntityScan和@EnableJpaRepositories的用法

    Springboot应用开发中使用JPA时,通常在主应用程序所在包或者其子包的某个位置定义我们的EntityRepository,这样基于Springboot的自动配置,无需额外配置,我们定义的EntityRepository即可被发现和使用。但有时候我们需要定义EntityRepository不在应用程序所在包及其子包,那么这时候就需要使用@EntityScan@EnableJpaRepositories了。

    上面提到的EntityRepository指的是通过类似下面的方式定义的EntityRepository :

    @Entity
    @Table(name = "grade")
    public class Grade {
       // 省略具体内容
    }
    
    @Repository
    public interface GradeRepository extends JpaRepository<Grade, Long>, JpaSpecificationExecutor<Grade> {
       // 省略具体内容
    }
    

    @EntityScan

    @EntityScan用来扫描和发现指定包及其子包中的Entity定义。其用法如下:

    @EntityScan(basePackages = {"com.department.entities","come.employee.entities"})
    

    如果多处使用@EntityScan,它们的basePackages集合能覆盖所有被Repository使用的Entity即可,集合有交集也没有关系。但是如果不能覆盖被Repository使用的Entity,应用程序启动是会出错,比如:

    Not a managed type: com.customer.entities.Customer

    @EnableJpaRepositories

    @EnableJpaRepositories用来扫描和发现指定包及其子包中的Repository定义。其用法如下:

    @EnableJpaRepositories(basePackages = {"com.department.repositories","come.employee.repositories"})
    

    如果多处使用@EnableJpaRepositories,它们的basePackages集合不能有交集,并且要能覆盖所有需要的Repository定义。

    如果有交集,相应的Repository会被尝试反复注册,从而遇到如下错误:

    The bean ‘OrderRepository’, defined in xxx, could not be registered. A bean with that name has already been defined in xxx and overriding is disabled.

    如果不能覆盖所有需要的Repository定义,会遇到启动错误:

    Parameter 0 of method setCustomerRepository in com.service.CustomerService required a bean of type ‘come.repo.OrderRepository’ that could not be found.

    原文地址:https://blog.csdn.net/andy_zhang2007/article/details/84099595
  • 相关阅读:
    java经典入门算法题,小白必备!
    java客房管理小项目,小白练手必备!
    10道java经典算法题,每一题都能提升你的java水平!第二弹!
    活动目录对象属性批量修改工具------ADModify
    CentOS7基于http方式搭建本地yum源
    如何禁用AD OU 下面的邮箱用户的Exchange ActiveSync 和 适用于设备的OWA
    通过组策略禁止有本地管理员权限的域用户更改网络配置
    1 什么是virtual Machine
    写Ansible playbook添加zabbix被监控的对象
    Windows server 安装和配置zabbix agent
  • 原文地址:https://www.cnblogs.com/jpfss/p/11127092.html
Copyright © 2011-2022 走看看