使用hibernate框架制作学生信息查询(多表查询)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31678809/article/details/77248390

需求:通过学院表和学生表进行关联,从浏览器点击学院信息,显示出各学院学生信息

功能展示:

这里写图片描述

代码演示:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

</head>
<body>
    <h2>学院信息</h2>
    <table>
        <c:forEach items="${list}" var="dept">
            <tr>
                <td><a target="frm"
                    href="<c:url value='/DemoServlet?cmd=queryStudents&id=${dept.id}'/>"
                    class="type"> ${dept.name} </a></td>
            </tr>
        </c:forEach>
    </table>
    <br />
    <a href="<c:url value='/DemoServlet?cmd=addDept'/>">添加部门</a>
    <br />
    <iframe name="frm"
        style="display:block;width:50%;height:100%;border-width:0px">
    </iframe>
</body>
</html>

我们通过隐藏帧来显示搜索后的学生信息:qlist.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<head>
<style type="text/css">
table {
    border: 1px solid gray;
    border-collapse: collapse;
    width: 60%;
}

td {
    border: 1px solid gray;
    padding: 5px;
}
</style>
</head>

<h2>查询结果</h2>
<table>
    <tr style="background:#7D7DFF;">
        <td>学号</td>
        <td>姓名</td>
        <td>年龄</td>
        <td>学员名称</td>
        <td>操作</td>
    </tr>
    <c:forEach items="${students}" var="stud">
        <tr>
            <td>${stud.studId }</td>
            <td>${stud.studName }</td>
            <td>${stud.age }</td>
            <td>${stud.dept.name }</td>
            <td><a
                href="<c:url value='/DemoServlet?cmd=delStudent&studId=${stud.studId }' />">删除</a>
            </td>
        </tr>
    </c:forEach>
</table>

我们需要先来配置hiberbate所需的文件: Student.hbm.xml:通过Student中配置<many-to-one>来匹配学生和学院,而在Dept中通过<set> 来配置学院和学生的一对多关系,我们需要将set中的inverse设为true,这个参数能够将两对象设成级联,这样,就可以通过查询学生后自动索引出学院信息

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.hncu.demo.domain">
    <class name="Student" table="students" catalog="hib">
        <!-- id标记是指Student类中的属性变量,该属性是对应表主键字段的 -->
        <id name="studId" type="java.lang.String">
            <!-- column标记是指数据库表中的哪一列(字段) -->
            <column name="id" length="8"></column>
        </id>
        <!-- 其他字段都用property 只有主键用id -->
        <property name="studName" type="java.lang.String">
            <column name="name" length="40"></column>
        </property>
        <property name="age" type="java.lang.Integer">
            <column name="age"></column>
        </property>
        <many-to-one name="dept" class="Dept" fetch="select">
            <column name="deptId" length="8"></column>
        </many-to-one>
    </class>
    <class name="Dept" table="depts" catalog="hib">
        <id name="id" type="java.lang.String">
            <column name="id" length="8"></column>
            <generator class="assigned"></generator>
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="40"></column>
        </property>
        <set name="student" table="students" inverse="true" cascade="all">
            <key>
                <column name="deptId"></column><!-- 配置外键字段 -->
            </key>
            <one-to-many class="Student"/>
        </set>
    </class>

</hibernate-mapping>

我这里将Servlet整合通过继承BaseServlet通过子对象的方法名称加载方法,再来调用: Baseserlvet:

package cn.hncu.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * 基类, 1:修改HttpServletRequest增强 2:动态调用用户指定的方法?cmd=save....,默认为execute方法
 * 
 * @author <a href="mailto:jack@hncu.cn">杰克</a>
 * @version 1.0 2014-12-29
 */
public abstract class BaseServlet extends HttpServlet {
    private Logger log = Logger.getLogger(BaseServlet.class);
    private static final long serialVersionUID = 1L;

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

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String cmd = req.getParameter("cmd");
        if (null == cmd || cmd.trim().equals("")) {
            cmd = "execute";
        }
        log.debug("调用的方法为:" + cmd);
        try {
            Method method = this.getClass().getMethod(cmd,
                    HttpServletRequest.class, HttpServletResponse.class);
            method.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 execute(HttpServletRequest req,
            HttpServletResponse resp) throws Exception;
}

DemoServlet:

package cn.hncu.demo;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

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

import cn.hncu.demo.domain.Dept;
import cn.hncu.demo.domain.Student;
import cn.hncu.demo.service.DemoServiceImpl;
import cn.hncu.utils.BaseServlet;

public class DemoServlet extends BaseServlet {
    private DemoServiceImpl service = new DemoServiceImpl();

    @Override
    public void execute(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        List<Dept> list = service.queryAllStudent();
        req.getSession().setAttribute("list", list);
        String showPage = getInitParameter("show");
        resp.sendRedirect(getServletContext().getContextPath() + showPage);
    }



    public void addDept(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        Dept dept = new Dept();
        dept.setId("D004");
        dept.setName("创新学院");
        Student stud1 = new Student();
        stud1.setstudId("s101");
        stud1.setstudName("贾宝玉");
        stud1.setAge(20);
        stud1.setDept(dept);
        dept.getStudent().add(stud1);
        Student stud2 = new Student();
        stud2.setstudId("s102");
        stud2.setstudName("林黛玉");
        stud2.setAge(20);
        stud2.setDept(dept);
        dept.getStudent().add(stud2);
        Student stud3 = new Student();
        stud3.setstudId("s103");
        stud3.setstudName("林玉");
        stud3.setAge(20);
        stud3.setDept(dept);
        dept.getStudent().add(stud3);

        service.addDept(dept);
        resp.sendRedirect(getServletContext().getContextPath() + "/index.jsp");
    }

    public void queryStudents(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        String id = req.getParameter("id");
        Dept d = new Dept();
        d.setId(id);
        List<Dept> list = service.queryDept(d);
        d = list.get(0);
        Set<Student> s = d.getStudent();
        req.getSession().setAttribute("students", s);
        req.getRequestDispatcher("/jsps/qlist.jsp").forward(req, resp);
    }

}

DaoJdbc:

package cn.hncu.demo.dao;

import java.util.List;

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

import cn.hncu.demo.domain.Dept;
import cn.hncu.demo.domain.Student;
import cn.hncu.utils.HibernateUtil;

public class DemoDaoJdbc {
    public List<Dept> queryAllStudents() {
        Session session = HibernateUtil.getSession();
        Query q = session.createQuery("from Dept");// HQL
                                                    // =
                                                    // SQL中的关键字+
                                                    // Java(类名,属性名)
        List<Dept> list = q.list();
        return list;
    }

    public void delStudent(Student stud) {
        // Hibernate每次操作时重新获取session
        Session session = HibernateUtil.getSession();
        Transaction tran = session.beginTransaction();
        session.delete(stud);
        tran.commit();
        session.clear();// 每个session中有一级缓存,在删除后可能没有及时删除缓存中的数据
    }


    public List<Dept> queryDept(Dept dept) {
        boolean f1 = false, f2 = false, f3 = false;
        Session session = HibernateUtil.getSession();
        String hql = "from Dept d where 1=1";
        if (dept.getId() != null && dept.getId().trim().length() > 0) {
            hql = hql + " and d.id=:id";
            f1 = true;
        }
        if (dept.getName() != null && dept.getName().trim().length() > 0) {
            hql = hql + " and d.name like :name";
            f2 = true;
        }

        Query q = session.createQuery(hql);
        if (f1) {
            q.setParameter("id", dept.getId());
        }
        if (f2) {
            q.setParameter("name", "%" + dept.getName() + "%");
        }
        session.clear();
        return q.list();
    }

    public void addDept(Dept dept) {
        Session session = HibernateUtil.getSession();
        Transaction tran =session.beginTransaction();
        session.saveOrUpdate(dept);
        tran.commit();
        session.clear();
    }
}

这样我们就可以通过学院表和学生表进行关联,从浏览器点击学院信息,显示出各学院学生信息了

没有更多推荐了,返回首页