当前位置:首页 > 开发 > 编程语言 > Spring > 正文

声明式spring整合hibernate配置参考

发表于: 2011-09-05   作者:chyx72   来源:转载   浏览次数:
摘要: applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.o
applicationContext.xml
<?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:tx="http://www.springframework.org/schema/tx"
		xmlns:context="http://www.springframework.org/schema/context"
		xsi:schemaLocation="
			http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans-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/context 
			http://www.springframework.org/schema/context/spring-context-2.5.xsd">
			
	<!-- 持久层配置 -->
 	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>   
		<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/oa?useUnicode=true&amp;characterEncoding=utf8"></property>   
		<property name="user" value="root"></property>   
		<property name="password" value="root"></property>  
		<property name="maxPoolSize" value="40"></property>   
		<property name="minPoolSize" value="1"></property>   
		<property name="initialPoolSize" value="1"></property>   
		<property name="maxIdleTime" value="180"></property>   
	</bean>  

	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
<!--				<prop key="hibernate.current_session_context_class">thread</prop>-->
			</props>
		</property>
		
		<property name="mappingLocations">
			<list>
				<value>classpath:/com/gc/oa/entity/*.hbm.xml</value>
			</list>
		</property>
	</bean>
	<!-- end  -->
	
	<!-- 事物配置 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 
		<property name="sessionFactory"> 
			<ref local="sessionFactory" /> 
		</property> 
	</bean>
	
	<bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true" lazy-init="true"> 
		<property name="transactionManager"> 
			<ref bean="transactionManager" /> 
		</property>
		<property name="proxyTargetClass"> 
			<value>false</value> 
		</property> 
		
		<property name="transactionAttributes"> 
			<props> 
				<prop key="*">PROPAGATION_REQUIRED</prop> 
			</props> 
		</property> 
	</bean>
	<!-- end -->
	
	<!-- 使用spring annotation自动扫描配置 -->
	<context:component-scan base-package="com.gc.oa" />
	<!-- 使用spring annotation自动事务配置-->
	<tx:annotation-driven transaction-manager="transactionManager" />
	<!-- end -->
</beans>

部分代码:
package com.gc.oa.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gc.oa.dao.BaseDao;
import com.gc.oa.utils.Pagination;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T>{
	
	private Class clazz;
	
	public BaseDaoImpl(Class clazz) {
		this.clazz=clazz;
	}
	
	@Autowired
	protected void setSessionFactoryS(SessionFactory sessionFactory) {
		this.setSessionFactory(sessionFactory);
	}

	public void add(T t) throws Exception {
		this.getHibernateTemplate().save(t);
	}

	public void delete(T t) throws Exception {
		this.getHibernateTemplate().delete(t);
	}

	public void update(T t) throws Exception {
		this.getHibernateTemplate().update(t);
	}

	public Pagination findByPage(final String query,final int pageNum,final int pageSize) {
		
		return (Pagination)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				String queryStr="From "+clazz.getName();
				if(query!=null&&!query.equals("")){
					queryStr+=" Where "+query;
				}
				int count=session.createQuery(queryStr).list().size();
				
				List list=session.createQuery(queryStr)
						.setFirstResult((pageNum-1)*pageSize)
						.setMaxResults(pageSize).list();
				
				Pagination pagination=new Pagination();
				pagination.setCountResult(count);
				pagination.setList(list);
				pagination.setCurPage(pageNum);
				pagination.setPageSize(pageSize);
				return pagination;
			}
			
		});
	
	}

	public T findById(int id) {
		return (T)getHibernateTemplate().get(this.clazz, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> query(final String str) throws Exception {
		return getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
					return session.createQuery("From "+clazz.getName()+" where "+str).list();
			}
		});
	}

	public List<T> findAll() {
		return getHibernateTemplate().loadAll(clazz);
	}
	

}

package com.gc.oa.dao.impl;

import org.springframework.transaction.annotation.Transactional;

import com.gc.oa.entity.Diary;
@Repository
public class DiaryDaoImpl extends BaseDaoImpl<Diary>{
	public DiaryDaoImpl() {
		super(Diary.class);
	}

	@Transactional
	public void deleteById(int id) {
		Diary diary=super.findById(id);
		this.getHibernateTemplate().delete(diary);
	}

}

package com.gc.oa.service.impl;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.gc.oa.dao.DiaryDao;
import com.gc.oa.entity.Diary;
import com.gc.oa.service.DiaryService;
import com.gc.oa.utils.Pagination;
@Service
public class DiaryServiceImpl implements DiaryService {
	public static final Logger logger = Logger.getLogger(DiaryServiceImpl.class);
	@Autowired
	private DiaryDao DiaryServiceImpl;

	@Transactional
	public void add(Diary diary) {
		try {
			diary.setCreateTime(new Date());
			DiaryServiceImpl.add(diary);
		} catch (Exception e) {
			logger.error("添加公告失败");
		}
	}

	public Diary findById(int id) {
		Diary diary = null;
		try {
			diary= DiaryServiceImpl.findById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return diary;
	}

	public Pagination findByPage(String query, int pageNum, int pageSize) throws Exception {
		return DiaryServiceImpl.findByPage(query, pageNum, pageSize);
	}
	@Transactional
	public void update(Diary diary) {
		try {
			Diary diary1=findById(diary.getId());
			if(diary1!=null){
				diary1.setTitle(diary.getTitle());
				diary1.setUpdateTime(new Date());
				diary1.setContent(diary.getContent());
				diary1.setEmployer(diary.getEmployer());
				DiaryServiceImpl.update(diary1);
			}
		} catch (Exception e) {
			logger.error("修改公告失败");
		}
	}
	@Transactional
	public void deleteById(int id) {
		try {
			DiaryServiceImpl.deleteById(id);
		} catch (Exception e) {
			logger.error("删除公告失败");
		}
		
	}
}

package com.gc.oa.action;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.gc.oa.entity.Diary;
import com.gc.oa.service.DiaryService;

@Controller("diaryAction")
@Scope("prototype")
public class DiaryAction {
	private Diary diary;
	@Autowired
	private DiaryService diaryServiceImpl;
	public String add(Diary diary){
		diaryServiceImpl.add(diary);
		return "addSuc";
	}
	
	public String delete(Diary diary){
		diaryServiceImpl.deleteById(Integer.valueOf(ServletActionContext.getRequest().getParameter("id")));
		return "delSuc";
	}
	
	public String update(Diary diary){
		diaryServiceImpl.update(diary);
		return "updSuc";
	}
	
	public Diary findById(int id){
		id = Integer.valueOf(ServletActionContext.getRequest().getParameter("id"));
		diary=diaryServiceImpl.findById(id);
		return diary;
		}
	
	public Diary getDiary() {
		return diary;
	}
	public void setDiary(Diary diary) {
		this.diary = diary;
	}
}

例子很简单,代码中记得放@Autowired,@Transactional,@Scope("prototype")...注解
entity配置和hibernate一样,一个javabean对应一个.hbm.xml
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath*:applicationContext.xml
		</param-value>
	</context-param>
	
	<context-param>
		<param-name>log4jRefreshInterval</param-name>
		<param-value>6000</param-value>
	</context-param>
	
	<!-- spring2 -->
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	
	<!-- 权限控制 -->
	<filter>
		<filter-name>privilegeController</filter-name>
		<filter-class>com.gc.oa.privilege.PrivilegeController</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>privilegeController</filter-name>
		<url-pattern>/employer/*</url-pattern>
	</filter-mapping>
	
	<!-- open session in view配置 -->
	<filter>
		<filter-name>sessionFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>

	</filter>
	<filter-mapping>
		<filter-name>sessionFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 编码过滤器 -->
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- struts2 -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>*.do</url-pattern>
		<dispatcher>REQUEST</dispatcher>  
		<dispatcher>FORWARD</dispatcher>
	</filter-mapping>
	
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 
  	<error-page>
		<error-code>403</error-code>
		<location>/403.html</location>
	</error-page>
-->
</web-app>

基本上就这样吧

声明式spring整合hibernate配置参考

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
/*2011年8月28日 10:03:30 by Rush */ 环境配置 项目使用SSH架构,现在要添加Spring事务管理功能,
一、根据第一节项目稍作修改即可,看截图需要修改的地方。 二、按画红线处依次贴出代码 UserDAOImpl
使用spring提供的事务处理机制的好处是程序员可以不用关心事务的切面了,只要配置就好了,可以少写
Spring声明式事物配置管理 1.首先在applicationContext.xml添加以下内容: <!-- 配置事务管理器
项目使用SSH架构,现在要添加Spring事务管理功能,针对当前环境,只需要添加Spring 2.0 AOP类库即可
写道 1 先加入spring 选择全部JAR包文件 并且选择copy check-----这项 意思是把jar包都拷贝到项目的
web.xml----> <!-- 从类路径下加载spring配置文件,classpath关键字特指类路径下加载 -->
本文基于SPRING2.56,HIBERANTE3.25及Oracle10g classes14.jar驱动,介绍SPRING与HIBERNATE是如何配
Spring的声明式事务管理是通过Spring AOP实现的,默认情况下,Spring事务只在遇见RuntimeException
Spring的声明式事务管理是通过Spring AOP实现的,默认情况下,Spring事务只在遇见RuntimeException
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号