前面两篇博客已经将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');
需要的Jar包
数据库连接包以及hibernate必须包,这些包在项目的WEBROOT/WEBINF的bin目录下都有。
链接:
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(); } }