Springboot应用中的注解 @EntityScan @EnableJpaRepositories

一、pandas是什么?

Springboot应用开发中使用JPA时,通常在 程序启动类 所在包或者其子包的某个位置定义我们的EntityRepository,这样基于Springboot的自动配置,无需额外配置,我们定义的Entity和Repository即可被发现和使用。

但有时候我们需要定义Entity和Repository不在应用程序所在包及其子包,那么这时候就需要使用@EntityScan@EnableJpaRepositories了。

二、使用步骤

@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 用来扫描和发现指定包及其子包中的 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.

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值