`

Struts2+Spring2.5+Hibernate3.3整合开发附源代码

阅读更多

第一步在Spring中配置数据源:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass" value="org.gjt.mm.mysql.Driver"/>
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh2?useUnicode=true&amp;characterEncoding=UTF-8"/>
		<property name="user" value="root"/>
		<property name="password" value="hjc"/>
		<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
		<property name="initialPoolSize" value="1"/>
		<!--连接池中保留的最小连接数。-->
		<property name="minPoolSize" value="1"/>	
		<!--连接池中保留的最大连接数。Default: 15 -->
		<property name="maxPoolSize" value="300"/>
		<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
		<property name="maxIdleTime" value="60"/>	
		<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
		<property name="acquireIncrement" value="5"/>	
		<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
		<property name="idleConnectionTestPeriod" value="60"/>
	</bean>
 
第二步集成进hibernate
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		 <property name="mappingResources">
			    <list>
			      <value>org/ssh2/bean/Employee.hbm.xml</value>
			    </list>
		</property>
		 <property name="hibernateProperties">
			 <value>
			      hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
			      hibernate.hbm2ddl.auto=update
			      hibernate.show_sql=false
			      hibernate.format_sql=false
			  </value>
		 </property>
	</bean>
 第三步使用Spring容器管理事务服务:
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	<!--使用基于注解方式配置事务 -->
	<tx:annotation-driven transaction-manager="txManager"/>
 
package org.ssh2.action;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.ssh2.service.EmployeeService;
import com.opensymphony.xwork2.ActionContext;

@Controller // employeeAction
public class EmployeeAction {
    @Resource EmployeeService employeeService;
    
	public String execute(){
		ActionContext.getContext().put("employees", employeeService.list());
		return "list";
	}
}
 
package org.ssh2.action;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.ssh2.bean.Employee;
import org.ssh2.service.EmployeeService;
import com.opensymphony.xwork2.ActionContext;

@Controller @Scope("prototype")
public class EmployeeManageAction {
	@Resource EmployeeService employeeService;
	private Employee employee;	
	
	public Employee getEmployee() {
		return employee;
	}
	public void setEmployee(Employee employee) {
		this.employee = employee;
	}
	public String addUI(){
		return "add";
	}	
	public String add(){
		employeeService.save(employee);
		ActionContext.getContext().put("message", "保存成功");
		return "message";
	}
}
 
package org.ssh2.bean;

public class Employee {
	private String username;
	private String password;
	private Gender gender = Gender.MAN;
	
	public Employee(){}
	
	public Employee(String username, String password) {
		this.username = username;
		this.password = password;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Gender getGender() {
		return gender;
	}
	public void setGender(Gender gender) {
		this.gender = gender;
	}
}
 
package org.ssh2.bean;
/**
 * 性别
 * 
 */
public enum Gender {
	MAN,
	WOMEN;
}
 

 

<hibernate-mapping package="org.ssh2.bean">
    <class name="Employee">
       <id name="username" length="20"/>
       <property name="password" length="20" not-null="true"/>
       <property name="gender" not-null="true" length="5">
        	<type name="org.hibernate.type.EnumType">
        		<param name="enumClass">org.ssh2.bean.Gender</param>
<!-- 12为java.sql.Types.VARCHAR常量值,即保存枚举的字面值到数据库。如果不指定type参数,保存枚举的索引值(从0开始)到数据库-->
        		<param name="type">12</param>
        	</type>
        </property>
    </class>
</hibernate-mapping>
 
package org.ssh2.service;

import java.util.List;

import org.ssh2.bean.Employee;

public interface EmployeeService {
	public void save(Employee employee);
	public void update(Employee employee);
	public Employee find(String username);
	public void delete(String... usernames);
	public List<Employee> list();
}
 
package org.ssh2.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.ssh2.bean.Employee;
import org.ssh2.service.EmployeeService;


@Service @Transactional
public class EmployeeServiceBean implements EmployeeService{
	@Resource SessionFactory factory;

	public void delete(String... usernames) {
		for(String username : usernames){
			factory.getCurrentSession().delete(factory.getCurrentSession().load(Employee.class, username));
		}
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Employee find(String username) {
		return (Employee)factory.getCurrentSession().get(Employee.class, username);
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Employee> list() {		
		return factory.getCurrentSession().createQuery("from Employee").list();
	}
    
	public void save(Employee employee) {
		factory.getCurrentSession().persist(employee);
	}

	public void update(Employee employee) {
		factory.getCurrentSession().merge(employee);
	}

}
 
<struts>
	<!-- 默认的视图主题 -->
    <constant name="struts.ui.theme" value="simple" />

	 <constant name="struts.objectFactory" value="spring" />
	
	 <package name="employee" namespace="/employee" extends="struts-default">
	 	<action name="list" class="employeeAction">
	 		<result name="list">/WEB-INF/page/employee.jsp</result>
	 	</action>
	 	
	 	<action name="manage_*" class="employeeManageAction" method="{1}">
	 		<result name="add">/WEB-INF/page/employeeAdd.jsp</result>
	 		<result name="message">/WEB-INF/page/message.jsp</result>
	 	</action>
	 </package>
</struts>
 
package org.ssh2.service;

import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.ssh2.bean.Employee;
import org.ssh2.bean.Gender;
import org.ssh2.service.EmployeeService;


public class EmployeeTest {
	private static EmployeeService employeeService;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		try {
			ApplicationContext act = new ClassPathXmlApplicationContext("beans.xml");
			employeeService = (EmployeeService)act.getBean("employeeServiceBean");
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void save(){
		employeeService.save(new Employee("ssh2", "123456"));
	}
	@Test
	public void update(){
		Employee employee = employeeService.find("ssh2");
		employee.setGender(Gender.WOMEN);
		employeeService.update(employee);
	}
	
	@Test
	public void delete(){
		employeeService.delete("ssh2");
	}
	
	@Test
	public void list(){
		List<Employee> ems = employeeService.list();
		for(Employee em: ems)
			System.out.println(em.getPassword());
	}
	
	@Test
	public void find(){
		Employee em = employeeService.find("ssh2");
		System.out.println(em.getPassword());
	}
}
//ssh2.org ———— ssh2整合技术论坛,现在需要大量的管理员和版主,希望你们支持
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics