Как реализовать Spring boot + Hibernate - PullRequest
1 голос
/ 17 февраля 2020

Я получаю эту ошибку:

*************************** 
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.springframe .orm.hibernate4.SpringSessionContext

Ответы [ 2 ]

1 голос
/ 17 февраля 2020

попробуйте создать Autowired sessionFactory в вашем репозитории

   @Repository
   public class EmployeeDAO {
            private SessionFactory sessionFactory;

            @Autowired
            public EmployeeDAO(EntityManagerFactory entityManagerFactory) {
                    this.sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
            }
    }

или попробуйте это решение - { ссылка }

0 голосов
/ 17 февраля 2020

Вам не нужно создавать сессию. Просто добавьте зависимость spring-boot-starter-jpa в pom. xml, чтобы использовать hibernate. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>

Если вы это сделаете, то можете напрямую передать запрос в хранилище.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...