Hibernate实例二
Hibernate实例二
一、测试openSession方法和getCurrentSession方法
hebernate中可以通过上述两种方法获取session对象以对数据库进行操作,下面的代码以及注解是对两种方法的辨析
这两种方法是从SessionFactory获取Session的时候用
SessionTest.java
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.jdbc.Work;
import org.hibernate.service.ServiceRegistry;
import org.junit.Test; /*
* session详解
* 如何获得session对象
* 1)openSession
* 2)getCurrentSession
* getCurrentSession在事务提交或者回滚之后会自动关闭,而openSession需要你
* 手动关闭。如果使用openSession而没有手动关闭,多次之后会导致连接池溢出
*
* openSession方法每次都是创建新的对象
* getCurrentSession一直使用的是同一个对象,有点类似单例模式
*/ public class SessionTest { @Test
public void testOpenSession(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new
StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();
//创建会话工厂对象
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//创建会话对象
Session session1 = sessionFactory.openSession();
Session session2 = sessionFactory.openSession();
System.out.println(session1==session2);//false
/*
if (session!=null) {
System.out.println("session创建成功");
}
else {
System.out.println("session创建失败");
}
*/
} @Test
public void testGetCurrentSession(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new
StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();
//创建会话工厂对象
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//创建会话对象
Session session1 = sessionFactory.getCurrentSession();
Session session2 = sessionFactory.getCurrentSession();
System.out.println(session1==session2);//true
/*
if (session!=null) {
System.out.println("session创建成功");
}
else {
System.out.println("session创建失败");
}
*/
} @Test
public void testSaveStudentsWithOpenSession(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new
StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();
//创建会话工厂对象
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//创建会话对象
Session session1 = sessionFactory.openSession();
//开启事务
Transaction transaction = session1.beginTransaction();
//生产学生对象
Students s = new Students(1,"饭饭","男",new Date(),"博客园");
session1.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// TODO Auto-generated method stub
System.out.println("connection hashCode:"+connection.hashCode());
}
});
session1.save(s);//保存对象进入数据库
//session1.close();
transaction.commit();//提交事务 //创建会话对象
Session session2 = sessionFactory.openSession();
//开启事务
transaction = session2.beginTransaction();
//生产学生对象
s = new Students(2,"饭饭2","男",new Date(),"博客园2");
session2.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// TODO Auto-generated method stub
System.out.println("connection hashCode:"+connection.hashCode());
}
});
session2.save(s);//保存对象进入数据库
transaction.commit();//提交事务
} @Test
public void testSaveStudentsWithGetCurrentSession(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new
StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();
//创建会话工厂对象
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//创建会话对象
Session session1 = sessionFactory.getCurrentSession();
//开启事务
Transaction transaction = session1.beginTransaction();
//生产学生对象
Students s = new Students(1,"饭饭","男",new Date(),"博客园");
session1.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// TODO Auto-generated method stub
System.out.println("connection hashCode:"+connection.hashCode());
}
});
session1.save(s);//保存对象进入数据库
//session1.close();
transaction.commit();//提交事务 //创建会话对象
Session session2 = sessionFactory.getCurrentSession();
//开启事务
transaction = session2.beginTransaction();
//生产学生对象
s = new Students(2,"饭饭2","男",new Date(),"博客园2");
session2.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// TODO Auto-generated method stub
System.out.println("connection hashCode:"+connection.hashCode());
}
});
session2.save(s);//保存对象进入数据库
159 transaction.commit();//提交事务
}
}
这里有事务提交,事务提交就是将sql传到数据库,要是没有事务,session对象只能自己提交了。
二、如何使用对象类型Blob类型
Blob类型可以用来存照片、音频、视频等文件

Hibernate对象数据类型
1、实体类中定义这样的属性
private Blob picture;//照片,大文本数据类型
当然也要写这个属性对应的get/set方法
2、修改映射文件
<property name="picture" type="java.sql.Blob">
<column name="PICTURE" />
</property>
3、测试Blob类型
//这里报错我一直在纠结,其实视频里面这里也有错啊,我浪费时间
//多去看视频下面的评论,有告诉我们很多问题的解决方案
//运行代码时老犯配置错误,原来配置文件中不支持java注释的写法
//我是通过删减犯错位置的代码来发现错误的 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.util.Date; import javax.print.DocFlavor.INPUT_STREAM; import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; //测试类
public class StudentsTest { private SessionFactory sessionFactory;
private Session session;
private Transaction transaction; @Before
public void init(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new
StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();//这里有点不一样
//创建会话工厂对象
sessionFactory = config.buildSessionFactory(serviceRegistry);
//会话对象
session = sessionFactory.openSession();
//开启事务
transaction = session.beginTransaction(); } @After
public void destory(){
transaction.commit();//提交事务
session.close();//关闭会话
sessionFactory.close();//关闭会话工厂
} @Test
public void testSaveStudents(){
//生产学生对象
// Students s = new Students(1,"饭饭","男",new Date(),"博客园");
Students s = new Students();
s.setSid(1);
s.setSname("饭饭");
s.setGender("男");
s.setBirthday(new Date());
//s.setAddress("博客园");
Address address = new Address("400715","1888****749","重庆北碚西南大学");
s.setAddress(address);
session.save(s);//保存对象进入数据库
} @Test
public void TestWriteBlob() throws Exception {
Students s = new Students(1,"饭饭","男",new Date(),"博客园");
//先获得照片文件
File f = new File("e:"+File.separator+"fanfan.jpg");
//获取照片文件的输入流
InputStream input = new FileInputStream(f);
//创建一个Blob对象
Blob image = (Blob) Hibernate.getLobCreator(session).createBlob(input, input.available());
//设置照片属性
s.setPicture(image);
//保存学生
session.save(s);
} @Test
public void testReadBlob() throws Exception{
Students s = (Students)session.get(Students.class, 1);
//获取Blob对象
Blob image = s.getPicture();
//获取输入流
InputStream input = image.getBinaryStream();
//创建输出流
File f = new File("e:"+File.separator+"dest.jpg");
//获取输出流
OutputStream output = new FileOutputStream(f);
//创建缓冲区
byte[] buff = new byte[input.available()];
input.read(buff);
output.write(buff);
input.close();
output.close(); } }
三、Hibernate使用组件类型
1、写出属性类Address.java,并在实体类Students.java中添加Address属性
//地址类
public class Address { private String postcode;//邮编
private String phone;//电话
private String address;//地址 public Address(){ } public Address(String postcode, String phone, String address) {
//super();
this.postcode = postcode;
this.phone = phone;
this.address = address;
} public String getPostcode() {
return postcode;
} public void setPostcode(String postcode) {
this.postcode = postcode;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} }
下面是在实体类Students.java中添加Address属性
private Address address;//地址类对象
也要生产地址类对象的get与set方法
2、修改映射文件Students.hbm.xml
<!--
<property name="address" type="java.lang.String">
<column name="ADDRESS" />
</property>
-->
被替换为:
<component name="address" class="Address">
<property name="postcode" column="POSTCODE"></property>
<property name="phone" column="PHONE"></property>
<property name="address" column="ADDRESS"></property>
</component>
3、测试组件类型
//这里报错我一直在纠结,其实视频里面这里也有错啊,我浪费时间
//多去看视频下面的评论,有告诉我们很多问题的解决方案
//运行代码时老犯配置错误,原来配置文件中不支持java注释的写法
//我是通过删减犯错位置的代码来发现错误的 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.util.Date; import javax.print.DocFlavor.INPUT_STREAM; import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; //测试类
public class StudentsTest { private SessionFactory sessionFactory;
private Session session;
private Transaction transaction; @Before
public void init(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new
StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();//这里有点不一样
//创建会话工厂对象
sessionFactory = config.buildSessionFactory(serviceRegistry);
//会话对象
session = sessionFactory.openSession();
//开启事务
transaction = session.beginTransaction(); } @After
public void destory(){
transaction.commit();//提交事务
session.close();//关闭会话
sessionFactory.close();//关闭会话工厂
} @Test
public void testSaveStudents(){
//生产学生对象
// Students s = new Students(1,"饭饭","男",new Date(),"博客园");
Students s = new Students();
s.setSid(1);
s.setSname("饭饭");
s.setGender("男");
s.setBirthday(new Date());
//s.setAddress("博客园");
Address address = new Address("400715","1888****749","重庆北碚西南大学");
s.setAddress(address);
session.save(s);//保存对象进入数据库
} }
四、Hibernate的增删改查操作
* save():(增)保存数据 delete():(删)删除数据 update():(改)更新数据 get()/load():(查)取出数据
//这里报错我一直在纠结,其实视频里面这里也有错啊,我浪费时间
//多去看视频下面的评论,有告诉我们很多问题的解决方案
//运行代码时老犯配置错误,原来配置文件中不支持java注释的写法
//我是通过删减犯错位置的代码来发现错误的 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.util.Date; import javax.print.DocFlavor.INPUT_STREAM; import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; //测试类
public class StudentsTest { private SessionFactory sessionFactory;
private Session session;
private Transaction transaction; @Before
public void init(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new
StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();//这里有点不一样
//创建会话工厂对象
sessionFactory = config.buildSessionFactory(serviceRegistry);
//会话对象
session = sessionFactory.openSession();
//开启事务
transaction = session.beginTransaction(); } @After
public void destory(){
transaction.commit();//提交事务
session.close();//关闭会话
sessionFactory.close();//关闭会话工厂
} @Test
public void testSaveStudents(){
//生产学生对象
// Students s = new Students(1,"饭饭","男",new Date(),"博客园");
Students s = new Students();
s.setSid(1);
s.setSname("饭饭");
s.setGender("男");
s.setBirthday(new Date());
//s.setAddress("博客园");
Address address = new Address("400715","1888****749","重庆北碚西南大学");
s.setAddress(address);
session.save(s);//保存对象进入数据库
} /*
* get和load都是查询单个记录
* 1、get方法会向数据库立即发送sql语句,load方法要等到第一次用的时候再发sql语句
* 2、get方法返回的是本身对象,load方法返回的是代理对象,代理对象只保存了实例对象的主键id
* 3、查询对象不存在时,get返回null,load返回ObjectNotFoundException异常
*/ @Test
public void testGetStudents(){//get查询单个记录
Students s = (Students)session.get(Students.class, 1);
System.out.println(s.getClass().getName());//answer: Students
System.out.println(s);
//answer: Students [sid=1, sname=饭饭, gender=男, birthday=2017-05-31 06:03:13.0, address=Address@c8b96ec]
} @Test
public void testLoadStudents(){//load查询单个记录
/*
* 没有后面这个输出s的语句,load方法不向数据库发送sql语句,加上这句话立马就有了
*
*/
Students s = (Students)session.load(Students.class, 1);
System.out.println(s.getClass().getName());//answer: Students_$$_jvstd5_0 显然这个结果是一个代理对象
System.out.println(s);
//answer: Students [sid=1, sname=饭饭, gender=男, birthday=2017-05-31 06:03:13.0, address=Address@c8b96ec]
} @Test
public void testUpdateStudents(){//更新记录
Students s = (Students)session.get(Students.class, 1);
s.setGender("女");
session.update(s);
System.out.println(s); } @Test
public void testDeleteStudents(){//删除记录
Students s = (Students)session.get(Students.class, 1);
session.delete(s);
}
}
五、总结
* 1、什么是ORM?为什么要使用Hibernate?
* ORM是对象关系映射
* 使用ORM的好处是使得习惯使用面向对象编程的程序员在项目中尽量少写和底层数据库相关的sql语句
* 这样做的好处:方便程序维护和修改以及跨平台性和扩展
* Hibernate是Java领域类技术成熟稳定的ORM框架
* 2、Hibernate开发的基本步骤
* (1)编写项目配置文档hibernate.cfg.xml
* (2)编写实体类(需遵循Java bins的规范)
* (3)生产对应实体类的映射文件并添加到配置文档中
* (4)调用Hibernate API函数进行测试
* 3、什么是session?
* hibernate对数据库的操作都要使用session对象,session对象相当于我们使用jdbc开发的一个connection对象
* 我们使用hibernate对数据库的操作本质上就是调用session的API函数来实现的
* save():(增)保存数据 get()/load():(查)取出数据 update():(改)更新数据 delete():(删)删除数据
* 4、openSession与getCurrentSession
* openSession每次创建一个新的实例对象,需要我们显示关闭
* getCurrentSession使用的是一种单例模式,每次创建的都是相同的对象,自动关闭
* 5、单表操作有哪些方法?
* save():(增)保存数据 delete():(删)删除数据 update():(改)更新数据 get()/load():(查)取出数据
* 6、get和load
* get使用时立刻发送sql语句,而且直接获得实体类本身
* load是在使用到具体的实例的非主属性的时候才会发送sql语句,返回的是代理对象
Hibernate实例二的更多相关文章
- Hibernate实例
Hibernate实例 一.Hibernate简介 Hibernate是简化项目中连接数据库的一个框架工具 Hibernate是Java领域类技术成熟稳定的ORM框架 * ORM是对象关系映射 * 使 ...
- SSH---整合Struts2&Spring&Hibernate(实例)
一.SSH回顾 Struts2:核心为过滤器+拦截器.过程:Filter--->FilterDispatcher-->ActionMapper-->ActionProxy--> ...
- 使用MyEclipse可视化开发Hibernate实例
2.7 使用MyEclipse可视化开发Hibernate实例 2.7节的例子源代码在配套光盘sourcecode/workspace目录的chapter02_first项目中. 这个实例主要演示如 ...
- C语言库函数大全及应用实例二
原文:C语言库函数大全及应用实例二 [编程资料]C语言库函数大全及应用实例二 函数名: bioskey 功 能 ...
- Ajax实例二:取得新内容
Ajax实例二:取得新内容 通过点击pre和next按钮,从服务器取得最新内容. HTML代码 <div id="slide">图片显示区</div> &l ...
- WPF中的多进程(Threading)处理实例(二)
原文:WPF中的多进程(Threading)处理实例(二) //错误的处理 private void cmdBreakRules_Click(object sender, RoutedEventArg ...
- Hibernate从入门到精通(二)Hibernate实例演示
上篇Hibernate从入门到精通(一)JDBC简介,我们主要对JDBC进行了简单介绍和使用说明,这次我们做一个Hibernate简单实例,通过这个实例对比Hibernate和JDBC,了解Hiber ...
- Hibernate(二)Hibernate 实例
上篇Hibernate(一)JDBC简介,我们主要对JDBC进行了简单介绍和使用说明,这次我们做一个Hibernate简单实例,通过这个实例对比Hibernate和JDBC,了解Hibernate的优 ...
- hibernate学习(二)
hibernate 单向一对多映射 一.数据表设计 数据库名:hibernate5 数据表: ①表名:CUSTOMERS 字段: CUSTOMER_ID CUSTOMER_NAME ②表名:ORDE ...
随机推荐
- 26最短路径之Floyd算法
Floyd算法 思想:将n个顶点的图G“分成”很多子图 每对顶点vi和vj对应子图Gij(i=0,1,…,n-1和j=0,1,…,n-1) 每对顶点vi和vj都保留一条顶点限于子图Gij中的最短路径P ...
- yii2模板
GridView 小部件在开发中常用的功能及技巧.持续更新中.... 数据网格或者说 GridView 小部件是Yii中最强大的部件之一.它有一个属性名叫 dataProvider ,这个属性能够提供 ...
- redis删除单个key和多个key,ssdb会落地导致重启redis无法清除缓存
redis删除单个key和多个key,ssdb会落地导致重启redis无法清除缓存,需要针对单个key进行删除 删除单个:del key 删除多个:redis-cli -a pass(密码) keys ...
- 三步搞定 opencv 初始环境设定
一.设定bin的初始位置:比如我的电脑 D:\安装程序\opencv\build\x86\vc10\bin H:\生产力工具\opencv\build\x86\vc10\bin D:\安装程 ...
- 20145306 张文锦 网络攻防 web基础
20145306 网络攻防 web基础 实验内容 WebServer:掌握Apache启停配置修改(如监听端口)前端编程:熟悉HTML+JavaScript.了解表单的概念编写不同的HTML网页,放入 ...
- CSS实现三角形、梯形、平行四边形、圆形、椭圆形、对话框、自适应正方形
本文篇幅较长,希望能坚持看完,转载请注明出处,如果觉得好文请给个赞吧 CSS实现梯形 CSS实现三角形和梯形主要是依靠border是梯形的特性来做的,有点像相框的那种感觉. 首先我们先给一个正方形设置 ...
- Python3基础 list 访问列表中的列表的元素
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- ADT Bundle下载和安装
下载官方adt集成包(即ADT Bundle)并安装. Android官方已经推出adt集成包,包含了eclipse.sdk和SDK Manager,只需解压出来,然后就能运行Eclipse. 官方集 ...
- LightOJ 1393 Crazy Calendar(博弈)题解
题意:r*c方格中,每个格子有一定石子,每次移动每格任意数量石子,只能向下或者向右动一格,不能移动为败 思路:显然是Nim,到右下曼哈顿距离为偶数的不用管,因为先手动一下后手动一下最后移到右下后还是先 ...
- C#面试题集锦
1.貌似最常用的是 值类型和引用类型,还有 装箱和 http://www.cnblogs.com/Autumoon/archive/2008/08/18/1270685.html http://ww ...