实现Hibernate框架的CRUD
1.创建Web项目HS_test如图所示:
2.创建数据库DBHSTest,在数据库中创建表Teacher,并插入数据
3.在Myeclipse中调出DB Brower视图
右键->New:
连接后如图所示:
4.导入Hibernate
右击项目->myeclipse->Add Hibernate Capabilities:
选择Hibernate3.3 点击Next:
默认设置,在src文件夹下创建hibernate.cfg.xml文件,点击Next:
选择之前新建的DB Driver:DBHSTest,配置自动显示出来,点击Next:
将 HibernateSessionFactory类建立在com.miaomiao.hs.test包下,点击Finish,完成导入。
查看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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration> <session-factory>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="connection.url">jdbc:sqlserver://127.0.0.1:1433;databaseName=dbHSTest</property>
<property name="connection.username">sa</property>
<property name="connection.password">123</property>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="myeclipse.connection.profile">dbHSTest</property> </session-factory> </hibernate-configuration>
5.创建ORM映射 反向工程
(1)选择DB Brower 下的dbHSTest ->...->dbo->table->Teacher,右键,选择Hibernate ReverseEngineering:
如图选择,点击Next,全部默认设置
创建完成后,生成如图Java文件和xml文件:
Teacher.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">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.miaoshi.hs.orm.Teacher" table="Teacher" schema="dbo" catalog="dbHSTest">
<id name="id" type="java.lang.String">
<column name="ID" length="10" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="Name" length="20" not-null="true" />
</property>
</class>
</hibernate-mapping>
Teacher.java文件内容:
package com.miaoshi.hs.orm; /**
* Teacher entity. @author MyEclipse Persistence Tools
*/ public class Teacher implements java.io.Serializable { // Fields private String id;
private String name; // Constructors /** default constructor */
public Teacher() {
} /** full constructor */
public Teacher(String id, String name) {
this.id = id;
this.name = name;
} // Property accessors public String getId() {
return this.id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
} }
6.实现对数据库的增删改查
(1)显示教师信息
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.miaoshi.hs.orm.Teacher"%>
<%@page import="com.miaoshi.hs.HibernateSessionFactory"%>
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.Query"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'TeacherList.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<%
Session ss = HibernateSessionFactory.getSession();
ss.beginTransaction(); Query query = ss.createQuery("from Teacher");
List<Teacher> teachers = query.list(); ss.getTransaction().commit();
ss.close(); %>
<center>
教师列表<br><br>
<a href="TeacherAdd.html">添加</a>
<table border="1" cellspacing="0" cellpadding="4">
<tr>
<th>工号</th>
<th>姓名</th>
<th>操作</th>
</tr>
<% for(int i = 0;i<teachers.size();i++){ %>
<tr>
<td><%=teachers.get(i).getId() %></td>
<td><%=teachers.get(i).getName() %></td>
<td><a href="StudentEdit.jsp?ID=<%=teachers.get(i).getId()%>">编辑</a>
<a href="servlet/StudentDelete.do?ID=<%=teachers.get(i).getId()%>">删除</a></td>
</tr>
<%} %>
</table>
</center>
</body>
</html>
(2)增加教师信息
TeacherAdd.html
<!DOCTYPE html>
<html>
<head>
<title>TeacherAdd.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body>
<form id="form1" name="form1" method="post"
action="/servlet/TeacherAdd">
<center>
添加教师信息<br> <br> 工号<input type="text" id="ID" name="ID"><br>
<br> 姓名<input type="text" id="Name" name="Name"><br>
<br> <input type="submit" value="确定">
</center>
</form>
</body>
</html>
创建TeacherAdd的Servlet
package com.miaoshi.hs; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import com.miaoshi.hs.HibernateSessionFactory;
import com.miaoshi.hs.orm.Teacher; public class TeacherAdd extends HttpServlet { /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("UTF-8");
String strID = "";
String strName = ""; strID = request.getParameter("ID");
strName = request.getParameter("Name");
Session session = HibernateSessionFactory.getSession();
try{ session.beginTransaction(); Teacher student = new Teacher();
student.setId(strID);
student.setName(strName);
session.save(student); session.getTransaction().commit();
session.close(); response.sendRedirect("../TeacherList.jsp"); }
catch(Exception e){
session.clear();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>Add fail</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" add fail! ");
out.println(" <a href='../TeacherList.jsp'>return</a>");
out.println(e.getMessage());
//out.print(this.getClass());
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
} }
未完待续。。。
实现Hibernate框架的CRUD的更多相关文章
- 为什么要用Hibernate框架? 把SessionFactory,Session,Transcational封装成包含crud的工具类并且处理了事务,那不是用不着spring了?
既然用Hibernate框架访问管理持久层,那为何又提到用Spring来管理以及整合Hibernate呢?把SessionFactory,Session,Transcational封装成包含crud的 ...
- Hibernate框架—简介
ORM对象/关系数据库映射 ORM全称Object/Relation Mapping,对象/关系数据库映射,可以理解成一种规范.该框架的基本特征:完成面向对象的编程语言到关系数据库之间的映射. ORM ...
- Hibernate框架--配置,映射,主键
SSH框架: Struts框架, 基于mvc模式的应用层框架技术! Hibernate, 基于持久层的框架(数据访问层使用)! Spring, 创建对象处理对象的依赖关系以及框架整合! Da ...
- Hibernate框架笔记01_环境搭建_API_CRUD
目录 1. Hibernate框架的概述 1.1 什么是框架 1.2 经典三层架构 1.3 Hibernate框架 2 Hibernate入门 2.1 下载Hibernate的开发包 2.2 创建项目 ...
- JPA、Hibernate框架、通用mapper
JPA是描述对象-关系表的映射关系,将运行期实体对象持久化到数据库中,提出以面向对象方式操作数据库的思想. Hibernate框架核心思想是ORM-实现自动的关系映射.缺点:由于关联操作提出Hql语法 ...
- JPA、Hibernate框架、通用mapper之间的关系及通用mapper的具体实现
JPA是描述对象-关系表的映射关系,将运行期实体对象持久化到数据库中,提出以面向对象方式操作数据库的思想. Hibernate框架核心思想是ORM-实现自动的关系映射.缺点:由于关联操作提出Hql语法 ...
- Hibernate框架第一天
**框架和CRM项目的整体介绍** 1. 什么是CRM * CRM(Customer Relationship Management)客户关系管理,是利用相应的信息技术以及互联网技术来协调企业与顾客间 ...
- Hibernate框架学习笔记
Hibernate 是一个 JDO( Java Data Objects)工具.它的工作原理是通过文件把值对象(Java对象)和 数据库表之间建立起一个映射关系,还提供数据查询和获取数据的方法. ...
- Hibernate框架基础
Hibernate框架基础 Hibernate框架 ORM概念 O, Object 对象 R, Realtion 关系 (关系型数据库: MySQL, Oracle…) M,Mapping 映射 OR ...
随机推荐
- java 使用jsoup处理html字符
依赖的jar <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artif ...
- Etcd源码解析(转)
7 Etcd服务端实现 7.1 Etcd启动 Etcd有多种启动方式,我们从最简单的方式入手,也就是从embed的etcd.go开始启动,最后会启动EtcdServer. 先看看etcd.go中的启动 ...
- C++复习:类和对象
类和对象 基本概念 1)类.对象.成员变量.成员函数 2)面向对象三大概念 封装.继承.多态 3)编程实践 类的定义和对象的定义,对象的使用 求圆形的面积 定义Teacher类 ...
- Linux命令:sshpass
sshpass介绍 sshpass是一款凡是为凡是使用ssl方式访问的操作提供一个免输入密码的非交互式操作,以便于在脚本中执行ssl操作,如ssh,scp等.sshpass是一家以色列公司Lingnu ...
- 一种去中心化的manager设计思路
通常,我们设计游戏引擎时,或者管理器时,都会由管理器产出各种产品,一旦有新产品要加,就要修改管理器,来增加相应的生成代码. 这从设计上来看有两个问题: 1,管理器参数需要有个类型,在管理器中用if e ...
- debian下redis2.8.17安装过程
下载redis源码包,我下载的是redis2.8.17 解压缩该源码包 tar zxf redis-2.8.17.tar.gz 进入解压缩后的目录 cd redis-2.8.17/ 添加redis用户 ...
- delphi通过TADOConnection组件直接连接MSSQL数据库并读写数据。
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System ...
- 学JS的心路历程-JS支持面向对象?(二)
昨天讲了面向对象的继承,今天我们来谈谈多态和封装吧! 多态polymorphism 抽象讲法解释,就是使用单一界面操作多种型态的物件 继承父类别,定义与父类别中相同的方法,但实作内容不同,称为复写(o ...
- python使用cv2显示图片像素值
给定一张灰度图,显示这张图片的像素值 def show_image_pixel(img): ''' :param img: 需要输出像素值的图像,要求是灰度图 :return: 无返回值 ''' he ...
- MAC下Xcode配置opencv(2017.3.29最新实践,亲测可行)(转)
本文原创,未经同意,谢绝转载!(转载请告知本人并且经过本人同意--By Pacific-hong) 本人小硕一枚,因为专业方向图像相关,所以用到opencv,然后网上MAC下Xcode配置opencv ...