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&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>
基本上就这样吧