我收到此错误:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field sessionFactory in com.demo.dao.EmployeeDAO required a bean of type 'org.hibernate.SessionFactory' that could not be found.
Action: Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.
我HibernateUtil
课是:
@Configuration
public class HibernateUtil {
@Autowired
private EntityManagerFactory factory;
@Bean
public SessionFactory getSessionFactory() {
if(factory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("Factory is not a hibernate factory.");
}
return factory.unwrap(SessionFactory.class);
}
}
我EmployeeDao
课是:
@Repository
public class EmployeeDAO {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
public void save(Employee emp) {
Session session = null;
try {
session = sessionFactory.openSession();
System.out.println("Session got.");
Transaction tx = session.beginTransaction();
session.save(emp);
tx.commit();
}catch(HibernateException he) {
he.printStackTrace();
}
}
}
应用程序属性文件,
spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://localhost:3306/manissh
spring.datasource.username=root
spring.datasource.password=admin
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
尝试在存储库中创建Autowired
sessionFactory
@Repository
public class EmployeeDAO {
private SessionFactory sessionFactory;
@Autowired
public EmployeeDAO(EntityManagerFactory entityManagerFactory) {
this.sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
}
}
或尝试此解决方案 - https://stackoverflow.com/a/43895827/6582610
您不需要创建会话。只需在pom中添加依赖项spring-boot-starter-jpa.xml即可使用休眠。<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
如果这样做,则可以直接在存储库中给出查询。