关闭

JavaEE框架——hibernate框架的综合使用

标签: hibernatejava ee数据库框架
833人阅读 评论(0) 收藏 举报
分类:

hibernate框架的综合使用——通过使用hibernate框架多数据库的单表和多表进行增删改查,下面是详细代码

1.先通过蚂蚁搬家Ant建立数据库
createTables.sql

CREATE DATABASE mydb character set  utf8;
use mydb;
create table student(
    id varchar(32) primary key,
    name varchar(20),
    age int ,
    deptId varchar(32)
);
insert into student values('S001','Jack',20,'D001');
insert into student values('S002','TOM',21,'D001');
insert into student values('S003','张三',22,'D001');
insert into student values('S004','李四',23,'D001');

multi.sql

use mydb;
create table stud(
    id varchar(32) primary key,
    name varchar(20),
    age int ,
    deptId varchar(32)
);

create table dept(
    id varchar(32) primary key,
    name varchar(20)
);
ALTER TABLE stud ADD CONSTRAINT fk_dept FOREIGN KEY(deptId) REFERENCES dept(id);

insert into dept values('D001','信息科学与工程学院');
insert into dept values('D002','土木学院');

insert into stud values('S001','Jack',20,'D001');
insert into stud values('S002','TOM',21,'D001');
insert into stud values('S003','张三',22,'D001');
insert into stud values('S004','李四',23,'D001');

把build.xml放在项目目录下
build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="dft">
    <property name="url" value="jdbc:mysql://127.0.0.1:3306/sstud?useUnicode=true&amp;characterEncoding=UTF-8"></property>
    <property name="driver" value="com.mysql.jdbc.Driver"></property>
    <property name="user" value="root"></property>
    <property name="pwd" value="1234"></property>

    <target name="dft" depends="createStudentTable" >
        <echo>Hello</echo>
    </target>
        <target name="createStudentTable">
        <sql userid="${user}" password="${pwd}" url="${url}" driver="${driver}" delimiter=";">
            <fileset dir="${basedir}/WebRoot/sql">
                <include name="*.sql"/>
            </fileset>
            <classpath>
                <fileset dir="${basedir}/WebRoot/WEB-INF/lib">
                    <include name="*.jar"/>
                </fileset>
            </classpath>
    </sql>
    </target>
            <target name="createMutiTable">
            <sql userid="${user}" password="${pwd}" url="${url}" driver="${driver}" delimiter=";">
                <fileset dir="${basedir}/WebRoot/sql">
                    <include name="mutiSql.sql"/>
                </fileset>
                <classpath>
                    <fileset dir="${basedir}/WebRoot/WEB-INF/lib">
                        <include name="*.jar"/>
                    </fileset>
                </classpath>
        </sql>
        </target>
</project>

2.写hibernate配置文件和值对象

在项目的src目录下加上配置文件
hibernate.cfg.xml

<?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">
<hibernate-configuration>

<session-factory>
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="connection.url">
        jdbc:mysql://127.0.0.1:3306/mydb
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">1234</property>

    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>

    <mapping resource="cn/hncu/domain/Student.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

在值对象的目录下写入Student.hbm.xml映射文件
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">
<hibernate-mapping package="cn.hncu.domain">
    <class name="Student" table="student" catalog="mydb">
        <id name="studId" type="java.lang.String">
            <column name="id" length="32"></column>
        </id>
        <property name="studName" type="java.lang.String">
            <column name="name" length="20"></column>
        </property>
        <property name="studAge" type="java.lang.Integer">
            <column name="age"></column>
        </property>
        <property name="deptId" type="java.lang.String">
            <column name="deptId" length="32"></column>
        </property>
    </class>


    <class name="Stud" table="stud" catalog="mydb">
        <id name="studId" type="java.lang.String">
            <column name="id" length="32"></column>
        </id>
        <property name="studName" type="java.lang.String">
            <column name="name" length="20"></column>
        </property>
        <property name="studAge" type="java.lang.Integer">
            <column name="age"></column>
        </property>

    <!-- 在多方配置一个一方值对象:为Student类中的dept属性注入值  -->
            <many-to-one name="dept" class="Dept" fetch="select">
                <column name="deptId" length="32"></column>
            </many-to-one>
    </class>

    <class name="Dept" table="dept" catalog="mydb">
        <id name="deptId" type="java.lang.String">
            <column name="id" length="32"></column>
        </id>
        <property name="deptName" type="java.lang.String">
            <column name="name" length="20"></column>
        </property>

     <!-- 在一方为所拥有的多方集合注入值:为Dept类中的students属性注入值 ,级联必须要配置属性:cascade="all"  -->
         <set name="students" table="stud" catalog="mydb" inverse="true"  cascade="none">
       <key>
         <column name="deptId" length="32"></column>
       </key>
       <one-to-many class="Stud"/>
    </set>
    </class>

</hibernate-mapping>

Student.java值对象

package cn.hncu.domain;

public class Student {
    private String studId;
    private String studName;
    private Integer studAge;
    private String deptId;
    public String getStudId() {
        return studId;
    }
    public void setStudId(String studId) {
        this.studId = studId;
    }
    public String getStudName() {
        return studName;
    }
    public void setStudName(String studName) {
        this.studName = studName;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((studId == null) ? 0 : studId.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;
        Student other = (Student) obj;
        if (studId == null) {
            if (other.studId != null)
                return false;
        } else if (!studId.equals(other.studId))
            return false;
        return true;
    }
    public Integer getStudAge() {
        return studAge;
    }
    public void setStudAge(Integer studAge) {
        this.studAge = studAge;
    }
    public String getDeptId() {
        return deptId;
    }
    public void setDeptId(String deptId) {
        this.deptId = deptId;
    }
    @Override
    public String toString() {
        return "Student [studId=" + studId + ", studName=" + studName
                + ", studAge=" + studAge + ", deptId=" + deptId + "]";
    }
}

Stud.java值对象

package cn.hncu.domain;

public class Stud {
    private String studId;
    private String studName;
    private Integer studAge;
    private Dept dept;
    public String getStudId() {
        return studId;
    }
    public void setStudId(String studId) {
        this.studId = studId;
    }
    public String getStudName() {
        return studName;
    }
    public void setStudName(String studName) {
        this.studName = studName;
    }
    public Integer getStudAge() {
        return studAge;
    }
    public void setStudAge(Integer studAge) {
        this.studAge = studAge;
    }
    public Dept getDept() {
        return dept;
    }
    public void setDept(Dept dept) {
        this.dept = dept;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((studId == null) ? 0 : studId.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;
        Stud other = (Stud) obj;
        if (studId == null) {
            if (other.studId != null)
                return false;
        } else if (!studId.equals(other.studId))
            return false;
        return true;
    }

}

Dept.java值对象

package cn.hncu.domain;

import java.util.HashSet;
import java.util.Set;

public class Dept {
    private String deptId;
    private String deptName;
    private Set<Stud> students=new HashSet<Stud>();
    public String getDeptId() {
        return deptId;
    }
    public void setDeptId(String deptId) {
        this.deptId = deptId;
    }
    public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public Set<Stud> getStudents() {
        return students;
    }
    public void setStudents(Set<Stud> students) {
        this.students = students;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((deptId == null) ? 0 : deptId.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;
        Dept other = (Dept) obj;
        if (deptId == null) {
            if (other.deptId != null)
                return false;
        } else if (!deptId.equals(other.deptId))
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "Dept [deptId=" + deptId + ", deptName=" + deptName
                + ", students=" + students + "]";
    }




}

3.写前端页面
index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>hibernate技术演示</title>
</head>
<body>
    <a href="<c:url value='/DemoServlet'/>">演示单表操作</a><br/>
    <a href="<c:url value='/MultiServlet'/>">演示多表操作</a>
</body>
</html>

dem1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>hibernate技术演示——单表操作</title>
<script type="text/javascript" src="<c:url value='/js/ajax.js'/>"></script>
<script type="text/javascript">
    var path = "<c:url value='/'/>";
    function showChange(obj) {
        var id = obj.value;
        var ajax = new Ajax();
        var url = path + "DemoServlet?cmd=updateStudent&id=" + id;
        ajax.get(url, succ, failure);
    }
    function succ(data) {
        if (data == "1") {
            window.location.href = path + "/DemoServlet";
        }
    }
    function failure(data) {
        alert(data);
    }

    function query(){
        var id=document.getElementById("id").value;
        id=id.trim();
        var name=document.getElementById("name").value;
        name=name.trim();
        var age=document.getElementById("age").value;
        age=age.trim();
        var deptId=document.getElementById("deptId").value;
        deptId=deptId.trim();
        var ajax = new Ajax();
        var url=path+"DemoServlet";
        param="cmd=queryStudent&id="+id+"&name="+name+"&age="+age+"&deptId="+deptId;
        ajax.post(url, param, succ, failure);
    }
</script>
</head>
<body>
    <h3>hibernate技术演示——单表操作</h3>
    <table>
        <tr>
            <td>学生ID</td>
            <td>学生姓名</td>
            <td>学生年龄</td>
            <td>部门ID</td>
        </tr>
        <c:forEach items="${sessionScope.list }" var="stud">
            <tr>
                <td>${stud.studId}</td>
                <td>${stud.studName}</td>
                <td>${stud.studAge}</td>
                <td>${stud.deptId}</td>
                <td><a
                    href="<c:url value='/DemoServlet?cmd=delStudent&id=${stud.studId}'/>">删除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    <h3>添加一个学生信息</h3>
    <form action="<c:url value='/DemoServlet?cmd=addStudent'/>"
        method="post">
        <table>
            <tr>
                <td>学号<font color="red">*</font>
                </td>
                <td><input type="text" name="id" /></td>
            </tr>
            <tr>
                <td>姓名<font color="red">*</font>
                </td>
                <td><input type="text" name="name" /></td>
            </tr>
            <tr>
                <td>年龄<font color="red"></font>
                </td>
                <td><input type="text" name="age" /></td>
            </tr>
            <tr>
                <td>部门编号<font color="red">*</font>
                </td>
                <td><input type="text" name="deptId" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="添加" /></td>
            </tr>
        </table>
    </form>
    <h3>修改一个学生信息</h3>
    <select onchange="showChange(this)">

        <option value="none">请选择学生</option>
        <c:forEach items="${sessionScope.list }" var="stud">
            <option value="${stud.studId}">${stud.studId}</option>
        </c:forEach>
    </select>
    <c:if test="${!empty updateStud }">
        <form action="<c:url value='/DemoServlet?cmd=addStudent'/>"
            method="post">
            <table>
                <tr>
                    <td>学号<font color="red">*</font>
                    </td>
                    <td><input type="text" name="id" value="${updateStud.studId }" />
                    </td>
                </tr>
                <tr>
                    <td>姓名<font color="red">*</font>
                    </td>
                    <td><input type="text" name="name"
                        value="${updateStud.studName }" /></td>
                </tr>
                <tr>
                    <td>年龄<font color="red"></font>
                    </td>
                    <td><input type="text" name="age"
                        value="${updateStud.studAge }" /></td>
                </tr>
                <tr>
                    <td>部门编号<font color="red">*</font>
                    </td>
                    <td><input type="text" name="deptId"
                        value="${updateStud.deptId }" /></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="修改" /></td>
                </tr>
            </table>
        </form>
        <c:remove var="updateStud" />
    </c:if>
    <h3>学生信息查询</h3>
    <table>
        <tr>
            <td>学号<font color="red">*</font>
            </td>
            <td><input type="text" id="id" name="id" /></td>
        </tr>
        <tr>
            <td>姓名<font color="red">*</font>
            </td>
            <td><input type="text"id="name" name="name" /></td>
        </tr>
        <tr>
            <td>年龄<font color="red"></font>
            </td>
            <td><input type="text" id="age" name="age" /></td>
        </tr>
        <tr>
            <td>部门编号<font color="red"></font>
            </td>
            <td><input type="text" id="deptId" name="deptId" /></td>
        </tr>
        <tr>
            <td colspan="2"><input type="button" value="查询" onclick="query()" />
            </td>
        </tr>
    </table>
    <h3>查询结果</h3>
    <c:if test="${!empty sessionScope.qlist }">
        <table>
            <tr>
                <td>学号</td>
                <td>姓名</td>
                <td>年龄</td>
                <td>学院编号</td>
                <td>操作</td>
            </tr>
            <c:forEach items="${sessionScope.qlist }" var="stud">
                <tr>
                    <td>${stud.studId}</td>
                    <td>${stud.studName}</td>
                    <td>${stud.studAge}</td>
                    <td>${stud.deptId}</td>
                    <td><a
                        href="<c:url value='/DemoServlet?cmd=delStudent&id=${stud.studId}'/>">删除</a>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </c:if>
</body>
</html>

multi.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<title>hibernate技术演示——多表操作</title>
<script type="text/javascript" src="<c:url value='/js/ajax.js'/>"></script>
<script type="text/javascript">
    var path = "<c:url value='/'/>";
    function succ(data) {
            alert(data);
            window.location.href = path + "/MultiServlet";
    }
    function failure(data) {
        alert(data);
    }
    function addDept(){
        var deptId=document.getElementById("deptId").value;
        deptId=deptId.trim();
        var deptName=document.getElementById("deptName").value;
        deptName=deptName.trim();
        var ajax = new Ajax();
        var url=path+"MultiServlet";
        var param="cmd=addDept&deptId="+deptId+"&deptName="+deptName;
        ajax.post(url, param, succ, failure);
    }

</script>
<style type="text/css">
table {
    border: 1px solid;
}

td {
    border: 1px solid;
    border-collapse: none;
}
</style>
</head>
<body>
    <h3>hibernate技术演示——多表操作</h3>

    <table>
        <tr>
            <td>部门ID</td>
            <td>部门</td>
            <td>学生ID</td>
            <td>学生姓名</td>
            <td>学生年龄</td>
        </tr>
        <c:forEach items="${sessionScope.depts }" var="dept">
            <c:if test="${!empty dept.students }">
                <c:forEach items="${dept.students }" var="stud">
                    <tr>
                        <td>${dept.deptId}</td>
                        <td>${dept.deptName}</td>
                        <td>${stud.studId}</td>
                        <td>${stud.studName}</td>
                        <td>${stud.studAge}</td>
                        <td><a
                            href="<c:url value='/MultiServlet?cmd=delStudent&studId=${stud.studId}'/>">删除</a>
                        </td>
                    </tr>
                </c:forEach>
            </c:if>
            <c:if test="${empty dept.students }">
                <tr>
                    <td>${dept.deptId}</td>
                    <td>${dept.deptName}</td>
                </tr>
            </c:if>
        </c:forEach>
    </table>
    <h3>通过学院id查询学院表,把该学院的学生信息也同时输出来</h3>
    <form action="<c:url value='/MultiServlet?cmd=queryDeptById'/>"
        method="post">
        <table>
            <tr>
                <td>学院编号<font color="red">*</font></td>
                <td><input type="text" name="deptId">
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="查询">
                </td>
            </tr>
        </table>
    </form>
    <c:if test="${!empty sessionScope.map }">
        <h3>查询结果</h3>
             学院名称:${map.deptName}
             <table>
            <tr>
                <td>学号</td>
                <td>姓名</td>
                <td>年龄</td>
                <td>学院编号</td>
                <td>操作</td>
            </tr>
            <c:forEach items="${map.qlist}" var="stud">
                <tr>
                    <td>${stud.studId}</td>
                    <td>${stud.studName}</td>
                    <td>${stud.studAge}</td>
                    <td>${map.deptId}</td>
                    <td><a
                        href="<c:url value='/MultiServlet?cmd=delStudent&studId=${stud.studId}'/>">删除</a>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </c:if>
    <h3>删除部门演示</h3>
    <table>
        <tr>
            <td>部门ID</td>
            <td>部门</td>
        </tr>
        <c:forEach items="${sessionScope.depts }" var="dept">
            <tr>
                <td>${dept.deptId }</td>
                <td>${dept.deptName }</td>
                <td><a
                    href="<c:url value='/MultiServlet?cmd=delDept&deptId=${dept.deptId }'/>">删除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    <h3>添加部门演示</h3>
        <table>
        <tr>
            <td>部门ID<font color="red">*</font></td>
            <td><input type="text" id="deptId" name="deptId"/></td>
        </tr>
        <tr>
            <td>部门名称<font color="red">*</font></td>
            <td><input type="text" id="deptName" name="deptName"/></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="button" value="添加" onclick="addDept()"/></td>
        </tr>
    </table>
</body>
</html>

ajax.js

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<title>hibernate技术演示——多表操作</title>
<script type="text/javascript" src="<c:url value='/js/ajax.js'/>"></script>
<script type="text/javascript">
    var path = "<c:url value='/'/>";
    function succ(data) {
            alert(data);
            window.location.href = path + "/MultiServlet";
    }
    function failure(data) {
        alert(data);
    }
    function addDept(){
        var deptId=document.getElementById("deptId").value;
        deptId=deptId.trim();
        var deptName=document.getElementById("deptName").value;
        deptName=deptName.trim();
        var ajax = new Ajax();
        var url=path+"MultiServlet";
        var param="cmd=addDept&deptId="+deptId+"&deptName="+deptName;
        ajax.post(url, param, succ, failure);
    }

</script>
<style type="text/css">
table {
    border: 1px solid;
}

td {
    border: 1px solid;
    border-collapse: none;
}
</style>
</head>
<body>
    <h3>hibernate技术演示——多表操作</h3>

    <table>
        <tr>
            <td>部门ID</td>
            <td>部门</td>
            <td>学生ID</td>
            <td>学生姓名</td>
            <td>学生年龄</td>
        </tr>
        <c:forEach items="${sessionScope.depts }" var="dept">
            <c:if test="${!empty dept.students }">
                <c:forEach items="${dept.students }" var="stud">
                    <tr>
                        <td>${dept.deptId}</td>
                        <td>${dept.deptName}</td>
                        <td>${stud.studId}</td>
                        <td>${stud.studName}</td>
                        <td>${stud.studAge}</td>
                        <td><a
                            href="<c:url value='/MultiServlet?cmd=delStudent&studId=${stud.studId}'/>">删除</a>
                        </td>
                    </tr>
                </c:forEach>
            </c:if>
            <c:if test="${empty dept.students }">
                <tr>
                    <td>${dept.deptId}</td>
                    <td>${dept.deptName}</td>
                </tr>
            </c:if>
        </c:forEach>
    </table>
    <h3>通过学院id查询学院表,把该学院的学生信息也同时输出来</h3>
    <form action="<c:url value='/MultiServlet?cmd=queryDeptById'/>"
        method="post">
        <table>
            <tr>
                <td>学院编号<font color="red">*</font></td>
                <td><input type="text" name="deptId">
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="查询">
                </td>
            </tr>
        </table>
    </form>
    <c:if test="${!empty sessionScope.map }">
        <h3>查询结果</h3>
             学院名称:${map.deptName}
             <table>
            <tr>
                <td>学号</td>
                <td>姓名</td>
                <td>年龄</td>
                <td>学院编号</td>
                <td>操作</td>
            </tr>
            <c:forEach items="${map.qlist}" var="stud">
                <tr>
                    <td>${stud.studId}</td>
                    <td>${stud.studName}</td>
                    <td>${stud.studAge}</td>
                    <td>${map.deptId}</td>
                    <td><a
                        href="<c:url value='/MultiServlet?cmd=delStudent&studId=${stud.studId}'/>">删除</a>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </c:if>
    <h3>删除部门演示</h3>
    <table>
        <tr>
            <td>部门ID</td>
            <td>部门</td>
        </tr>
        <c:forEach items="${sessionScope.depts }" var="dept">
            <tr>
                <td>${dept.deptId }</td>
                <td>${dept.deptName }</td>
                <td><a
                    href="<c:url value='/MultiServlet?cmd=delDept&deptId=${dept.deptId }'/>">删除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    <h3>添加部门演示</h3>
        <table>
        <tr>
            <td>部门ID<font color="red">*</font></td>
            <td><input type="text" id="deptId" name="deptId"/></td>
        </tr>
        <tr>
            <td>部门名称<font color="red">*</font></td>
            <td><input type="text" id="deptName" name="deptName"/></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="button" value="添加" onclick="addDept()"/></td>
        </tr>
    </table>
</body>
</html>

4.写工具类和过滤器
BaseServlet.java

package cn.hncu.util;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String cmd=req.getParameter("cmd");
        if(null==cmd||cmd.trim().equals("")){
            cmd="excute";
        }
        try {
            Method m=this.getClass().getDeclaredMethod(cmd, HttpServletRequest.class,HttpServletResponse.class);
            m.invoke(this, req,resp);

        } catch (NoSuchMethodException e) {
            throw new RuntimeException("没有此方法:" + e.getMessage(), e);
        }catch(InvocationTargetException e){
            throw new RuntimeException("目标方法执行失败:" + e.getMessage(), e);
        }catch(IllegalAccessException e){
            throw new RuntimeException("你可能访问了一个私有的方法:" + e.getMessage(), e);
        }catch(Exception e){
            throw new RuntimeException(e.getMessage(), e);
        }

    }
    public abstract void excute(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException ;
}

CharaterFilter.java

package cn.hncu.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class CharaterFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {

    }

}

HibernateSessionFactory.java

package cn.hncu.hib;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {
    private static final String CONFIG_FILENAME="/hibernate.cfg.xml";//文件名
    private static final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();//本地线程
    private static Configuration config=new Configuration();
    private static SessionFactory sessionFactory;//声明一个SessionFactory对象
    static{
        try {
            config.configure(CONFIG_FILENAME);
            sessionFactory=config.buildSessionFactory();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public static Session getSession() throws HibernateException{
        Session session=threadLocal.get();
        if(session==null||!session.isOpen()){//如果这个链接没开
            if (sessionFactory==null) {
                config.configure(CONFIG_FILENAME);
                sessionFactory = config.buildSessionFactory();
            }
            session=(sessionFactory!=null)?sessionFactory.openSession():null;//是否开放一个session
            threadLocal.set(session);//把session放入本地线程
        }
        return session;
    }

    //关闭连接
    public static void closeSession() throws HibernateException{
        Session session=threadLocal.get();
        threadLocal.remove();
        if(session!=null){
            session.close();
        }

    }

}

5.单表的功能demo
DemoServlet.java

package cn.hncu.demo;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.demo.service.DemoServiceImpl;
import cn.hncu.domain.Student;
import cn.hncu.util.BaseServlet;



public class DemoServlet extends BaseServlet {
    private DemoServiceImpl service=new DemoServiceImpl();
    @Override
    public void excute(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Student> list=service.queryAllStudent();
        req.getSession().setAttribute("list", list);
        resp.sendRedirect(getServletContext().getContextPath()+"/jsps/demo1.jsp");
    }

    public void delStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id=req.getParameter("id");
        Student stud=new Student();
        stud.setStudId(id);
        stud=service.queryAStudent(stud);
        service.delStudent(stud);

        System.out.println(stud);
        List<Student> qlist=(List<Student>) req.getSession().getAttribute("qlist");
        if(qlist!=null){
            if(qlist.contains(stud)){
                System.out.println("qlist:"+qlist);
                qlist.remove(stud);//注意写equal方法
            }
        }
        resp.sendRedirect(getServletContext().getContextPath()+"/DemoServlet");
    }
    public void addStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Student stud=new Student();
        String id=req.getParameter("id");
        stud.setStudId(id);
        String name=req.getParameter("name");
        stud.setStudName(name);
        String strAge=req.getParameter("age");

        try {
            Integer age=Integer.parseInt(strAge);
            if(age>0){
                stud.setStudAge(age);
            }
        } catch (NumberFormatException e) {
        }
        String deptId=req.getParameter("deptId");
        stud.setDeptId(deptId);
        service.addStudent(stud);
        resp.sendRedirect(getServletContext().getContextPath()+"/DemoServlet");
    }

    public void updateStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Student stud=new Student();
        String id=req.getParameter("id");
        stud.setStudId(id);
        Student updateStud=service.queryAStudent(stud);
        req.getSession().setAttribute("updateStud", updateStud);
        resp.getWriter().print("1");
    }

    public void queryStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Student stud=new Student();
        String id=req.getParameter("id");
        stud.setStudId(id);
        String name=req.getParameter("name");
        stud.setStudName(name);
        String strAge=req.getParameter("age");
        try {
            Integer age=Integer.parseInt(strAge);
            if(age>0){
                stud.setStudAge(age);
            }
        } catch (NumberFormatException e) {
        }
        String deptId=req.getParameter("deptId");
        stud.setDeptId(deptId);
        List<Student> qlist=service.queryStudent(stud);
        req.getSession().setAttribute("qlist", qlist);
        resp.getWriter().print("1");
    }

}

DemoServiceImpl.java

package cn.hncu.demo.service;

import java.util.List;

import cn.hncu.demo.dao.DemoDaoJdbc;
import cn.hncu.domain.Student;

public class DemoServiceImpl {
    DemoDaoJdbc dao=new DemoDaoJdbc();
    public List<Student> queryAllStudent(){
        return dao.queryAllStudent();
    }
    public void delStudent(Student stud) {
        dao.delStudent(stud);
    }
    public void addStudent(Student stud) {
        dao.addStudent(stud);

    }
    public Student queryAStudent(Student stud) {
        return dao.queryAStudent(stud);
    }
    public List<Student> queryStudent(Student stud) {
        return dao.queryStudent(stud);
    }
}

DemoDaoJdbc.java

package cn.hncu.demo.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.hncu.domain.Student;
import cn.hncu.hib.HibernateSessionFactory;

public class DemoDaoJdbc {
    public List<Student> queryAllStudent(){
        Session session=HibernateSessionFactory.getSession();
        //无论是Load 还是 Get 都会首先查找缓存(一级缓存) 如果没有,才会去数据库查找,调用Clear() 方法,可以强制清除Session缓存
        session.clear();
        Query query=session.createQuery("from Student");
        List<Student> list=query.list();
        return list;
    }
    public void delStudent(Student stud) {
        Session session=HibernateSessionFactory.getSession();

        Transaction tr=session.beginTransaction();
        try {
            session.delete(stud);
            session.flush();
        } catch (Exception e) {
            System.out.println("回滚了");
//          tr.rollback();
        }
        tr.commit();//删除没有事务不行!
    }

    @Test
    public void t(){
        Student stud=new Student();
        stud.setStudId("S003");
        delStudent(stud);
        System.out.println(queryAllStudent());
    }

    public void addStudent(Student stud) {
        Session session=HibernateSessionFactory.getSession();
        Transaction tr=session.beginTransaction();
        try {
            session.saveOrUpdate(stud);
//          session.update(stud);
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        tr.commit();
    }

    public Student queryAStudent(Student stud) {
        Session session=HibernateSessionFactory.getSession();
        String hql="from Student s where s.studId=?";
        Query query=session.createQuery(hql);
        query.setParameter(0, stud.getStudId());
        List<Student> list=query.list();
        if(list!=null&&list.size()>0){
            return list.get(0);
        }
        return null;
    }
    public List<Student> queryStudent(Student stud) {
        Session session=HibernateSessionFactory.getSession();
        String hql="from Student s where 1=1";
        if(stud.getStudId()!=null&&stud.getStudId().trim().length()>0){
            hql+=" and s.studId='"+stud.getStudId()+"'";
        }
        if(stud.getStudName()!=null&&stud.getStudName().trim().length()>0){
            hql+=" and s.studName like '%"+stud.getStudName()+"%'";
        }
        if(stud.getStudAge()!=null){
            hql+=" and s.studAge ="+stud.getStudAge();
        }
        if(stud.getDeptId()!=null&&stud.getDeptId().trim().length()>0){
            hql+="and s.deptId='"+stud.getDeptId()+"'";
        }
        Query query=session.createQuery(hql);
        List<Student> list=query.list();
        return list;
    }
}

6.多表操作模块
MultiServlet.java

package cn.hncu.multi;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.domain.Dept;
import cn.hncu.domain.Stud;
import cn.hncu.multi.service.MultiServiceImpl;
import cn.hncu.util.BaseServlet;

public class MultiServlet extends BaseServlet {
    private MultiServiceImpl service=new MultiServiceImpl();
    @Override
    public void excute(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        List<Dept> depts=service.queryAll();
        req.getSession().setAttribute("depts", depts);
        resp.sendRedirect(getServletContext().getContextPath()+"/jsps/multi.jsp");
    }

    public void queryDeptById(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Map<String,Object> map=new HashMap<String,Object>();
        String deptId=req.getParameter("deptId");

        Dept dept=service.queryDeptById(deptId);
        if(dept!=null){
            map.put("deptId", dept.getDeptId());
            map.put("deptName", dept.getDeptName());
            map.put("qlist", dept.getStudents());
        }
        req.getSession().setAttribute("map", map);
        resp.sendRedirect(getServletContext().getContextPath()+"/jsps/multi.jsp");
    }

    public void delStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String studId=req.getParameter("studId");
        Stud stud=new Stud();
        stud.setStudId(studId);
        service.delStudent(stud);
        excute(req, resp);
    }
    public void delDept(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String deptId=req.getParameter("deptId");
        Dept dept=new Dept();
        dept.setDeptId(deptId);
        service.delDept(dept);
        excute(req, resp);
    }

    public void addDept(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
//      resp.setContentType("text/html");
        String deptId=req.getParameter("deptId");
        String deptName=req.getParameter("deptName");
        Dept dept=new Dept();
        dept.setDeptId(deptId);
        dept.setDeptName(deptName);
        service.addDept(dept);
        PrintWriter out = resp.getWriter();
        out.write("1");
        out.close();
    }
}

MultiServiceImpl.java

package cn.hncu.multi.service;

import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.hncu.demo.dao.DemoDaoJdbc;
import cn.hncu.domain.Dept;
import cn.hncu.domain.Stud;
import cn.hncu.hib.HibernateSessionFactory;
import cn.hncu.multi.dao.MultiServiceJdbc;

public class MultiServiceImpl {
    private MultiServiceJdbc dao=new MultiServiceJdbc();
    private DemoDaoJdbc demodao=new DemoDaoJdbc();
    public List<Dept> queryAll(){
        return dao.queryAll();
    }
    public Dept queryDeptById(String deptId) {
        return dao.queryDeptById(deptId);
    }
    public void delStudent(Stud stud) {
        Session session=HibernateSessionFactory.getSession();
        Transaction tr=session.beginTransaction();
        dao.delStudent(stud);
        tr.commit();//删除没有事务不行!
    }
    public void delDept(Dept dept) {
        dept=dao.queryDeptById(dept.getDeptId());//这里要获得新的dept
        Session session=HibernateSessionFactory.getSession();//这里搞事务
        Transaction tr=session.beginTransaction();
        if (dept!=null) {
            Set<Stud> students = dept.getStudents();
            if (students != null && students.size() > 0) {
                for (Stud stud : students) {
                    dao.delStudent(stud);
                }
            }
            dao.delDept(dept);
        }
        tr.commit();
    }

    public void addDept(Dept dept) {
        Session session=HibernateSessionFactory.getSession();//这里搞事务
        Transaction tr=session.beginTransaction();
        dao.addDept(dept);
        tr.commit();
    }
}

MultiDaoJdbc.java

package cn.hncu.multi.dao;

import java.util.List;
import java.util.Set;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.hncu.domain.Dept;
import cn.hncu.domain.Stud;
import cn.hncu.hib.HibernateSessionFactory;

public class MultiServiceJdbc {
    public List<Dept> queryAll(){
        Session session=HibernateSessionFactory.getSession();
        return session.createQuery("from Dept").list();

    }
    public Dept queryDeptById(String deptId) {
        Session session=HibernateSessionFactory.getSession();
        session.flush();
        String hql="from Dept where 1=1";
        if(deptId!=null&&deptId.trim().length()>0){
            hql+=" and id=:deptId";
        }
        Query query=session.createQuery(hql);
        if(deptId!=null&&deptId.trim().length()>0){
            query.setParameter("deptId", deptId);
        }
        Dept resDept =null;
        if (query.list()!=null&&query.list().size()>0) {
            resDept= (Dept) query.list().get(0);
        }
        return resDept;
    }



    public void delDept(Dept dept) {
        Session session=HibernateSessionFactory.getSession();
        session.delete(dept);

    }

    public void delStudent(Stud stud) {
        Session session=HibernateSessionFactory.getSession();
        try {
            session.delete(stud);
            session.flush();
        } catch (Exception e) {
            System.out.println("回滚了");
        }
    }

    @Test
    public void t(){
//      System.out.println(queryAll());
//      delDept("d004");
    }
    public void addDept(Dept dept) {
        Session session=HibernateSessionFactory.getSession();//这里搞事务
        session.saveOrUpdate(dept);

    }
}

7.其他
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    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_3_0.xsd">
  <display-name></display-name> 

  <filter>
    <filter-name>charset</filter-name>
    <filter-class>cn.hncu.filter.CharaterFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>charset</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
    <servlet-name>DemoServlet</servlet-name>
    <servlet-class>cn.hncu.demo.DemoServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>MultiServlet</servlet-name>
    <servlet-class>cn.hncu.multi.MultiServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>DemoServlet</servlet-name>
    <url-pattern>/DemoServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>MultiServlet</servlet-name>
    <url-pattern>/MultiServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:123763次
    • 积分:2773
    • 等级:
    • 排名:第13789名
    • 原创:154篇
    • 转载:4篇
    • 译文:0篇
    • 评论:5条
    博客专栏