Issue
I'm trying to enable Hibernate using the latest best-practices.
So I have this:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.27.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.2</version>
</dependency>
(every dependency is the latest version as of the date of posting)
and this
@Repository
public interface UserRepository extends JpaRepository<UserInfo, Long> {
}
and this:
@ContextConfiguration(locations = { "classpath:spring-backend-dao.xml" })
@EnableJpaRepositories("com.cth.orm")
@EntityScan("com.cth.orm")
public class UserRepositoryTest extends AbstractJUnit4SpringContextTests {
@Autowired private UserRepository target;
@Test
public void test() {
}
}
and so why do I get this error?
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.cth.orm.UserRepository' available: expected at least 1 bean which qualifies as autowire cand idate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Please note that when I started out I didn't have @EnableJpaRepositories
. That was added after extensive research on Google and SO, but it didn't resolve the problem.
Solution
A bit difficult to guess - so a few notes.
You don't need the Hibernate nor the spring-orm reference (included in starter-data-jpa), but you need to have you database jdbc dependency, for example:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
Not sure why you are using @ContextConfiguration - I guess you are working with Spring Boot and not with plain Spring? So you need a Configuration class like this:
@Configuration
@EntityScan(basePackages = {"com.cth.orm"})
@EnableJpaRepositories(basePackages = {"com.cth.orm"})
@EnableTransactionManagement // optional
public class DomainConfig {
}
This class should be in the main folder, it's not enough to have it in the tests.
You may try out https://bootify.io to get a running Spring Boot project with you database model, and the latest best-practices as well.
Answered By - Thomas