如何在HibernateDaoSupport中注入HibernateTemplate

时间:2017-11-10 04:40:04

标签: spring hibernate

我使用的是Spring版本5.0.1,hibernate版本5.2.12。

当我调用getHibernateTemplate()时,我得到null

我做错了什么?

Dao confif:

@PropertySource(value = {"classpath:hibernate.properties"})
@ComponentScan("ru.bochkarev.hmcs.dao")
@EnableTransactionManagement
@Configuration
public class DaoConfig {

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("hibernate.connection.driver_class"));
        dataSource.setUrl(environment.getRequiredProperty("hibernate.connection.url"));
        dataSource.setUsername(environment.getRequiredProperty("hibernate.connection.username"));
        dataSource.setPassword(environment.getRequiredProperty("hibernate.connection.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        return properties;
    }

    @Bean
    public SessionFactory sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan("ru.bochkarev.hmcs.model");
        sessionFactory.setHibernateProperties(hibernateProperties());
        try {
            sessionFactory.afterPropertiesSet();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sessionFactory.getObject();
    }

    @Bean
    public HibernateTransactionManager hibernateTransactionManager(){
        return new HibernateTransactionManager(sessionFactory());
    }

    @Bean
    public HibernateTemplate hibernateTemplate() {
        return new HibernateTemplate(sessionFactory());
    }
}

............................................... ..................

实施dao:

@Transactional
@Repository
public class DaoTest extends HibernateDaoSupport {

    public void save(TestModel testModel) {
        getHibernateTemplate().saveOrUpdate(testModel);
    }
}

当我调用getHibernateTemplate()时,我得到null

1 个答案:

答案 0 :(得分:0)

尝试以下DAO课程代码,并告知我们是否有效。

@Transactional
@Repository
public class DaoTest {

@Autowired
private HibernateTemplate hibernateTemplate;

public void save(TestModel testModel) {
    getHibernateTemplate().saveOrUpdate(testModel);
}
}