现在的位置: 首页 > 综合 > 正文

增删改查

2012年02月23日 ⁄ 综合 ⁄ 共 11399字 ⁄ 字号 评论关闭

re:

建表:
create table student(
id int primary key,
name varchar(20),
sex varchar(20),
date varchar(50),
content varchar(100)
)DEFAULT CHARSET=utf8;

新建项目Struts2Hibernate,添加hibernate支持,在将struts2所需基本包拷贝到项目中
1.在web.xml中配置struts2的信息
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>struts2Hiberante</display-name>
<filter>
   <filter-name>struts2Hibernate</filter-name>
   <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>

<filter-mapping>
   <filter-name>struts2Hibernate</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

2.生成的hibernate文件内容如下
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
   <property name="connection.username">root</property>
   <property name="connection.url">
    jdbc:mysql://localhost:3306/test
   </property>
   <property name="dialect">
    org.hibernate.dialect.MySQLDialect
   </property>
   <property name="myeclipse.connection.profile">
    com.mysql.jdbc.Driver
   </property>
   <property name="connection.password">root</property>
   <property name="connection.driver_class">
    com.mysql.jdbc.Driver
   </property>
   <mapping resource="com/test/vo/Student.hbm.xml" />

</session-factory>

</hibernate-configuration>

3.生成持久化类及hibernate映射文件
Student.java
package com.test.vo;

/**
* Student generated by MyEclipse Persistence Tools
*/

public class Student implements java.io.Serializable {

// Fields

/**
*
*/
private static final long serialVersionUID = 1L;

private Integer id;

@Override
public String toString() {
   return "id:"+id+"name:"+name;
}

private String name;

private String sex;

private String date;

private String content;

// Constructors

/** default constructor */
public Student() {
}

/** full constructor */
public Student(String name, String sex, String date, String content) {
   this.name = name;
   this.sex = sex;
   this.date = date;
   this.content = content;
}

// Property accessors

public Integer getId() {
   return this.id;
}

public void setId(Integer id) {
   this.id = id;
}

public String getName() {
   return this.name;
}

public void setName(String name) {
   this.name = name;
}

public String getSex() {
   return this.sex;
}

public void setSex(String sex) {
   this.sex = sex;
}

public String getDate() {
   return this.date;
}

public void setDate(String date) {
   this.date = date;
}

public String getContent() {
   return this.content;
}

public void setContent(String content) {
   this.content = content;
}

}

student.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.test.vo.Student" table="student">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="20" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="sex" length="20" />
        </property>
        <property name="date" type="java.lang.String">
            <column name="date" length="50" />
        </property>
        <property name="content" type="java.lang.String">
            <column name="content" length="100" />
        </property>
    </class>
</hibernate-mapping>

4.编写接口
package com.test.dao;

import java.util.List;

import com.test.vo.Student;

public interface StudentDAO {
public void save(Student student);

public void update(Student student);

public void delete (int id);

public Student findById(int id);

public List findAll();
}

5.编写接口实现类
package com.test.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.test.hiberante.HibernateSessionFactory;
import com.test.vo.Student;

public class StudentDAOImp implements StudentDAO {

public void delete(int id) {
   Session session = HibernateSessionFactory.getSession();
   Transaction transaction = session.beginTransaction();
   try{
    Student student = (Student)session.load(Student.class, id);
    session.delete(student);
    transaction.commit();
   }catch(Exception e){
    e.printStackTrace();
   }
}

@SuppressWarnings("unchecked")
public List<Student> findAll() {
   Session session = HibernateSessionFactory.getSession();
   Transaction transaction = session.beginTransaction();
   List<Student> list = new ArrayList<Student>();
   try{
    String hql = "from Student";
    Query query=session.createQuery(hql);
    list=query.list();
    transaction.commit();
   }catch(Exception e){
    e.printStackTrace();
   }finally{
    session.close();
   }
   return list;
}

public Student findById(int id) {
   Session session = HibernateSessionFactory.getSession();
   Transaction transaction = session.beginTransaction();
   try{
    Student student = (Student)session.createQuery("from Student s where s.id='"+id+"'").uniqueResult();
    //Student student=(Student) session.get(Student.class, id);
    transaction.commit();
    return student;
   }catch(Exception e){
    e.printStackTrace();
    transaction.rollback();
   }finally{
    session.close();
   }
   return null;
}

public void save(Student student) {
   Session session = HibernateSessionFactory.getSession();
   Transaction transaction = session.beginTransaction();
   try{
    session.save(student);
    transaction.commit();
   }catch(Exception e){
    e.printStackTrace();
   }finally{
    session.close();
   }
}

public void update(Student student) {
   Session session = HibernateSessionFactory.getSession();
   Transaction transaction = session.beginTransaction();
   try{
    session.saveOrUpdate(student);
    transaction.commit();
   }catch(Exception e){
    e.printStackTrace();
   }finally{
    session.close();
   }

}

}

6.编写struts2的业务控制类
package com.test.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.test.dao.StudentDAO;
import com.test.dao.StudentDAOImp;
import com.test.vo.Student;

public class StudentAction extends ActionSupport {
private Student student;

private List<Student> list;
StudentDAO studentDAO=new StudentDAOImp();

public List<Student> getList() {
   return list;
}

public void setList(List<Student> list) {
   this.list = list;
}
  

public Student getStudent() {
   return student;
}

public void setStudent(Student student) {
   this.student = student;
}

public String save() throws Exception{
   studentDAO.save(student);
   System.out.println("插入成功 ");
   return SUCCESS;
}

@SuppressWarnings("unchecked")
public String list() throws Exception{
   try{
    System.out.println("查询 ");
   list = studentDAO.findAll();
   System.out.println("插入成功 ");
   return SUCCESS;
   }catch(Exception e){
    e.printStackTrace();
    return ERROR;
   }
}

public String edit() {
   try{
    HttpServletRequest request = ServletActionContext.getRequest();
    int id=Integer.parseInt(request.getParameter("id"));
    student = studentDAO.findById(id);
    return SUCCESS;
   }catch(Exception e){
    e.printStackTrace();
    return ERROR;
   }
}

public String update() {
   try{
    studentDAO.update(student);
    return SUCCESS;
   }catch(Exception e){
    e.printStackTrace();
    return ERROR;
   }
}

public String delete() {
   try{
    HttpServletRequest request = ServletActionContext.getRequest();
    int id = Integer.parseInt(request.getParameter("id"));
    studentDAO.delete(id);
    return SUCCESS;
   }catch(Exception e){
    e.printStackTrace();
    return ERROR;
   }
}
}

7.struts2的配置文件struts.xml
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2Hiberante" extends="struts-default" >
   <action name="Save" class="com.test.action.StudentAction" method="save">
    <result name="success" type="redirect">/List.action</result>
    <result name="error">/errors.jsp</result>
   </action>
  
   <action name="List" class="com.test.action.StudentAction" method="list">
    <result name="success">/list.jsp</result>
    <result name="error">/errors.jsp</result>
   </action>
  
   <action name="Edit" class="com.test.action.StudentAction" method="edit">
    <result name="success">/insert.jsp</result>
    <result name="error">/errors.jsp</result>
   </action>
  
   <action name="Update" class="com.test.action.StudentAction" method="update">
    <result name="success" type="redirect">/List.action</result>
    <result name="error">/errors.jsp</result>
   </action>
  
   <action name="Delete" class="com.test.action.StudentAction" method="delete">
    <result name="success" type="redirect">/List.action</result>
    <result name="error">/errors.jsp</result>
   </action>
</package>
</struts>

8.页面文件
insert.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.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 rel="stylesheet" type="text/css" href="styles.css">
-->
<SCRIPT type="text/javascript">
   function doupdate(){
    document.forms[0].action = "./Update.action";
    document.forms[0].submit();
   }
</SCRIPT>
</head>

<body><br>
    <s:form action="Save.action" method="post">
   
    <table>
       <tr>
        <td><s:textfield name="student.id" label="学号"></s:textfield></td>
        <td><s:textfield name="student.name" label="姓名"></s:textfield> </td>
        <td><s:textfield name="student.sex" label="性别"></s:textfield> </td>
        <td><s:textfield name="student.date" label="生日"></s:textfield> </td>
        <td><s:textfield name="student.content" label="描述"></s:textfield> </td>
       </tr>
       <tr>
        <s:if test="${student.id==null}">
         <td colspan="4"><s:submit value="提 交"></s:submit> </td>
        </s:if>
        <s:else>
         <td colspan="4"><s:submit value="更 新" onclick="doupdate();"></s:submit> </td>
        </s:else>
       </tr>
    </table>
    </s:form>
</body>
</html>

显示页面
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
<head>
    <title>My JSP 'hello.jsp' starting page</title>
</head>

<body>
    <s:form action="" method="post">
    <table width="80%" align="center">
       <tr style="background-color:#eeee99;   border-bottom:2px   solid   black;   height:25px">
        <td>学号</td>
        <td>姓名</td>
        <td>性别</td>
        <td>出生日期</td>
        <td>描述</td>
        <td>编辑</td>
        <td>删除</td>
       </tr>
       <s:iterator id="list" value="list" status="index">
        <tr style="background-color:#ffeecc;   border-bottom:2px   solid   black;   height:25px">
         <td><s:property value="id"/> </td>
         <td><s:property value="name"/> </td>
         <td><s:property value="sex"/> </td>
         <td><s:property value="date"/> </td>
         <td><s:property value="content"/> </td>
         <td>
          <a href="Edit.action?id=<s:property value="id"/>">编辑</a>
         </td>
         <td>
         <a href="Delete.action?id=<s:property value="id"/>">删除</a>
         </td>
        </tr>
       </s:iterator>
    </table>
    </s:form>
</body>
</html>

错误页面errors.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
<head>
    <title>My JSP 'hello.jsp' starting page</title>
</head>

<body>
    <h1>Error!!!</h1>
</body>
</html>

抱歉!评论已关闭.