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

Posted wangjian_an

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaEE框架——hibernate框架的综合使用相关的知识,希望对你有一定的参考价值。

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>
        JAVAEE框架技术之14SSM综合案例 产品管理CRUD

在JavaEE中使用Hibernate框架

杨老师课堂之JavaEE三大框架Hibernate入门第一课

杨老师课堂之JavaEE三大框架Hibernate入门教程第一课

JAVAEE框架技术之17之SSM综合案例 角色管理

JAVAEE框架技术之17之SSM综合案例 角色管理