hibernate session和sessionfactory如何在spring中使用java配置?

时间:2018-06-14 18:03:08

标签: java spring hibernate

您好我正在使用带有hibernate的spring和java配置 这是我的代码

在dao类

中使用其方法的类
public class BaseHibernate {
@Autowired
private SessionFactory sessionFactory;
@Autowired
HttpSession session;

public Session getSession(){
    return sessionFactory.getCurrentSession();
}
public SessionFactory getSessionFactory() {
    return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}}

这是我的配置类

    @Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.sol.steelDoc.SDRepository.repositories.userService.dto",
            "com.sol.steelDoc.SDRepository.repositories.projectService.dto",
            "com.sol.steelDoc.SDRepository.repositories.publishService.dto" });
    sessionFactory.setHibernateProperties(getHibernateProperties());
    return sessionFactory;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager() {
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(sessionFactory().getObject());
    return txManager;
}

我在我的dao中使用这样的代码

getSession().save(POJO_OBJECT);

一切正常,但我需要知道如果在服务器启动时注入了sessionsession factory bean,则表示只应使用单个session和单个sessionfactory通过整个申请。因为它始终得到sessionFactory.getCurrentSession()。但我读到每个事务都应该使用新会话。这样就可以使用缓存属性了。

所以如果我错的话,请告诉我其实在这里发生了什么?

0 个答案:

没有答案