spring-boot-starter-data-jpa 采坑记录 @EntityScan @Entity @Repository

在对一个高龄产品进行维护升级,从spring 2.X/4.X到spring的重构过程中,遇到使用spring-boot-starter-data-jpa的两个问题。问题一:Field Repository找不到bean;问题二:Hibernate查询语法异常,实体未映射。解决方案涉及@EntityScan、@Entity和@Repository的正确使用,以及模块间的Repository冲突和查询语句中的实体类名错误。
摘要由CSDN通过智能技术生成

背景

最近在负责一个老产品的维护升级工作,此产品是个高龄产品,据说已经超过了十岁,产品代码结构中有公司自研的内容(已经无人维护),有spring 2.X的版本,有spring 4.X的版本,有ibatis也有jpa。
为了降低以后维护升级工作的难度,决定对产品代码做一次重构,去掉无法维护的自研框架,升级spring,统一持久化层使用jpa。在此过程中则遇到了一些问题在此留痕,希望能帮助到大家。

遇到的问题

1. Field xxxRepository in XXX required a bean of type ‘XXXRepository’ that could not be found.

异常信息:

Description:
Field xxxRepository in XXX required a bean of type 'XXXRepository' that could not be found.
Action:
Consider defining a bean of type 'XXXRepository' in your configuration.

遇到上边的异常信息去网上找一般都会被带到package是否被扫描,@EntityScan @Entity @Repository等注解是否添加上去,但是加上@EntityScan等一些网上的解决方式又引起了一系列其他问题。

后经过分析发现&

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
spring-boot-starter-data-jpaSpring Boot 提供的一个快速开发 JPA 应用的起步依赖。它提供了一系列默认的配置和依赖,方便我们快速地使用 JPA 进行开发。 以下是入门步骤: 1. 添加依赖:在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 2. 配置数据源:在 application.properties 或 application.yml 文件中配置数据库连接信息,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 创建实体类:创建一个用于映射数据库表的实体类,例如: ```java @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // 省略 getter 和 setter 方法 } ``` 4. 创建 Repository 接口:创建一个继承 JpaRepository 接口的 Repository 接口,例如: ```java public interface UserRepository extends JpaRepository<User, Long> { } ``` 5. 使用 Repository:在业务逻辑中使用 UserRepository 进行增删改查操作,例如: ```java @Service public class UserService { @Autowired private UserRepository userRepository; public User save(User user) { return userRepository.save(user); } public User findById(Long id) { return userRepository.findById(id).orElse(null); } public List<User> findAll() { return userRepository.findAll(); } public void deleteById(Long id) { userRepository.deleteById(id); } } ``` 以上就是使用 spring-boot-starter-data-jpa 开发 JPA 应用的基本步骤。需要注意的是,该起步依赖默认使用 Hibernate 作为 JPA 的实现,因此需要添加 Hibernate 的相关依赖。同时,也可以根据需要进行自定义配置,例如配置 JPA 的缓存、事务管理等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EngineZhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值