【框架】[Hibernate]利用Hibernate进行单表的增删改查-Web实例(1)

简介: 【框架】[Hibernate]利用Hibernate进行单表的增删改查-Web实例

前面两篇博客已经将Hibernate的基础知识讲解得差不多了,差不多到写实例的时候了。

本篇只用hibernate进行单表的增删改查、

应用Hibernate,对students表进行增删改查。

service层和DAO层,我都是直接写实现类了(因为这里主要是演示一下Hibernate的使用),如果是开发项目,注意一定要写接口!

准备数据库:

首先准备一个students表:

create database hib charset=utf8;
use hib;
create table students(
    sId varchar(8) primary key,
    sName varchar(40),
    sAge int,
    deptId varchar(8)
);

插入数据:

insert into students(sId,sName,sAge,deptId) values('S001','Jack',23,'D001');
insert into students(sId,sName,sAge,deptId) values('S002','Tom',25,'D001');
insert into students(sId,sName,sAge,deptId) values('S003','张三',43,'D001');
insert into students(sId,sName,sAge,deptId) values('S004','李四',55,'D001');
insert into students(sId,sName,sAge,deptId) values('S005','Jack',23,'D002');
insert into students(sId,sName,sAge,deptId) values('S006','Tom',25,'D003');
insert into students(sId,sName,sAge,deptId) values('S007','张三',43,'D002');
insert into students(sId,sName,sAge,deptId) values('S008','李四',55,'D002');

image.png

需要的Jar包

数据库连接包以及hibernate必须包,这些包在项目的WEBROOT/WEBINF的bin目录下都有。

image.png

链接:

https://github.com/chenhaoxiang/Java/blob/master/Hibernate/myHibWeb/myHibWeb.zip

部分核心源码:

Student.java:

package cn.hncu.domain;
public class Student {
    private String sId;
    private String sName;
    private Integer sAge;
    private String deptId;
    public String getDeptId() {
        return deptId;
    }
    public void setDeptId(String deptId) {
        this.deptId = deptId;
    }
    public Student() {
        super();
    }
    public String getsId() {
        return sId;
    }
    public void setsId(String sId) {
        this.sId = sId;
    }
    public String getsName() {
        return sName;
    }
    public void setsName(String sName) {
        this.sName = sName;
    }
    public Integer getsAge() {
        return sAge;
    }
    public void setsAge(Integer sAge) {
        this.sAge = sAge;
    }
    @Override
    public String toString() {
        return "Student [sId=" + sId + ", sName=" + sName + ", sAge=" + sAge
                + ", deptId=" + deptId + "]";
    }
}

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/hib
        </property>
        <property name="connection.username">root</property>
        <property name="connection.password">1234</property>
        <property name="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
          <!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于查错,
        程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。
        项目部署后可以设置为false,提高运行效率-->   
        <property name="hibernate.show_sql">true </property>   
        <!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。
        Fetch Size设的越大,读数据库的次数越少,速度越快,Fetch Size越小,读数据库的次数越多,速度越慢-->   
        <property name="jdbc.fetch_size">50 </property> 
        <!--jdbc.batch_size是指Hibernate批量插入,删除和更新时每次操作的记录数。
        Batch Size越大,批量操作的向数据库发送Sql的次数越少,速度就越快,同样耗用内存就越大-->   
        <property name="jdbc.batch_size">23 </property>  
        <!--jdbc.use_scrollable_resultset是否允许Hibernate用JDBC的可滚动的结果集。
        对分页的结果集。对分页时的设置非常有帮助-->   
        <property name="jdbc.use_scrollable_resultset">false </property> 
        <!--connection.useUnicode连接数据库时是否使用Unicode编码 -->
        <property name="connection.useUnicode">true</property>
        <!--connection.characterEncoding连接数据库时数据的传输字符集编码方式 -->
        <property name="connection.characterEncoding">utf-8</property>
        <mapping resource="cn/hncu/domain/Student.hbm.xml" />
    </session-factory>
</hibernate-configuration>


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">
    <!--name指的是POJO类的类名,table是数据库的表名,catalog是数据库的名称  -->
    <class name="Student" table="students" catalog="hib">
        <!--id表示此字段为数据库的主键,这里也可以用property来写,name为Student类的成员变量名,type为类型的包全名  -->
        <id name="sId" type="java.lang.String">
            <!--column表示映射的数据库的字段,name表示数据库中字段名,length表示varchar/char型的长度  -->
            <column name="sId" length="8"></column>
            <generator class="assigned"></generator>            
        </id>
        <property name="sName" type="java.lang.String">
            <column name="sName" length="40" />
        </property>
        <property name="sAge" type="java.lang.Integer">
            <column name="sAge" />
        </property>
        <property name="deptId" type="java.lang.String">
        <column name="deptId" length="8" />
     </property>
    </class>
</hibernate-mapping>

BaseServlet.java

package cn.hncu.utils;
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 {
    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");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String cmd = req.getParameter("cmd");
        if (null == cmd || cmd.trim().equals("")) {
            cmd = "execute";
        }
        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;
}

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 String configFile = "/hibernate.cfg.xml";
   private static Configuration config = new Configuration();
   private static SessionFactory sessionFactory =null;
   private static final ThreadLocal<Session> t = new ThreadLocal<Session>();
   static{
       try {
           config.configure(configFile);
           sessionFactory = config.buildSessionFactory();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
   }
   public static Session getSession() throws HibernateException{
       Session session = t.get();
       if(session == null || !session.isOpen()){
           if(sessionFactory==null){
               rebuildSessionFactory();
           }
           session = (sessionFactory!=null) ? sessionFactory.openSession() : null;
           t.set(session);
       }
       return session;
   }
   private static void rebuildSessionFactory() {
       try {
           config.configure(configFile);
           sessionFactory = config.buildSessionFactory();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
   }
   //关闭与数据库的会话
   public static void closeSession() throws HibernateException{
       Session session = t.get();
       t.set(null);
       if(session!=null){
           session.close();
       }
   }
}

DemoServlet.java

package cn.hncu.demo;
import java.io.PrintWriter;
import java.util.Date;
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.utils.BaseServlet;
public class DemoServlet extends BaseServlet {
    DemoServiceImpl service = new DemoServiceImpl();
    @Override
    public void execute(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        List<Student> list = service.queryAllStudents();
        req.getSession().setAttribute("list", list);
        req.getRequestDispatcher("/jsps/demo.jsp").forward(req, resp);
    }
    public void delStudent(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        String studId = req.getParameter("studId");
        Student stud = new Student();
        stud.setsId(studId);
        service.delStudent(stud);
        resp.sendRedirect(getServletContext().getContextPath()+"?time="+(new Date().getTime()));
    }
    public void addStudent(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        String studId = req.getParameter("studId");
        String studName = req.getParameter("studName");
        String strAge = req.getParameter("age");
        Integer age = Integer.valueOf(strAge);
        String deptId = req.getParameter("deptId");
        Student stud = new Student();
        stud.setsId(studId);
        //System.out.println(studName);//正常汉字
        stud.setsName(studName);
        stud.setsAge(age);
        stud.setDeptId(deptId);
        service.addStudent(stud);
        resp.sendRedirect(getServletContext().getContextPath());
    }
    public void queryStudents(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        String studId = req.getParameter("studId");
        String studName = req.getParameter("studName");
        String deptId = req.getParameter("deptId");
        Student stud = new Student();
        stud.setsId(studId);
        stud.setsName(studName);
        stud.setDeptId(deptId);
        List<Student> qlist = service.queryStudents(stud);
        req.getSession().setAttribute("qlist", qlist);
        PrintWriter out = resp.getWriter();
        out.print("1"); //坑:不能使用out.println("1")
    }
}

DemoJdbcDao.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 cn.hncu.domain.Student;
import cn.hncu.hib.HibernateSessionFactory;
public class DemoJdbcDao {
    public List<Student> queryAllStudents() {
        Session s = HibernateSessionFactory.getSession();
        Query query = s.createQuery("from Student");
        List<Student> list = query.list();
        return list;
    }
    public void delStudent(Student stud) {
        Session s = HibernateSessionFactory.getSession();
            try {
                Transaction tran = s.beginTransaction();
                System.out.println("stud:"+stud);
                s.delete(stud);
//              Student stud2 = new Student();
//              stud2.setStudId("S001");
//              s.save(stud2);
                tran.commit();
            } catch (HibernateException e) {
                //tran.rollback();//可以不写,内部会进行回滚
                System.out.println("抓到异常...");
            }
    }
    public void addStudent(Student stud) {
        Session s = HibernateSessionFactory.getSession();
        Transaction tran = s.beginTransaction();
        try {
            System.out.println(stud.getsName());
            s.saveOrUpdate(stud);
            tran.commit();
        } catch (HibernateException e) {
        }
    }
    public List<Student> queryStudents(Student stud) {
        System.out.println(stud);
        boolean f1=false,f2=false,f3=false;
        Session s = HibernateSessionFactory.getSession();
        String hql = "from Student s where 1=1";
        if(stud.getsId()!=null && stud.getsId().trim().length()>0){
            hql = hql + " and s.sId=:sId";
            f1=true;
        }
        if(stud.getsName()!=null && stud.getsName().trim().length()>0){
            hql = hql + " and s.sName like :sName";
            f2=true;
        }
        if(stud.getDeptId()!=null && stud.getDeptId().trim().length()>0){
            hql = hql + " and s.deptId=:deptId";
            f3=true;
        }
        Query query = s.createQuery(hql);
        if(f1){
            query.setParameter("sId", stud.getsId().trim());
        }
        if(f2){
            query.setParameter("sName", "%"+stud.getsName().trim()+"%");
        }
        if(f3){
            query.setParameter("deptId", stud.getDeptId().trim());
        }
        return query.list();
    }
}
目录
相关文章
|
11天前
|
中间件 Go API
【Go 语言专栏】Go 语言中的 Web 框架比较与选择
【4月更文挑战第30天】本文对比了Go语言中的四个常见Web框架:功能全面的Beego、轻量级高性能的Gin、简洁高效的Echo,以及各自的性能、功能特性、社区支持。选择框架时需考虑项目需求、性能要求、团队经验和社区生态。开发者应根据具体情况进行权衡,以找到最适合的框架。
|
12天前
|
机器学习/深度学习 前端开发 数据可视化
数据分析web可视化神器---streamlit框架,无需懂前端也能搭建出精美的web网站页面
数据分析web可视化神器---streamlit框架,无需懂前端也能搭建出精美的web网站页面
|
12天前
|
开发框架 前端开发 JavaScript
学会Web UI框架--Bootstrap,快速搭建出漂亮的前端界面
学会Web UI框架--Bootstrap,快速搭建出漂亮的前端界面
|
12天前
|
缓存 前端开发 安全
Python web框架fastapi中间件的使用,CORS跨域详解
Python web框架fastapi中间件的使用,CORS跨域详解
|
12天前
|
API 数据库 Python
Python web框架fastapi数据库操作ORM(二)增删改查逻辑实现方法
Python web框架fastapi数据库操作ORM(二)增删改查逻辑实现方法
|
12天前
|
关系型数据库 MySQL API
Python web框架fastapi数据库操作ORM(一)
Python web框架fastapi数据库操作ORM(一)
|
12天前
|
Python
python web框架fastapi模板渲染--Jinja2使用技巧总结
python web框架fastapi模板渲染--Jinja2使用技巧总结
|
12天前
|
开发框架 网络协议 前端开发
Python高性能web框架--Fastapi快速入门
Python高性能web框架--Fastapi快速入门
|
12天前
|
网络协议 数据库 开发者
构建高效Python Web应用:异步编程与Tornado框架
【4月更文挑战第29天】在Web开发领域,响应时间和并发处理能力是衡量应用性能的关键指标。Python作为一种广泛使用的编程语言,其异步编程特性为创建高性能Web服务提供了可能。本文将深入探讨Python中的异步编程概念,并介绍Tornado框架如何利用这一机制来提升Web应用的性能。通过实例分析,我们将了解如何在实际应用中实现高效的请求处理和I/O操作,以及如何优化数据库查询,以支持更高的并发用户数和更快的响应时间。
|
12天前
|
JSON 前端开发 网络架构
Django的web框架Django Rest_Framework精讲(四)
Django的web框架Django Rest_Framework精讲(四)