您的位置:首页 > 编程语言 > Java开发

Spring学习总结8(整合Hibernate)

2011-04-14 17:19 459 查看
1.在Spring中设置DataSource

设置DataSource,当要获取数据库连接时,就可以直接向DataSource申请。

由于建立数据库连接是一个非常耗时耗资源的行为,所以通过连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中申请一个就行,用完后再放回去。 所以DataSource通常就是一个连接池。

DBCP(DataBase connection pool)。是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。单独使用dbcp需要3个包:common-dbcp.jar,common-pool.jar,common-collections.jar。

通过XML直接设置DataSource属性

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@192.168.134.56/YYET</value>
</property>
<property name="username">
<value>EIFQAS01</value>
</property>
<property name="password">
<value>EIFQAS01</value>
</property>
</bean>


通过properties文件设置DataSource属性

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>

<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>


通过Spring提供的JNDI支持找到web容器提供的数据源

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/eifetl</value>
</property>
<property name="lookupOnStartup">
<value>false</value>
</property>
<property name="cache">
<value>true</value>
</property>
<property name="proxyInterface">
<value>javax.sql.DataSource</value>
</property>
</bean>


2.整合hibernate (通常是通过初始化Spring提供的与Hibernate集成的HibernateTemplate来实现Hibernate中对数据库的操作)

<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <context:annotation-config />
<context:component-scan base-package="com.bjsxt" />

<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>

<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<!-- 使用XML式hibernate的sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>product.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.HSQLDialect
</value>
</property>
</bean>

<!-- 使用注解式hibernate的sessionFactory hibernate3.2以上版本才支持-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--
<!-- 明确指定DTO的路径 -->
<property name="annotatedClasses">
<list>
<value>com.bjsxt.model.User</value>
<value>com.bjsxt.model.Log</value>
</list>
</property>
-->
<!-- 扫描指定包下的所有DTO -->
<property name="packagesToScan">
<list>
<value>com.bjsxt.model</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>

<!-- 声明支持hibernate的数据库访问模板类,注入sessionFactory -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<!-- 声明支持hibernate事务的类,注入sessionFactory -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<aop:config>
<aop:pointcut id="bussinessService"
expression="execution(public * com.bjsxt.service..*.*(..))" />
<aop:advisor pointcut-ref="bussinessService"
advice-ref="txAdvice" />
</aop:config>

<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="getUser" read-only="true" />
<tx:method name="add*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>

</beans>


当初始化HibernateTemplate完后,在DAO中注入HibernateTemplate属性,就可以使用HibernateTemplate中提供的方法进行数据库操作。

使用HibernateTemplate里面提供的方法是不需要再关心连接的打开与释放了,因为HibernateTemplate使用的回调机制。

回调解析

声明一个接口 该接口声明了要发生的核心行为(插入操作,删除操作等)

public interface MyHibernateCallback {
public void doInHibernate(Session s);
}


声明一个模板类

public class MyHibernateTemplate {
// 该方法定义了除了核心行为外的其他重复的行为(打开连接,关闭连接),并以上面接口对象为参数,在里面调用接口里的核心行为方法
public void executeWithNativeSession(MyHibernateCallback callback) {
Session s = null;
try {
// 获取连接,打开事务
s = getSession();
s.beginTransaction();

// 进行数据库操作
callback.doInHibernate(s);

// 提交事务
s.getTransaction().commit();
} catch (Exception e) {
// 回滚事务
s.getTransaction().rollback();
} finally {
//...
}
}

private Session getSession() {
// 获取当前连接
// .......

return null;
}

// 定义要实现的核心操作的具体方法(如插入),当调用该方法时,执行的是插入操作,同时也会执行插入相关的前后方法
public void save(final Object o) {

new MyHibernateTemplate().executeWithNativeSession(new MyHibernateCallback() {
public void doInHibernate(Session s) {
s.save(o);

}
});
}

}


前一种是使用注入的方式,将HibernateTemplate注入DAO中进行使用Hibernate的方法。还有一种是用DAO继承HibernateDaoSupport的方式来实现

自定义一个SuperDao

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

@Component
public class SuperDAO extends HibernateDaoSupport {

@Resource(name="sessionFactory")
public void setSuperSessionFactory(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}

}


Dao继承自定义的SuperDao,即可使用通过HibernateDaoSupport获取HibernateTemplate对象。
import javax.annotation.Resource;

import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;

@Component("u")
public class UserDAOImpl extends SuperDAO implements UserDAO {

public void save(User user) {

this.getHibernateTemplate().save(user);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: