【发布时间】:2020-12-15 04:57:16
【问题描述】:
我计划通过 Spring Boot 2.1.7 在一个应用程序(一些实体 JPA 和其他 JDBC)中使用 Spring Data JPA 和 JDBC 存储库。
public interface UserRepository2 extends CrudRepository<User, Integer> {
}
@Entity
@Table(name = "userstab")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String email;
...
}
运行应用程序我收到错误:
The bean 'userRepository2', defined in null, could not be registered. A bean with that name has already been defined in null and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting **spring.main.allow-bean-definition-overriding=true**
Invalid bean definition with name 'userRepository2' defined in null: Cannot register bean definition [Root bean: class [org.springframework.data.**jpa**.repository.support.**JpaRepositoryFactoryBean**]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] for bean 'userRepository2': There is already [Root bean: class [org.springframework.data.**jdbc**.repository.support.**JdbcRepositoryFactoryBean**];
我在没有 Spring Data JDBC 的情况下尝试了 Spring Boot 测试应用程序=>没问题
我用 spring.main.allow-bean-definition-overriding=true 尝试了这个应用程序 => 没问题
因此 Spring Data 从一个存储库接口创建 2 个存储库 bean(JPA 和 JDBC),其名称为接口 (userRepository2)。 我不能为这 2 个 repo bean 设置不同的名称,不能使用 spring.main.allow-bean-definition-overriding=true。
为每个存储库/实体选择 JPA/JDBC 的最佳做法是什么?
PS:发现 @EnableJdbcRepositories 带有 basePackages 属性,但我不确定这是个好主意
【问题讨论】:
-
请提供更多信息,尤其是。用户 Data JPA 的 Repository 类,以及 Data Jdbc 和 Entity 类。
-
Repository 类由 Spring Data 自动生成
-
我尝试在一个应用程序中使用 4 个 repos(JPA, Data JPA, Jdbc, Data Jdbc),它可以工作,检查here, 4 urls to test them。
-
我想这就是为什么你的存储库 bean 没有冲突的原因:@EnableJdbcRepositories(basePackages = "com.example.demo.jdbc")
-
不相关。删除它,它仍然有效。
标签: java spring spring-boot spring-data-jpa spring-data-jdbc