繁体   English   中英

如何实现 Spring Boot + Hibernate

[英]How to implement Spring boot + Hibernate

我收到此错误:

*************************** 
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();
        }
    }
}

application.properties 文件,

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.xml 中添加依赖 spring-boot-starter-jpa 即可使用 hibernate。 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>

如果这样做,则可以直接在存储库中提供查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM