【发布时间】:2017-06-01 20:51:09
【问题描述】:
我一直在用 SpringBoot + Spring Data JPA 编写我的第一个项目。我使用 MySql 作为我的数据库提供程序。我对 Spring Boot 和 Hibernate 有点陌生。
我按照http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/ 上的教程进行了我的项目。
在会话工厂之前一切都清楚了。提到的教程不使用会话工厂;相反,它使用基于CrudRepository 的事务。但就我而言,由于我还是 Hibernate 的新手,我使用 SessionFactory 进行数据库操作。
在我的项目中,DaoImpl 类如下所示。
@Repository
public class ReadDaoImpl implements ReadDao{
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
@Autowired
public static void setSessionFactory(SessionFactory sessionFactory) {
TenderReadDaoImpl.sessionFactory = sessionFactory;
}
@Override
public List<Read> getAllReads() {
System.out.println("DEBUG: Inside ReadDaoImpl.getAllReads");
Session session = sessionFactory.openSession(); // I think that the issue comes from here
Transaction tx = null;
..............................
..............................
}
}
我的项目开始在服务器上运行,没有任何问题。但是当我访问 getAll() 方法的相关 url 时,Eclipse 控制台会打印出一个空指针异常,引用以下行。
Session session = sessionFactory.openSession();
我想我错过了sessionFactory 的一些配置。但我无法弄清楚它是什么。
这是我的application.properties 文件。它实际上是来自上述链接的同一文件的副本。
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database
spring.datasource.url = jdbc:mysql://localhost:3306/readsdb?useSSL=false
# Username and password
spring.datasource.username = root
spring.datasource.password = password
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = create-drop
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
在我的项目中,没有任何配置文件。我需要添加一个来创建sessionFactory Bean 吗?我遇到了一个叫entityManagerFactory 的东西。我需要为这个基于 Spring Jpa 的项目配置sessionfactory 吗?如果有,怎么做?
目前我完全没有解决方案。指导我完成这件事。如果能指出这样做的详尽方法,对我会有很大帮助。
谢谢..!
【问题讨论】:
-
这个问题你解决了吗?我也面临同样的问题。
-
很遗憾没有。但是,我能够使用基于 entityManager 的数据库连接来完成任务
-
你遇到了什么错误?
标签: hibernate spring-boot spring-data-jpa sessionfactory