我是学习者,并且有谁知道如何获取由Spring Boot创建的Hibernate Session Factory的句柄?我看到了许多解决方案,并且实现了以下代码,但是在命中服务时出现异常
org.hibernate.HibernateException: No CurrentSessionContext configured!
spring.datasource.url= jdbc:mysql://localhost:3306/sakila
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
@SpringBootApplication
public class SpringBootCurd1Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootCurd1Application.class, args);
}
@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
return hemf.getSessionFactory();
}
}
@Repository
public class EmployeeDao {
@Autowired
SessionFactory sessionFactory;
/**
* getListOfStates
*
* @return
*/
public List<?> getListOfStates(int userId) {
String hql = "FROM states s WHERE " + "s.userid = :userId";
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery(hql);
query.setParameter("userId", userId);
session.flush();
session.clear();
return query.list();
}
}
答案 0 :(得分:2)
不要使用普通的Hibernate,而是使用JPA作为API,除非您确实需要特定的Hibernate特定功能(无需查看代码)。
因此,改写您的代码以改为使用EntityManager
:
Repository
public class EmployeeDao {
@PersistenceContext
private EntityManager entityManager;
/**
* getListOfStates
*
* @return
*/
public List<State> getListOfStates(int userId) {
return em.createQuery("SELECT s FROM states s WHERE s.userid = :userId", State.class)
.setParameter("userId", userId)
.getResultList();
}
}
现在,如果您确实需要访问Session
,请使用EntityManager.unwrap(Session.class)
来获取它。
@Repository
public class EmployeeDao {
@PersistenceContext
private EntityManager entityManager;
/**
* getListOfStates
*
* @return
*/
public List<?> getListOfStates(int userId) {
String hql = "FROM states s WHERE " + "s.userid = :userId";
Session session = entityManager.unwrap(Session.class);
Query query = session.createQuery(hql);
query.setParameter("userId", userId);
session.flush();
session.clear();
return query.list();
}
}
但是,如上所述,与Hibernate的普通API相比,您应该更喜欢JPA。
注意::您现在还可以删除产生@Bean
的{{1}}方法。