注解方式配置SessionFactory的注入

之前程序中的SessionFactory都是通过hibernate的方式获取的:

Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

因为一些问题想要改成Spring注入的方式,但是我的程序都是使用的注解的方式注入bean,为了保持一致性还是用@Bean来配置SessionFactory


首先配置DataSource

	@Bean(destroyMethod="close")
	public DataSource dataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(url);
		dataSource.setUsername(userName);
		dataSource.setPassword(password);
		return dataSource;
	}

这里按照Spring的文档的说法配置DataSource的时候一定要写DestoryMothod


其次配置SessionFactory

我们用XML配置的时候一般用LocalSessionFactoryBean作为implementation,但是用java代码配置的时候发现LocalSessionFactoryBean并没有实现SessionFactory,原来LocalSessionFactoryBean只是一个FactoryBean,其中有一个SessionFactory类型的成员变量,需要调用LocalSessionFactoryBean的getObject()方法返回SessionFactory。

	@Bean
	public SessionFactory sessionFactory() {
		LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
		factoryBean.setDataSource(dataSource());
		String rootPath = getClass().getResource("/").getPath();
		File file = new File(rootPath+"/hibernate.cfg.properties");
		Properties hbtProperties = new Properties();
		try {
			hbtProperties.load(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		factoryBean.setHibernateProperties(hbtProperties);
		//mapping resoureces 不需要写出文件的全路径,只需要文件名
		factoryBean.setMappingResources(new String[]{"hbm.xml"});
		try {
			//这个方法是真正生成sessionFactory的
			factoryBean.afterPropertiesSet();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return factoryBean.getObject();
	}


另外在hibernate.cfg.properties中show_sql一定要写成hibernate.show_sql,而在hibernate.cfg.xml中就可以只写show_sql

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值