hibernate框架实例演示(增删改查):
2016-10-02 17:05
316 查看
一:hibernate框架后台:
1、导入hibernate框架常用包2、在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/hib2 </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>3、在hib包中编写会话工厂类(
HibernateSessionFactory),通过工厂产生一个session对象,session是hibernate的核心,能对数据库进行操作
package cn.hncu.hib;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
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();
}
}
}
4、在domain包中编写pojo类(student,java)以及映射文件(Student.hnb)
pojo类:
package cn.ccc.domain; public class Student { private String studId; private String studName; private Integer age; 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; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getDeptId() { return deptId; } public void setDeptId(String deptId) { this.deptId = deptId; } }
映射文件:
<?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="students" catalog="hib2"> <id name="studId" type="java.lang.String"> <column name="id" length="8"></column> </id> <property name="studName" type="java.lang.String"> <column name="name" length="40" /> </property> <property name="age" type="java.lang.Integer"> <column name="age" /> </property> <property name="deptId" type="java.lang.String"> <column name="deptId" length="8" /> </property> </class> </hibernate-mapping>
5、编写测试文件
(1)、先在工具包中写一个工具类(baseServlet)用于(demoServlet)来继承:
baseServlet代码如下:
package cn.ccc.utils; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.servlet.Servl e6eb etException; 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"); 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; }
2、在demo包中分为dao层service层servlet层
(1)、在dao层写好增删改查等功能
package cn.ccc.demo.dao; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Transaction; import org.hibernate.classic.Session; 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(); Transaction tran = s.beginTransaction(); try { 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 { s.saveOrUpdate(stud); tran.commit(); } catch (HibernateException e) { } } public List<Student> queryStudents(Student stud) { boolean f1=false,f2=false,f3=false; Session s = HibernateSessionFactory.getSession(); String hql = "from Student s where 1=1"; if(stud.getStudId()!=null && stud.getStudId().trim().length()>0){ hql = hql + " and s.studId=:studId"; f1=true; } if(stud.getStudName()!=null && stud.getStudName().trim().length()>0){ hql = hql + " and s.studName like :studName"; 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("studId", stud.getStudId().trim()); } if(f2){ query.setParameter("studName", "%"+stud.getStudName().trim()+"%"); } if(f3){ query.setParameter("deptId", stud.getDeptId().trim()); } return query.list(); } }
2、把dao层注入到service层中
package cn.hncu.demo.service; import java.util.List; import cn.ccc.demo.dao.DemoJdbcDao; import cn.ccc.domain.Student; public class DemoServiceImpl { private DemoJdbcDao dao = new DemoJdbcDao();//注入 public List<Student> queryAllStudents() { return dao.queryAllStudents(); } public void delStudent(Student stud) { dao.delStudent(stud); } public void addStudent(Student stud) { dao.addStudent(stud); } public List<Student> queryStudents(Student stud) { return dao.queryStudents(stud); } }
(3)、把service层注入到servlet层
package cn.ccc.demo; import java.io.PrintWriter; 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.setStudId(studId); service.delStudent(stud); resp.sendRedirect(getServletContext().getContextPath()); } 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.setStudId(studId); stud.setStudName(studName); stud.setAge(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.setStudId(studId); stud.setStudName(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") } }
二:以下是前台页面的编写:
1、index页面:<%@ 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> <title>利用Hibernate进行表的增删改查</title> </head> <body> <jsp:forward page="/DemoServlet"></jsp:forward> </body> </html>2、demo页面:
<%@ 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> <title>利用Hibernate进行单表的增删改查</title> <style type="text/css"> table{ border: 1px solid gray; border-collapse: collapse; width:60%; } td{ border: 1px solid gray; padding: 5px; } </style> <script type="text/javascript" src="<c:url value='/js/ajax.js'/>"></script> <script type="text/javascript"> var path = "<c:url value='/'/>"; </script> <script type="text/javascript"> function query(){ var studId= document.getElementsByName("studId")[1].value; studId = studId.trim(); var studName= document.getElementsByName("studName")[1].value; studName = studName.trim(); var deptId= document.getElementsByName("deptId")[1].value; deptId = deptId.trim(); //ajax提交 var ajax = new Ajax(); var url = path+"/DemoServlet"; var params = "cmd=queryStudents&studId="+studId+"&studName="+studName+"&deptId="+deptId; ajax.post(url, params, function(data){ if(data=="1"){ //alert(data); window.parent.window.location.href=path; } }); } </script> </head> <body> <table> <tr> <td>学号</td> <td>姓名</td> <td>年龄</td> <td>学院编号</td> <td>操作</td> </tr> <c:forEach items="${list}" var="stud" > <tr> <td>${stud.studId}</td> <td>${stud.studName}</td> <td>${stud.age}</td> <td>${stud.deptId}</td> <td> <a href="<c:url value='/DemoServlet?cmd=delStudent&studId=${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="studId"> </td> </tr> <tr> <td>姓名<font color="red">*</font></td> <td><input type="text" name="studName"> </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" align="center"><input type="submit" value="添加/修改"> </td> </tr> </table> </form> <hr/> <h3>学生查询</h3> <table> <tr> <td>学号</td> <td><input type="text" name="studId"> </td> </tr> <tr> <td>姓名</td> <td><input type="text" name="studName"> </td> </tr> <tr> <td>学院编号</td> <td><input type="text" name="deptId"> </td> </tr> <tr> <td colspan="2" align="center"> <input type="button" onclick="query();" value="查询"> </td> </tr> </table> <c:if test="${!empty sessionScope.qlist }"> <h3>查询结果</h3> <table> <tr> <td>学号</td> <td>姓名</td> <td>年龄</td> <td>学院编号</td> <td>操作</td> </tr> <c:forEach items="${qlist}" var="stud" > <tr> <td>${stud.studId}</td> <td>${stud.studName}</td> <td>${stud.age}</td> <td>${stud.deptId}</td> <td> <a href="<c:url value='/DemoServlet?cmd=delStudent&studId=${stud.studId}'/>" >删除</a> </td> </tr> </c:forEach> </table> </c:if> </body> </html>
3、ajax.js
String.prototype.trim=function(){
var p=/^\s*/;
var str = this.replace(p, "");
p=/\s*$/;
str = str.replace(p, "");
return str;
};
function Ajax(){
this.get= function(url,succ,failure){
//1创建一个ajax对象
var xhr = null;
if(window.XMLHttpRequest){//IE7之后,火狐,google
xhr = new XMLHttpRequest();
}else{//IE6及以下,其它大部分旧版本的浏览器
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
//2 设置通讯方式和地址
xhr.open("GET",url,true);//异步--多线程
//3 设置访问成功后的 js对象(回调函数)
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//服务器的响应消息接收完毕
if(xhr.status==200){//服务器正常响应
var txt = xhr.responseText;//后台的响应信息
succ(txt);
}else{
if(failure){
failure(xhr.status);
}
}
}
};
//4发送---Get方式,没有参数(请求体) ---数据在请求地址中
xhr.send(null);
};
this.post= function(url,data,succ, failure){
//1创建一个ajax对象
var xhr = null;
if(window.XMLHttpRequest){//IE7之后,火狐,google
//alert("XMLHttpRequest...");
xhr = new XMLHttpRequest();
}else{//IE6及以下,其它大部分旧版本的浏览器
//alert("ActiveXObject...");
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
//2 设置通讯方式和地址
xhr.open("POST",url,true);//※异步--多线程
//3 设置访问成功后的 js对象(回调函数)
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//服务器的响应消息接收完毕
if(xhr.status==200){//服务器正常响应
var txt = xhr.responseText;//后台的响应信息
succ(txt);
}else{
if(failure){
failure(xhr.status);
}
}
}
};
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4发送---Post方式,有参数(请求体) <---数据 ※
xhr.send(data);
};
}
相关文章推荐
- 【Hibernate框架开发之七】Hibernate使用Annotation中各种关系映射的CRUD(增删改查)&&集合映射&&继承映射
- Hibernate 框架基本的数据库增删改查操作
- 大师养成计划之二:hibernate框架的使用------实例演示
- struts&amp;hibernate应用(对数据库增删改查)实例
- hibernate通过session实现增删改查操作实例解析
- android使用xfire webservice框架远程对sqlserver操作(包括增删改查)的实例!!已在真机上试验通过
- 19、SSM框架-Mybatis入门概述及第一个Mybatis实例实现增删改查(1)
- MyBatis框架配置及增删改查应用实例
- ssh SSH的整合框架及增删改查操作实例练习
- 【框架】[Hibernate]利用Hibernate进行单表的增删改查-Web实例
- android使用xfire webservice框架远程对sqlserver操作(包括增删改查)的实例!!已在真机上试验通过
- Hibernate框架的增删改查代码详解
- 【Hibernate框架开发之七】Hibernate使用Annotation中各种关系映射的CRUD(增删改查)&&集合映射&&继承映射
- Hibernate执行流程&用Hibernate框架完成增删改查的操作
- Hibernate 基本数据操作(增删改查)
- hibernate基本概念和CURD(增删改查)详解
- Hadoop Herriot测试框架之旅——演示实例
- Hibernate基本概念与CRUD(增删改查)
- Hibernate概念深入和CURD(增删改查)
- 继完成hibernate配置后的增删改查例子