package com.spring.hibernateTransactionManager;
import org.hibernate.Session;
public interface BaseDao<T> {
public Session getHibernateSession();
public void save(Object entity);
}
package com.spring.hibernateTransactionManager;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
@SuppressWarnings("unchecked")
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
public BaseDaoImpl() {
GenricsUtils.getSuperClassGenricType(getClass());
}
public Session getHibernateSession() {
return this.getSession();
}
public void save(Object entity) {
this.getHibernateTemplate().save(entity);
}
public void update(Object entity) {
this.getHibernateTemplate().update(entity);
}
public void saveOrUpdate(Object entity) {
this.getHibernateTemplate().merge(entity);
}
public void update(String hql) {
this.getHibernateTemplate().bulkUpdate(hql);
}
public void delete(String hql) {
this.getHibernateTemplate().bulkUpdate(hql);
}
public void delete(Object entity) {
this.getHibernateTemplate().delete(entity);
}
public List<T> find(String hql, Object... values) {
return this.getHibernateTemplate().find(hql, values);
}
public T first(String hql, Object... values) {
Iterator i = this.getHibernateTemplate().iterate(hql, values);
if (i.hasNext()) {
return (T) i.next();
} else {
return null;
}
}
public boolean isExists(String hql, Object... values) {
return !this.getHibernateTemplate().find(hql, values).isEmpty();
}
@SuppressWarnings("hiding")
public <T> T get(Class<T> entityClass,Serializable id) {
return (T) getHibernateTemplate().get(entityClass, id);
}
public List<T> find(String hql, int startIndex, int pageSize,
Object... values) {
Query query = getSession().createQuery(hql);
query.setFirstResult(startIndex);
query.setMaxResults(pageSize);
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
return query.list();
}
}
package com.spring.hibernateTransactionManager;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class GenricsUtils {
private GenricsUtils(){}
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(Class clazz){
return getSuperClassGenricType(clazz, 0);
}
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
* @return the index generic declaration, or <code>Object.class</code> if cannot be determined
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(Class clazz, int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return Object.class;
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
}
package com.spring.hibernateTransactionManager;
import com.spring.model.Product;
import com.spring.model.Receiver;
public interface ProductManager {
public void save(Product p);
public void save(Product p, Receiver r);
}
package com.spring.hibernateTransactionManager;
import com.spring.model.Product;
import com.spring.model.Receiver;
public class ProductManagerImpl implements ProductManager{
private BaseDao<Product> baseDao;
private BaseDao<Receiver> baseRDao;
@Override
public void save(Product p) {
baseDao.save(p);
}
public void save(Product p, Receiver r) {
baseDao.save(p);
baseRDao.save(r);
}
public BaseDao<Product> getBaseDao() {
return baseDao;
}
public void setBaseDao(BaseDao<Product> baseDao) {
this.baseDao = baseDao;
}
public BaseDao<Receiver> getBaseRDao() {
return baseRDao;
}
public void setBaseRDao(BaseDao<Receiver> baseRDao) {
this.baseRDao = baseRDao;
}
}
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://127.0.0.1/jinhonglun?useEncoding=true&characterEncoding=UTF-8
database.username=root
database.password=root
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" 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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <!-- 获取资源文件 --> <bean id="configurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:/com/spring/dataSourceTransactionManager/configuration.properties" /> <!-- 获取多个资源文件 <property name="locations"> <list> <value>classpath:/com/zsw/config/jdbc.properties</value> </list> </property> --> <!-- 使用location属性定义单个配置文件 <property name="location"> <value>classpath:/com/zsw/config/jdbc.properties</value> </property> --> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${database.driver}" /> <property name="url" value="${database.url}" /> <property name="username" value="${database.username}" /> <property name="password" value="${database.password}" /> <property name="timeBetweenEvictionRunsMillis" value="300000" /> <property name="numTestsPerEvictionRun" value="6" /> <property name="minEvictableIdleTimeMillis" value="1800000" /> <property name="initialSize" value="3" /> <property name="maxActive" value="10" /> <property name="maxIdle" value="10" /> <property name="maxWait" value="5000" /> <property name="poolPreparedStatements" value="true" /> <property name="maxOpenPreparedStatements" value="100" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mappingLocations"> <value>classpath:/com/spring/model/*.hbm.xml</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.query.substitutions" >true 1, false 0</prop> </props> </property> </bean> <bean id="baseDao" class="com.spring.hibernateTransactionManager.BaseDaoImpl" > <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="productManager" class="com.spring.hibernateTransactionManager.ProductManagerImpl" > <property name="baseDao" ref="baseDao"></property> <property name="baseRDao" ref="baseDao"></property> </bean> <!-- 位于org.springframework.orm.hibernate3包中,提供对单个org.hibernate.SessionFactory事务支持, 用于集成Hibernate框架时的事务管理;该事务管理器只支持Hibernate3+版本,且Spring3.0+版本只支持Hibernate 3.2+版本; --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 采用AOP机制切面管理事务 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="processNotifyTrade" propagation="REQUIRES_NEW" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 解释一下(* com.evan.crm.service.*.*(..))中几个通配符的含义: 第一个 * —— 通配 任意返回值类型 第二个 * —— 通配 包com.evan.crm.service下的任意class 第三个 * —— 通配 包com.evan.crm.service下的任意class的任意方法 第四个 .. —— 通配 方法可以有0个或多个参数 --> <aop:config> <aop:pointcut expression="execution(public * com.spring.hibernateTransactionManager..*.*(..))" id="servicePointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/> </aop:config> </beans>
package com.spring.hibernateTransactionManager;
import java.sql.SQLException;
import javax.naming.NamingException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.spring.model.Product;
import com.spring.model.Receiver;
public class TestHibernate {
public static void main(String[] args) throws NamingException, SQLException {
ApplicationContext app = new FileSystemXmlApplicationContext("src/com/spring/hibernateTransactionManager/spring-hibernate.xml");
ProductManager productManager = (ProductManager)app.getBean("productManager");
Product p = new Product();
p.setProductTitle("阿萨啊啊阿");
Receiver r = new Receiver();
productManager.save(p, r);
}
}