Springboot应用中@EntityScan和@EnableJpaRepositories的用法
在Springboot
应用开发中使用JPA
时,通常在主应用程序所在包或者其子包的某个位置定义我们的Entity
和Repository
,这样基于Springboot
的自动配置,无需额外配置,我们定义的Entity
和Repository
即可被发现和使用。但有时候我们需要定义Entity
和Repository
不在应用程序所在包及其子包,那么这时候就需要使用@EntityScan
和@EnableJpaRepositories
了。
上面提到的Entity
和Repository
指的是通过类似下面的方式定义的Entity
和Repository
:
@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
最新文章
- google你懂得
- 关于百度地图api测距显示NaN的解决方案
- Bootstrap 3学习笔记 -栅格
- ios 获得设备型号方法
- django基于正则的url匹配
- Git最佳实践
- CodeForces 706D Vasiliy&#39;s Multiset (字典树查询+贪心)
- 使用haproxy做负载均衡时保持客户端真实的IP
- OpenCV——分水岭算法
- 理想非常丰满,现实非常骨感——致WiFi通话
- angular中重要指令介绍($eval,$parse和$compile)
- JavaScript操作cookie基础分析
- 真正从零开始,TensorFlow详细安装入门图文教程!
- const 本质
- hdu多校1002 Balanced Sequence
- 使用Ubuntu的Crontab定时任务需要注意的地方
- [Windows Azure] How to Configure Cloud Services
- alsamixer + alsactl 控制放音通道
- 20145316《Java程序设计》第六周学习总结
- 分析apache日志,统计访问量
热门文章
- POJ4852 Ants
- chrome浏览器 新打开的页面覆盖当前页面
- Mac 下终端命令行之基本命令总结(持续更新)
- Hdu 3068 最长回文字串Manacher算法
- 2018-12-29-WPF-如何建立自己的-3d-gis-程序
- SDUT-3402_数据结构实验之排序五:归并求逆序数
- 详解TCP三握四挥
- JQuery--动画队列以及清空队列.stop()方法
- 开启php中短标签<;%%>;和<;??>;的方法
- idea 项目热部署设置