Spring整合Hibernate的一个简单实例
单独使用Hibernate的时候,连接数据库时,Hibernate自己获得DataSource。整合Spring后,Spring容器也可以获得DataSource,而且还可以实现HIbernate相关的功能,这样就可以不要写Hibernate.cfg.xml文件了,直接在Spring的容器中配置就OK了。
?
先看bean.xml文件,通过读取jdbc.properties中的属性,连接数据库,也就是获得DataSource,得到了DataSource就可以通过DataSource来获得SessionFactory。<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"><context:annotation-config /><context:component-scan base-package="com.lbx" /><!-- <bean id="dataSource"value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/spring" /><property name="username" value="root" /><property name="password" value="root" /></bean>--><beandestroy-method="close"/><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><bean id="sessionFactory"ref="dataSource" /><property name="annotatedClasses"><list><value>com.lbx.model.User</value></list></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><prop key="hibernate.show_sql">true</prop></props></property></bean></beans>?
?
?