ssh

来源:互联网 发布:mysql查询最小时间 编辑:程序博客网 时间:2024/05/16 14:53

1.

package cn.itcast.action;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bean.Employee;
import cn.itcast.service.EmployeeService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Service("employeeAction")
@Scope("prototype")
public class EmployeeAction extends ActionSupport{
 private static final long serialVersionUID = 1852954109640133975L;
 
 @Resource(name="employeeService")
 private EmployeeService employeeService;
 @Override
 public String execute() throws Exception {
  List<Employee> employees = employeeService.list();
  ActionContext.getContext().put("employees", employees);
  return "list";
 }

}

2.

package cn.itcast.bean;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name = "T_Employee")
public class Employee {
private String username;
private String password;
private Gender gender=Gender.MAN;


public Employee(String username, String password) {
 this.username = username;
 this.password = password;
}
public Employee() {}
@Id
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;
}
@Enumerated(EnumType.STRING)
public Gender getGender() {
 return gender;
}
public void setGender(Gender gender) {
 this.gender = gender;
}
@Override
public String toString() {
 return "姓名:"+username+" 密码:"+password+" 性别:"+gender;
}
@Override
public int hashCode() {
 final int prime = 31;
 int result = 1;
 result = prime * result + ((gender == null) ? 0 : gender.hashCode());
 result = prime * result + ((password == null) ? 0 : password.hashCode());
 result = prime * result + ((username == null) ? 0 : username.hashCode());
 return result;
}
@Override
public boolean equals(Object obj) {
 if (this == obj)
  return true;
 if (obj == null)
  return false;
 if (getClass() != obj.getClass())
  return false;
 final Employee other = (Employee) obj;
 if (gender == null) {
  if (other.gender != null)
   return false;
 } else if (!gender.equals(other.gender))
  return false;
 if (password == null) {
  if (other.password != null)
   return false;
 } else if (!password.equals(other.password))
  return false;
 if (username == null) {
  if (other.username != null)
   return false;
 } else if (!username.equals(other.username))
  return false;
 return true;
}

}

3.

package cn.itcast.bean;
public enum Gender {
 MAN,WOMAN;
}
4.<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<hibernate-mapping package="cn.itcast.bean">
 <class name="Employee" table="employee">
  <id name="username" length="20">
  <generator class="assigned" />
  <!--
   <column name="id" />
   <generator class="native"></generator>
   -->
  </id>
  <property name="password" length="20" not-null="true">
   <!--
   <column name="name" />
   -->
  </property>
  <property name="gender" not-null="true" length="5">
   <type name="org.hibernate.type.EnumType">
   <param name="enumClass">cn.itcast.bean.Gender</param>
   <!-- 12为java.sql.Types.VARCHAR常量值,即保存枚举的字面值到数据库。如果不指定type参数,保存枚举的索引值(从0开始)到数据库 -->
   <param name="type">12</param>
   </type>
  </property>
 </class>
</hibernate-mapping>
实体类采用注解后已不需要映射文件

4.

package cn.itcast.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 cn.itcast.bean.Employee;
import cn.itcast.service.EmployeeService;

@Service("employeeService")
@Transactional
public class EmployeeServiceBean implements EmployeeService {
 @Resource
 private 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().save(employee);
  //factory.getCurrentSession().persist(employee);
 }
 public void update(Employee employee) {
  //factory.getCurrentSession().update(employee);
  factory.getCurrentSession().merge(employee);
 }

}

5.

package cn.itcast.service;

import java.util.List;
import cn.itcast.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();
}

6.测试

package junit.test;

import java.util.List;

import org.codehaus.jackson.map.Module.SetupContext;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.bean.Employee;
import cn.itcast.bean.Gender;
import cn.itcast.service.EmployeeService;
import cn.itcast.service.impl.EmployeeServiceBean;

import com.opensymphony.xwork2.interceptor.annotations.Before;

public class EmployeeTest {
 private static EmployeeService emService;
 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
  try {
   ApplicationContext act=new ClassPathXmlApplicationContext("applicationContext.xml");  
   emService=(EmployeeService)act.getBean("employeeService");
  } catch (RuntimeException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 @Test
 public void save() {
  emService.save(new Employee("zhangliwei","liwei"));
  emService.save(new Employee("zhangliwei1","liwei"));
  emService.save(new Employee("zhangliwei2","liwei"));
  emService.save(new Employee("zhangliwei3","liwei"));
  emService.save(new Employee("zhangliwei4","liwei"));
 }
/* @Test public void save(Employee employee);
 public void update(Employee employee);
 public Employee find(String username);
 public void delete(String... usernames);
 public List<Employee> list();*/
 @Test
 public void update() {
  Employee employee = emService.find("zhangliwei");
  employee.setGender(Gender.WOMAN);
  emService.update(employee);
 }
 @Test
 public void find() {
  Employee employee = emService.find("zhangliwei");
  System.out.println(employee);
 }
 @Test
 public void delete() {
  emService.delete("zhangliwei");
 }
 @Test
 public void list() {
  List<Employee> employees = emService.list();
  for(Employee emp:employees){
   System.out.println(emp);
  }
 }
}

 

7.

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 要让applicationContext.xml认得事务处理,我们需要将beans头识别修改一下,如下: -->
<beans xmlns=" 

<!-- 使用Spring的各类annotation
 <context:annotation-config />-->
   
     <!-- 扫描包结构找到使用了annotation的类 -->
 <context:component-scan base-package="cn.itcast"></context:component-scan>

  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  destroy-method="close">
       <property name="driverClass" value="oracle.jdbc.OracleDriver"/>
       <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
       <property name="user" value="fee"/>
       <property name="password" value="fee"/>
       <!-- 初始化时获取的连接数,取值应在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>


 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
 <!-- 同时我们需要将Employee.hbm.xml的路径放到applicationContext中 -->
  <property name="dataSource"><ref bean="dataSource" /></property>
  <!--
  <property name="mappingResources">
   <list>
    <value>cn/itcast/bean/Employee.hbm.xml</value>
   </list>
  </property>
   -->
   <property name="packagesToScan" value="cn."/>
  <property name="hibernateProperties">
    <props>
     <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
     <prop key="hibernate.hbm2ddl.auto">update</prop>
     <prop key="hibernate.show_sql">true</prop>
     <prop key="hibernate.format_sql">true</prop>
    </props>
  </property>
 </bean>

 <!-- 同时增加事务的处理 -->
 <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory"><ref local="sessionFactory" /></property>
 </bean>
 <!-- 使用基于注解配置事务 -->
 <tx:annotation-driven transaction-manager="txManager"/>

 <!-- 上述完成后,我们就需要在spring中注册类了。打开applicationContext.xml,然后注册<bean>
  
  增加的代码如下:-->
</beans>

8.

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

>
<!--  在<struts></struts>之间添加一个常量,将struts交给spring管理。 -->
<struts>
 <constant name="struts.objectFactory" value="spring" />

 <!-- 配置struts.xml,将action写入 -->
  <package name="employee" namespace="/employee" extends="struts-default" >
  <action name="list" class="employeeAction">
   <result name="list">/WEB-INF/page/employee.jsp</result> 
  </action>
 </package>
</struts>

8.

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ taglib uri="" prefix="ec"%>
<%@ taglib uri="" prefix="c"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    <title>My JSP 'employee.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link href="<c:url value="/style/extremecomponents.css"/>" type="text/css" rel=stylesheet>
 -->
  <link rel="stylesheet" href="../style/extremecomponents.css" type="text/css"></link></head>
 
  <body>
  <ec:table
  items="employees"
  action="${pageContext.request.contextPath}/employee/list"
  imagePath="${pageContext.request.contextPath}/images/table/*.gif"
  title="Presidents"
  width="80%"
  rowsDisplayed="15"
  locale="zh_CN"
  >
  <ec:row>
   <ec:column property="username"/>
   <ec:column property="password"/>
   <ec:column property="gender"/>
  </ec:row>
 </ec:table>
  <!--JSTL/EL:<br/>
   <c:forEach items="${employees}" var="employee">
   姓名:${employee.username},密码:${employee.password},性别:${employee.gender}<br/>
   </c:forEach>
  <br/>
  ONGL:<br/>
  <s:iterator value="#request.employees">
   姓名:<s:property value="username"/>,密码:<s:property value="password"/>,性别:<s:property value="gender"/><br/>
  </s:iterator>  -->
  </body>
</html>

9.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
  <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
 
</web-app>

0 0
原创粉丝点击