vivo vivo配件查询收纳包 赠品怎么样,好不好 购买心得

您还可以使用以下方式登录
当前位置:&>&&>&&>& > 【框架】[Hibernate]利用Hibernate进行单表的增删改查-Web实例
ssh框架增删改查实例 【框架】[Hibernate]利用Hibernate进行单表的增删改查-Web实例
前面两篇博客已经将Hibernate的基础知识讲解得差不多了,差不多到写实例的时候了。本篇只用hibernate进行单表的增删改查、应用Hibernate,对students表进行增删改查。service层和DAO层,我都是直接写实现类了(因为这里主要是演示一下Hibernate的使用),如果是开发项目,注意一定要写接口!准备数据库:首先准备一个students表:create database hib charset=utf8;create table students(
sId varchar(8) primary key,
sName varchar(40),
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目录下都有。链接:/chenhaoxiang/Java/blob/master/Hibernate/myHibWeb/myHibWeb.zip部分核心源码:Student.java:package cn.hncu.public class Student {
private String sId;
private String sN
private Integer sA
private String deptId;
public String getDeptId() {
return deptId;
public void setDeptId(String deptId) {
this.deptId = deptId;
public Student() {
public String getsId() {
return sId;
public void setsId(String sId) {
this.sId = sId;
public String getsName() {
public void setsName(String sName) {
this.sName = sN
public Integer getsAge() {
public void setsAge(Integer sAge) {
this.sAge = sA
public String toString() {
return &Student [sId=& + sId + &, sName=& + sName + &, sAge=& + sAge
+ &, deptId=& + deptId + &]&;
}}hibernate.cfg.xml
com.mysql.jdbc.Driver
jdbc:mysql://127.0.0.1:3306/hib
org.hibernate.dialect.MySQLDialect
Student.hbm.xml
BaseServlet.javapackage cn.hncu.import java.io.IOEimport java.lang.reflect.InvocationTargetEimport java.lang.reflect.Mimport javax.servlet.ServletEimport javax.servlet.http.HttpSimport javax.servlet.http.HttpServletRimport javax.servlet.http.HttpServletRpublic abstract class BaseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding(&utf-8&);
resp.setCharacterEncoding(&utf-8&);
resp.setContentType(&text/charset=utf-8&);
String cmd = req.getParameter(&cmd&);
if (null == cmd || cmd.trim().equals(&&)) {
cmd = &execute&;
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 E}HibernateSessionFactory.javapackage cn.hncu.import org.hibernate.HibernateEimport org.hibernate.Simport org.hibernate.SessionFimport org.hibernate.cfg.Cpublic class HibernateSessionFactory {
private static String configFile = &/hibernate.cfg.xml&;
private static Configuration config = new Configuration();
private static SessionFactory sessionFactory =
private static final ThreadLocal t = new ThreadLocal();
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() :
t.set(session);
private static void rebuildSessionFactory() {
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.javapackage cn.hncu.import java.io.PrintWimport java.util.Dimport java.util.Limport javax.servlet.http.HttpServletRimport javax.servlet.http.HttpServletRimport cn.hncu.demo.service.DemoServiceIimport cn.hncu.domain.Simport cn.hncu.utils.BaseSpublic class DemoServlet extends BaseServlet {
DemoServiceImpl service = new DemoServiceImpl();
public void execute(HttpServletRequest req, HttpServletResponse resp)
throws Exception {
List 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 qlist = service.queryStudents(stud);
req.getSession().setAttribute(&qlist&, qlist);
PrintWriter out = resp.getWriter();
out.print(&1&); //坑:不能使用out.println(&1&)
}}DemoJdbcDao.javapackage cn.hncu.demo.import java.util.Limport org.hibernate.HibernateEimport org.hibernate.Qimport org.hibernate.Simport org.hibernate.Timport cn.hncu.domain.Simport cn.hncu.hib.HibernateSessionFpublic class DemoJdbcDao {
public List queryAllStudents() {
Session s = HibernateSessionFactory.getSession();
Query query = s.createQuery(&from Student&);
List list = query.list();
public void delStudent(Student stud) {
Session s = HibernateSessionFactory.getSession();
Transaction tran = s.beginTransaction();
System.out.println(&stud:&+stud);
s.delete(stud);//
Student stud2 = new Student();//
stud2.setStudId(&S001&);//
s.save(stud2);
} catch (HibernateException e) {
//tran.rollback();//可以不写,内部会进行回滚
System.out.println(&抓到异常...&);
public void addStudent(Student stud) {
Session s = HibernateSessionFactory.getSession();
Transaction tran = s.beginTransaction();
System.out.println(stud.getsName());
s.saveOrUpdate(stud);
} catch (HibernateException e) {
public List queryStudents(Student stud) {
System.out.println(stud);
boolean f1=false,f2=false,f3=
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&;
if(stud.getsName()!=null && stud.getsName().trim().length()&0){
hql = hql + & and s.sName like :sName&;
if(stud.getDeptId()!=null && stud.getDeptId().trim().length()&0){
hql = hql + & and s.deptId=:deptId&;
Query query = s.createQuery(hql);
query.setParameter(&sId&, stud.getsId().trim());
query.setParameter(&sName&, &%&+stud.getsName().trim()+&%&);
query.setParameter(&deptId&, stud.getDeptId().trim());
return query.list();
}}ajax.jsString.prototype.trim=function(){
var p = /^\s*/;
//\s 匹配任何空白字符,包括空格、制表符、换页符等等
var str = this.replace(p, &&);
str = str.replace(p, &&);};function Ajax(){
//1 创建一个ajax对象
if(window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp = new ActiveXObject(&Microsoft.XMLHTTP&);
//url为请求的链接或文件。
//succ是status返回为200后运行的函数。
//failure是status返回不为200后运行的函数。
this.get=function(url,succ,failure){
//2 设置通讯方式和地址
xmlhttp.open(&GET&, url, true);//异步--多线程
//3 设置访问成功后的 js对象(回调函数)
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){//服务器的响应消息接收完毕
if(xmlhttp.status==200){//服务器正常响应
var txt = xmlhttp.responseT//后台的响应信息
succ(txt);
if(failure){
failure(xmlhttp.status);
//4发送---Get方式,没有参数(请求体) ---数据在请求地址中
xmlhttp.send();
this.post= function(url,data,succ, failure){
//2 设置通讯方式和地址
xmlhttp.open(&POST&,url,true);//异步--多线程
//3 设置访问成功后的 js对象(回调函数)
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){//服务器的响应消息接收完毕
if(xmlhttp.status==200){//服务器正常响应
var txt = xmlhttp.responseT//后台的响应信息
succ(txt);
if(failure){
failure(xmlhttp.status);
//4设置请求头
xmlhttp.setRequestHeader(&Content-Type&, &application/x-www-form-urlencoded&);
//5发送---Post方式,有参数(请求体) &---数据 ※
xmlhttp.send(data);
};}demo.jsp&%@ page language=&java& import=&java.util.*& pageEncoding=&UTF-8&%&&%@taglib uri=&/jsp/jstl/core& prefix=&c&%&&script type="text/javascript" src="&/script&&script type="text/javascript"&
var path = "";&/script&&script type="text/javascript"&
var d = new Date();
function query() {
var studId = document.getElementsByName("studId")[1].
studId = studId.trim();
var studName = document.getElementsByName("studName")[1].
studName = studName.trim();
var deptId = document.getElementsByName("deptId")[1].
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") {
//这个返回来输出的页面的是子页面!
window.parent.window.location.href = path + "?time="
+ d.getTime();
}&/script& 学号姓名年龄学院编号操作${stud.sId}${stud.sName}${stud.sAge}${stud.deptId}删除添加一个学生信息学生查询学号姓名学院编号查询结果 学号姓名年龄学院编号操作${stud.sId}${stud.sName}${stud.sAge}${stud.deptId}删除演示结果:显示所有:添加学生:查询学生:完整项目链接:/chenhaoxiang/Java/blob/master/Hibernate/myHibWeb/myHibWeb.zip就爱阅读网友整理上传,为您提供最全的知识大全,期待您的分享,转载请注明出处。
欢迎转载:
推荐:    &&&&J2EE企业级开发(Struts2+Spring+Hibernate整合技术计算机科学与...
邀请好友参加吧
版 次:1页 数:183字 数:印刷时间:日开 本:16开纸 张:胶版纸印 次:1包 装:平装是否套装:否国际标准书号ISBN:0所属分类:&&&
下载免费当当读书APP
品味海量优质电子书,尊享优雅的阅读体验,只差手机下载一个当当读书APP
本商品暂无详情。
当当价:为商品的销售价,具体的成交价可能因会员使用优惠券、积分等发生变化,最终以订单结算页价格为准。
划线价:划线价格可能是图书封底定价、商品吊牌价、品牌专柜价或由品牌供应商提供的正品零售价(如厂商指导价、建议零售价等)或该商品曾经展示过的销售价等,由于地区、时间的差异化和市场行情波动,商品吊牌价、品牌专柜价等可能会与您购物时展示的不一致,该价格仅供您参考。
折扣:折扣指在划线价(图书定价、商品吊牌价、品牌专柜价、厂商指导价等)某一价格基础上计算出的优惠比例或优惠金额。如有疑问,您可在购买前联系客服咨询。
异常问题:如您发现活动商品销售价或促销信息有异常,请立即联系我们补正,以便您能顺利购物。
当当购物客户端手机端1元秒
当当读书客户端万本电子书免费读一、Hibernate框架简介
Hibernate是一个优秀的Java持久化层解决方案,是当今主流的对象-关系映射(ORM,ObjectRelationalMapping)工具
1.1、理解持久化
瞬时状态:在程序运行的时候,有些程序数据是保存在内存中,当程序退出后,这些数据就不复存在了,所以称这些数据的状态为瞬时状态
持久状态:在使用一此软件的时候,有些数据,在程序退出后,还以文件等形式保存在硬盘或者数据库中,称这些数据的状态是持久状态
持久化:持久化就是将程序中的数据在瞬时状态和持久状态之间转换的机制。(如:JDBC)
1.2、对象-关系映射(ORM)
Java是一种面象对象的设计语言。在程序运行时的数据是以对象形式存在内存中,而保存数据时,又要以对象的形式存在关系型数据库中。
ORM简单讲:就是能在对象和关系型数据库两者之间进行数据转换的机制。Hibernate就是这样一个中间的解决方案。关系如下图
1.3、ORM框架综述
ORM:对象关系映射(Object Relation Mapping)
Hibernate框架:能够实现ORM框架
Hibernate是一个优秀的Java持久化层解决方案,是当今主流的对象-关系映射(ORM,ObjectRelationalMap
Hibernate框架对JDBC时行和封装,简化了数据访问层。可应用在任何使用JDBC的场合如:Servlet、JSP的WEB应用,JAVA客户端等。
&二、Hibernate下载
官网:http://sourceforge.net/projects/hibernate/files/hibernate3/
这里下载的是3.3.2GA,
解压后,将根目录下的hibernate3.jar和将lib目录下全部的jar导入项目中
同时将数据库驱动也导入这里使用Oracle 11g
其中加入了一些其它的jar包如:JSTL包
当然也可以用MyEclipse完全集成,不用下载
三、Hibernate配置
&3.1、创建hibernate.cfg.xml文件.
这是配置文件默认名.一般放在src目录下:作用指定数据库连接的信息及映射文件路径
获取配置文件进行修改。当然如果记得了就全写也可以。在下载的Hibernate解压目录下就有配置文件模板
hibernate-distribution-3.3.2.GA-dist\hibernate-distribution-3.3.2.GA\project\tutorials\web\src\main\resources此目录下就有,将其复制到src目录下进行修改
&?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&
&!-- Database connection settings --&
&!-- 数据库驱动 不同的数据库不一样--&
&property name="connection.driver_class"&oracle.jdbc.driver.OracleDriver&/property&
&!-- 数据库访问url 不同的数据库不一样--&
&property name="connection.url"&jdbc:oracle:thin:@localhost:1521:orcl&/property&
&!-- 数据库连接用户名 --&
&property name="connection.username"&sa&/property&
&!--数据库连接用户名的密码
&property name="connection.password"&&/property&
&!-- JDBC connection pool (use the built-in) --&
&!--数据库连接池默认连接数量
&property name="connection.pool_size"&2&/property&
&!-- SQL dialect --&
&!--方言,不同的数据不同的版都有所不同
&property name="dialect"&org.hibernate.dialect.HSQLDialect&/property&
&!-- Enable Hibernate's current session context --&
&!-- Session设置 --&
&property name="current_session_context_class"&org.hibernate.context.ManagedSessionContext&/property&
&!-- Disable the second-level cache
&!--二级缓存
&property name="cache.provider_class"&org.hibernate.cache.NoCacheProvider&/property&
&!-- Echo all executed SQL to stdout --&
&!-- 在执行数据操作时,是不是在控制台显示SQL语句,true为显示 --&
&property name="show_sql"&true&/property&
&!-- Drop and re-create the database schema on startup --&
&!--根据数据库表得到类,根据类到表
&property name="hbm2ddl.auto"&create&/property&
&!--对类的配置文件映射
&mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/&
&mapping resource="org/hibernate/tutorial/domain/Person.hbm.xml"/&
&/session-factory&
&/hibernate-configuration&
这里暂时只做数据库的连接配置Oracle的
&?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&
&!-- Database connection settings --&
&!-- 数据库驱动 不同的数据库不一样--&
&property name="connection.driver_class"&oracle.jdbc.driver.OracleDriver&/property&
&!-- 数据库访问url 不同的数据库不一样--&
&property name="connection.url"&jdbc:oracle:thin:@localhost:1521:orcl&/property&
&!-- 数据库连接用户名 --&
&property name="connection.username"&accp&/property&
&!--数据库连接用户名的密码
&property name="connection.password"&accp&/property&
&/session-factory&
&/hibernate-configuration&
3.2、创建持久化类和映射文件
也就是创建实体类的配置文件如:Login.hbm.xml(Login为类名),并在hibernate.cfg.xml文件下方&/session-factory&前面中添加映射文件路径
1、在数据库中创建一张表
create table login
varchar2(20)
primary key,
varchar2(20)
2、创建Login实体类
package com.pb.
* 登录实体类
public class Login {
public String getUsername() {
public void setUsername(String username) {
this.username =
public String getPassword() {
public void setPassword(String password) {
this.password =
3、在实体类的同一个包下创建实体类的配置文件
&?xml version='1.0' encoding='utf-8'?&
&!-- 这里与hibernate.cfg.xml配置文件不一样注意 --&
&!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"& &!-- 这里与hibernate.cfg.xml配置文件不一样注意 --&
&hibernate-mapping&
&!--类名和数据库中的表名相对应 哪个用户 --&
&class name="com.pb.entity.Login" table="LOGIN" schema="accp"&
&!-- id代表主键
column列表 type代表数据类型--&
&!-- 类中的属性 --&
&id name="username" type="java.lang.String"&
&!-- 表中哪一个字段或者是列名 --&
&column name="USERNAME" length="20" /&
&!--生成的方式
assigned代表由外部外部程序负责生成,在 save() 之前必须指定一个--&
native由hibernate根据使用的数据库自行判断采用identity、hilo、sequence其中一种作为主键生成方式,灵活性很强。如果能支持identity则使用identity,如果支持sequence则使用sequence。--&
&generator class="assigned" /&
&!-- 密码段设置 --&
&!--类中的名字和数据类型
&property name="password" type="java.lang.String"&
&!-- 表中的字段名,长度可心不要,是不为空true为不能为空,false是可以为空 --&
&column name="PASSWORD" length="20" not-null="true"/&
&/property&
&!--如果还有其它的属性,设置方式与password一样设置
&/hibernate-mapping&
在src下的配置文件中添加映射
&?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&
&!-- Database connection settings --&
&!-- 数据库驱动 不同的数据库不一样--&
&property name="connection.driver_class"&oracle.jdbc.driver.OracleDriver&/property&
&!-- 数据库访问url 不同的数据库不一样--&
&property name="connection.url"&jdbc:oracle:thin:@localhost:1521:orcl&/property&
&!-- 数据库连接用户名 --&
&property name="connection.username"&accp&/property&
&!--数据库连接用户名的密码
&property name="connection.password"&accp&/property&
&!--为实体类配置文件添加映射
&mapping resource="com/pb/entity/Login.hbm.xml"/&
&/session-factory&
&/hibernate-configuration&
3.3、创建Hibernate连接工具类
Hibernater主要接口和类:
Configuration
SessionFactory:DriverManager
Session:Connection
Transaction
Query:Statement和PreparedStatement
在下载的包中有提供好的一个比较简单的工具类
package com.pb.
import org.hibernate.SessionF
import org.hibernate.cfg.C
public class HibernateUtil {
private static final SessionFactory sessionF
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
public static SessionFactory getSessionFactory() {
return sessionF
这个比较,也可以增加一功能
相比较MyEclipse提供的一个比较完美
package com.pb.
import org.hibernate.HibernateE
import org.hibernate.S
import org.hibernate.cfg.C
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution.
Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
public class HibernateSessionFactory {
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal&Session& threadLocal = new ThreadLocal&Session&();
static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionF
private static String configFile = CONFIG_FILE_LOCATION;
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
private HibernateSessionFactory() {
* Returns the ThreadLocal Session instance.
Lazy initialize
* the &code&SessionFactory&/code& if needed.
@return Session
@throws HibernateException
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
session = (sessionFactory != null) ? sessionFactory.openSession()
threadLocal.set(session);
Rebuild hibernate session factory
public static void rebuildSessionFactory() {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
Close the single hibernate session instance.
@throws HibernateException
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
return session factory
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionF
return session factory
session factory will be rebuilded in the next call
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configF
sessionFactory = null;
return hibernate configuration
public static Configuration getConfiguration() {
根据需要选择
四、Hibernate的持久化操作的步骤
4.1、读取并散板配置文件
Configuration config=new Configuration().configure();
4.2、读取并解析映射信息,创建SessionFactory
SessionFactory factory=config.buildSessionFactory();
4.3、打开session
Session session=factory.openSessin();
4.4、开始一个事务(增、删、改操作必须,查询操作可选)
Transaction tran=session.beginTransaction();
4.5、操作化操作
session.save(对象);
session.update(对象);
session.delete(对象);
session.get(主键之类的);
4.6、提交事务
4.7、关闭session
session.close();
五、Hibernate使用
&实现增、删、改、查的类
package com.pb.LoginD
import java.util.L
import org.hibernate.HibernateE
import org.hibernate.Q
import org.hibernate.S
import org.hibernate.T
import com.pb.entity.L
import com.pb.until.HibernateSessionF
import com.pb.until.HibernateU
public class LoginDao {
public void save(Login login) {
// 得到Session
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tran = null;
// Session session=new
// Configuration().configure().buildSessionFactory().openSession();
// 打开事务
tran = session.beginTransaction();
// 执行数据添加
session.save(login);
// 提交事务
System.out.println("用户信息添加成功");
} catch (HibernateException e) {
// 事务回滚
tran.rollback();
e.printStackTrace();
System.out.println("用户信息添加失败");
} finally {
// 关闭session
session.close();
* 修改根据用户名
public void update(Login login) {
// 得到Session
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tran = null;
// Session session=new
// Configuration().configure().buildSessionFactory().openSession();
// 打开事务
tran = session.beginTransaction();
// 执行数据添加
session.update(login);
// 提交事务
System.out.println("用户信息修改成功");
} catch (HibernateException e) {
// 事务回滚
tran.rollback();
e.printStackTrace();
System.out.println("用户信息修改失败");
} finally {
// 关闭session
session.close();
* 修改根据用户名修改密码
public void delte(Login login) {
// 得到Session
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tran = null;
// Session session=new
// Configuration().configure().buildSessionFactory().openSession();
// 打开事务
tran = session.beginTransaction();
// 执行数据添加
session.delete(login);
// 提交事务
System.out.println("用户信息删除成功");
} catch (HibernateException e) {
// 事务回滚
tran.rollback();
e.printStackTrace();
System.out.println("用户信息删除失败");
} finally {
// 关闭session
session.close();
* 查询一查询全部用户
public List&Login& QueryALL() {
// 使用myeclipse提供的工具类来得到session
Session session = HibernateSessionFactory.getSession();
// 建立查询
Query query = session.createQuery("from Login");
// 查询重到List集合
List&Login& list = query.list();
// 关闭session
session.close();
// 返回结果集合
* 查询二 查询指定的用户名的
public Login QueryByName(String username) {
// 使用myeclipse提供的工具类来得到session
Session session = HibernateSessionFactory.getSession();
// 建立查询
Query query = session.createQuery("from Login l where l.username=?");
query.setString(0, username);
// 查询返回唯一
Login login = (Login) query.uniqueResult();
// 关闭session
session.close();
// 返回结果集合
* 查询三,模糊查询
public List&Login& QueryLikeName(String username) {
// 使用myeclipse提供的工具类来得到session
Session session = HibernateSessionFactory.getSession();
// 建立查询
Query query = session
.createQuery("from Login l where l.username like ?");
query.setString(0, "%" + username + "%");
// 查询重到List集合
List&Login& list = query.list();
// 关闭session
session.close();
// 返回结果集合
package com.pb.
import java.util.L
import com.pb.LoginDao.LoginD
import com.pb.entity.L
public class Test {
public static void main(String[] args) {
//声明LoginDao对象
LoginDao loginDao=new LoginDao();
//声明对象并赋初始值
Login login=new Login();
login.setUsername("Jack");
login.setPassword("blue");
//执行添加
loginDao.save(login);
//执行修改
login.setUsername("Jack");
login.setPassword("while");
loginDao.update(login);
//执行删除
loginDao.delte(login);
System.out.println("=========查询全部========");
//查询全部
List&Login& list=loginDao.QueryALL();
for (Login log : list) {
System.out.println("用户名:"+log.getUsername()+"
密码:"+log.getPassword());
System.out.println("=========精确查询========");
//查询一个用户
Login lg=loginDao.QueryByName("ffff");
if(lg!=null){
System.out.println("用户名:"+lg.getUsername()+"
密码:"+lg.getPassword());
System.out.println("没有此用户");
System.out.println("=========模糊查询========");
//模糊查询
List&Login& likelist=loginDao.QueryLikeName("t");
for (Login lo : likelist) {
System.out.println("用户名:"+ lo.getUsername()+"
密码:"+ lo.getPassword());
以上就介绍了Hibernate框架简介(二)基本使用增、删、改、查,包括了方面的内容,希望对Java教程有兴趣的朋友有所帮助。
本文网址链接:/article/detail_117522.html
上一篇: 下一篇:

我要回帖

更多关于 vivo配件xshare 的文章

 

随机推荐