Search code examples
javaspringspring-bootspring-data-jpaspring-data-jdbc

BeanDefinitionOverrideException, Spring Data JPA and JDBC beans conflict


I planned to use Spring Data JPA and JDBC repositories in one application (some entities JPA and other JDBC) with Spring Boot 2.1.7.

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;

    ...
}

Running application I got the error:

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**]; 

I tried Spring Boot test-application without Spring Data JDBC => no problems

I tried this application with spring.main.allow-bean-definition-overriding=true => no problems

So Spring Data creates 2 repository beans (JPA and JDBC) from one repository interface with the name of interface (userRepository2). I can't set different names for this 2 repo beans, can't use spring.main.allow-bean-definition-overriding=true.

What are the best practices for choosing JPA/JDBC for every repository/entity?

PS: found @EnableJdbcRepositories with basePackages property, but i am not sure that it is a good idea


Solution

  • This is almost certainly due to a fixed bug in older versions of Spring Data JDBC. Make sure that you have at least one of the following versions of spring-data-jdbc

    1.0.12 1.1.1 2.0.0

    See DATAJDBC-437 for details.