簡體   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