gpt4 book ai didi

java - 即使没有可用的 SessionFactory 实例,Spring @Autowired 如何绑定(bind) SessionFactory 对象

转载 作者:行者123 更新时间:2023-11-30 08:56:59 26 4
gpt4 key购买 nike

我在基于 Java 的配置中使用 Hibernate 和 Spring。我的配置文件是这个:

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}

@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "dto" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}

工作正常。这没问题,但是当我手动尝试为 trasactionManager 设置 sessionfactory 参数时,如下所示:

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory());
return txManager;
}

IDE 正在显示:

`The method setSessionFactory(SessionFactory) in the type HibernateTransactionManager is not applicable for the arguments (LocalSessionFactoryBean)`

所以,我创建了一个如下所示的 sessionFactory

@Bean
@Autowired
public SessionFactory sessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionFactory = new LocalSessionFactoryBuilder(dataSource);
sessionFactory.addProperties(hibernateProperties());
sessionFactory.scanPackages("dto");
return sessionFactory.buildSessionFactory();

}

并传递给 trasactionManager 它起作用了。

我的问题是,即使在第一种方法中不存在 sessionFactory 实例,spring 如何 Autowiring sessionFactory 对象?

最佳答案

您需要将方法返回类型从 SessionFactory 更改为 HibernateTransactionManager

它应该是这样的:

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}

@Bean
public SessionFactory sessionFactory() {
Properties properties = new Properties();
properties.setProperty("hibernate.show_sql", "true")
properties.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory")
properties.setProperty("hibernate.cache.use_query_cache", "true")
properties.setProperty("hibernate.cache.use_second_level_cache", "true")
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")

return new LocalSessionFactoryBuilder(dataSource())
.scanPackages("dto")
.addProperties(properties)
.buildSessionFactory();
}

关于java - 即使没有可用的 SessionFactory 实例,Spring @Autowired 如何绑定(bind) SessionFactory 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337967/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com