【发布时间】:2016-12-31 01:28:46
【问题描述】:
在将 Hibernate 实施到我的项目之前,我正在按照本教程对其进行测试:http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/
我的问题是这条指令要求 UserDAO 是一个 bean:
@Autowired
private UserDao userDao;
这不是……?我觉得我在本网站提供的示例中遗漏了一些非常重要的东西。我习惯于使用implements Serializable 实现bean,但在这种情况下不使用它。它应该如何被视为一个bean?
如果有人能向我解释我缺少什么,我将不胜感激。这种实现 CRUD 的方式以及更多仅使用接口和标准方式来声明函数看起来非常吸引人。谢谢!
编辑:下面是我的代码。当我尝试将教程提供的代码集成到我的项目中时,它不起作用,因为项目架构的差异(这是我的猜测)。
Application.java
@SpringBootApplication
@ComponentScan("boot")
@ComponentScan("dao")
@ComponentScan("modele")
@EnableJpaRepositories("org.utc.ai15")
public class Application {
public static void main (String[] args){
SpringApplication.run(Application.class, args);
}
}
TestDAO.java
@Transactional
@Component
public interface TestDAO extends CrudRepository<Test, Long > {
/**
* This method will find an User instance in the database by its email.
* Note that this method is not implemented and its working code will be
* automagically generated from its signature by Spring Data JPA.
*/
public Test findByEmail(String email);
}
我认为这就是问题所在。
我尝试将 @Component 添加到 TestDAO.java 以便使用 @ComponentScan("dao") 对其进行扫描,但它不起作用。
这是错误:
Field testDao in boot.controller.TestController required a bean of type 'dao.TestDAO' that could not be found.
编辑 2:错误是 @EnableJpaRepositories("org.utc.ai15"),正确的声明是 @EnableJpaRepositories("dao")(参见 @Alex 答案)。
【问题讨论】:
-
userDao 是一个“存储库”bean。也许您应该阅读 Spring Data JPA 文档? docs.spring.io/spring-data/jpa/docs/current/reference/html.
-
您的教程提到了这一点:“使用 Spring Data JPA,您的实体的 DAO 只需通过扩展 Spring 提供的 CrudRepository 接口来创建”。简而言之,Spring Data 只需创建一个接口即可为您提供现成的存储库。然后您可以将其作为 bean 注入并使用保存/删除/查找方法...
-
感谢您的回复。我更了解发生了什么。但是我仍然无法创建 UserDAO 的 bean。它只是不被识别为豆子。我已经用@EnableJpaRepositories 进行了注释,遵循了与文档中定义的步骤相同的教程。你知道会出什么问题吗?我明天会发布我的代码示例,但它的 UserDAO 是相同的。
-
我敢打赌这与您的包裹有关。你有一个带有主要方法的
@SpringBootApplication吗?这就是您注释@EnableJpaRepositories的地方?要么确保 UserDAO 低于 SpringBootApplication(Spring Boot 使用主类作为根来扫描 bean),要么使用@EnableJpaRepositories(basePackages="org.my.pkg")定义存储库包,或者添加@ScanPackages以定义其他包用于 bean 发现(不仅仅是存储库)。这只是一个猜测(基于我见过的常见错误)。 -
明天将检查所有内容。再次感谢。
标签: hibernate spring-boot spring-data-jpa