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语句,返回的是代理对象

最新文章

  1. 关于LockSupport
  2. ASP.net 验证码(C#) MVC
  3. HDU 4643 GSM 算术几何
  4. AngularJS开发相关配置
  5. Discuz建站教程:本地安装discuz网站
  6. 深入浅出Hadoop Mahout数据挖掘实战(算法分析、项目实战、中文分词技术)
  7. MySQL两种引擎的区别
  8. 深入学习javaScript闭包(闭包的原理,闭包的作用,闭包与内存管理)
  9. Educational Codeforces Round 5
  10. jenkins ansible 附zabbix_agent批量安装示例
  11. git获取一个版本相对于另一个版本新增,修改,删除的文件
  12. POJ 1936 All in All 匹配, 水题 难度:0
  13. APICloud开发
  14. PCB中实现元器件旋转一个角度放置
  15. C# 多线程九之Timer类
  16. JS 提升 p4
  17. SpringCloud 组件Eureka参数配置项详解
  18. 【leetcode】solution in java——Easy4
  19. linux磁盘空间使用问题
  20. 【Python】Python基础教程系列目录

热门文章

  1. RocketMQ 集群搭建--双Master方案
  2. pandas练习(一)------ 了解数据
  3. jQuery ajax 请求HttpServlet返回[HTTP/1.1 405 Method not allowed]
  4. mysql设置环境变量
  5. Linux配置自动时间同步
  6. Nginx服务器之负载均衡策略(6种)
  7. 20145127《java程序设计》第四周学习总结
  8. 20145127《java程序设计》第三周学习总结
  9. C++类的静态成员变量初始化 Win32 API 定时器使用
  10. 函数引用参数加const