首页 > 代码库 > Hibernate实例二
Hibernate实例二
Hibernate实例二
一、测试openSession方法和getCurrentSession方法
hebernate中可以通过上述两种方法获取session对象以对数据库进行操作,下面的代码以及注解是对两种方法的辨析
SessionTest.java
1 import java.sql.Connection; 2 import java.sql.SQLException; 3 import java.util.Date; 4 5 import org.hibernate.Session; 6 import org.hibernate.SessionFactory; 7 import org.hibernate.Transaction; 8 import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 9 import org.hibernate.cfg.Configuration; 10 import org.hibernate.jdbc.Work; 11 import org.hibernate.service.ServiceRegistry; 12 import org.junit.Test; 13 14 /* 15 * session详解 16 * 如何获得session对象 17 * 1)openSession 18 * 2)getCurrentSession 19 * getCurrentSession在事务提交或者回滚之后会自动关闭,而openSession需要你 20 * 手动关闭。如果使用openSession而没有手动关闭,多次之后会导致连接池溢出 21 * 22 * openSession方法每次都是创建新的对象 23 * getCurrentSession一直使用的是同一个对象,有点类似单例模式 24 */ 25 26 27 28 public class SessionTest { 29 30 @Test 31 public void testOpenSession(){ 32 //创建配置对象 33 Configuration config = new Configuration().configure(); 34 //创建服务注册对象 35 ServiceRegistry serviceRegistry = new 36 StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build(); 37 //创建会话工厂对象 38 SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); 39 //创建会话对象 40 Session session1 = sessionFactory.openSession(); 41 Session session2 = sessionFactory.openSession(); 42 System.out.println(session1==session2);//false 43 /* 44 if (session!=null) { 45 System.out.println("session创建成功"); 46 } 47 else { 48 System.out.println("session创建失败"); 49 } 50 */ 51 } 52 53 @Test 54 public void testGetCurrentSession(){ 55 //创建配置对象 56 Configuration config = new Configuration().configure(); 57 //创建服务注册对象 58 ServiceRegistry serviceRegistry = new 59 StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build(); 60 //创建会话工厂对象 61 SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); 62 //创建会话对象 63 Session session1 = sessionFactory.getCurrentSession(); 64 Session session2 = sessionFactory.getCurrentSession(); 65 System.out.println(session1==session2);//true 66 /* 67 if (session!=null) { 68 System.out.println("session创建成功"); 69 } 70 else { 71 System.out.println("session创建失败"); 72 } 73 */ 74 } 75 76 @Test 77 public void testSaveStudentsWithOpenSession(){ 78 //创建配置对象 79 Configuration config = new Configuration().configure(); 80 //创建服务注册对象 81 ServiceRegistry serviceRegistry = new 82 StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build(); 83 //创建会话工厂对象 84 SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); 85 //创建会话对象 86 Session session1 = sessionFactory.openSession(); 87 //开启事务 88 Transaction transaction = session1.beginTransaction(); 89 //生产学生对象 90 Students s = new Students(1,"饭饭","男",new Date(),"博客园"); 91 session1.doWork(new Work() { 92 @Override 93 public void execute(Connection connection) throws SQLException { 94 // TODO Auto-generated method stub 95 System.out.println("connection hashCode:"+connection.hashCode()); 96 } 97 }); 98 session1.save(s);//保存对象进入数据库 99 //session1.close(); 100 transaction.commit();//提交事务 101 102 //创建会话对象 103 Session session2 = sessionFactory.openSession(); 104 //开启事务 105 transaction = session2.beginTransaction(); 106 //生产学生对象 107 s = new Students(2,"饭饭2","男",new Date(),"博客园2"); 108 session2.doWork(new Work() { 109 @Override 110 public void execute(Connection connection) throws SQLException { 111 // TODO Auto-generated method stub 112 System.out.println("connection hashCode:"+connection.hashCode()); 113 } 114 }); 115 session2.save(s);//保存对象进入数据库 116 transaction.commit();//提交事务 117 } 118 119 @Test 120 public void testSaveStudentsWithGetCurrentSession(){ 121 //创建配置对象 122 Configuration config = new Configuration().configure(); 123 //创建服务注册对象 124 ServiceRegistry serviceRegistry = new 125 StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build(); 126 //创建会话工厂对象 127 SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); 128 //创建会话对象 129 Session session1 = sessionFactory.getCurrentSession(); 130 //开启事务 131 Transaction transaction = session1.beginTransaction(); 132 //生产学生对象 133 Students s = new Students(1,"饭饭","男",new Date(),"博客园"); 134 session1.doWork(new Work() { 135 @Override 136 public void execute(Connection connection) throws SQLException { 137 // TODO Auto-generated method stub 138 System.out.println("connection hashCode:"+connection.hashCode()); 139 } 140 }); 141 session1.save(s);//保存对象进入数据库 142 //session1.close(); 143 transaction.commit();//提交事务 144 145 //创建会话对象 146 Session session2 = sessionFactory.getCurrentSession(); 147 //开启事务 148 transaction = session2.beginTransaction(); 149 //生产学生对象 150 s = new Students(2,"饭饭2","男",new Date(),"博客园2"); 151 session2.doWork(new Work() { 152 @Override 153 public void execute(Connection connection) throws SQLException { 154 // TODO Auto-generated method stub 155 System.out.println("connection hashCode:"+connection.hashCode()); 156 } 157 }); 158 session2.save(s);//保存对象进入数据库 159 transaction.commit();//提交事务 160 } 161 }
二、如何使用对象类型Blob类型
Blob类型可以用来存照片、音频、视频等文件
Hibernate对象数据类型
1、实体类中定义这样的属性
private Blob picture;//照片,大文本数据类型
当然也要写这个属性对应的get/set方法
2、修改映射文件
<property name="picture" type="java.sql.Blob">
<column name="PICTURE" />
</property>
3、测试Blob类型
1 //这里报错我一直在纠结,其实视频里面这里也有错啊,我浪费时间 2 //多去看视频下面的评论,有告诉我们很多问题的解决方案 3 //运行代码时老犯配置错误,原来配置文件中不支持java注释的写法 4 //我是通过删减犯错位置的代码来发现错误的 5 6 7 8 import java.io.File; 9 import java.io.FileInputStream; 10 import java.io.FileOutputStream; 11 import java.io.InputStream; 12 import java.io.OutputStream; 13 import java.sql.Blob; 14 import java.util.Date; 15 16 import javax.print.DocFlavor.INPUT_STREAM; 17 18 import org.hibernate.Hibernate; 19 import org.hibernate.Session; 20 import org.hibernate.SessionFactory; 21 import org.hibernate.Transaction; 22 import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 23 import org.hibernate.cfg.Configuration; 24 import org.hibernate.service.ServiceRegistry; 25 import org.junit.After; 26 import org.junit.Before; 27 import org.junit.Test; 28 29 30 31 //测试类 32 public class StudentsTest { 33 34 private SessionFactory sessionFactory; 35 private Session session; 36 private Transaction transaction; 37 38 @Before 39 public void init(){ 40 //创建配置对象 41 Configuration config = new Configuration().configure(); 42 //创建服务注册对象 43 ServiceRegistry serviceRegistry = new 44 StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();//这里有点不一样 45 //创建会话工厂对象 46 sessionFactory = config.buildSessionFactory(serviceRegistry); 47 //会话对象 48 session = sessionFactory.openSession(); 49 //开启事务 50 transaction = session.beginTransaction(); 51 52 } 53 54 @After 55 public void destory(){ 56 transaction.commit();//提交事务 57 session.close();//关闭会话 58 sessionFactory.close();//关闭会话工厂 59 } 60 61 62 @Test 63 public void testSaveStudents(){ 64 //生产学生对象 65 // Students s = new Students(1,"饭饭","男",new Date(),"博客园"); 66 Students s = new Students(); 67 s.setSid(1); 68 s.setSname("饭饭"); 69 s.setGender("男"); 70 s.setBirthday(new Date()); 71 //s.setAddress("博客园"); 72 Address address = new Address("400715","1888****749","重庆北碚西南大学"); 73 s.setAddress(address); 74 session.save(s);//保存对象进入数据库 75 } 76 77 @Test 78 public void TestWriteBlob() throws Exception { 79 Students s = new Students(1,"饭饭","男",new Date(),"博客园"); 80 //先获得照片文件 81 File f = new File("e:"+File.separator+"fanfan.jpg"); 82 //获取照片文件的输入流 83 InputStream input = new FileInputStream(f); 84 //创建一个Blob对象 85 Blob image = (Blob) Hibernate.getLobCreator(session).createBlob(input, input.available()); 86 //设置照片属性 87 s.setPicture(image); 88 //保存学生 89 session.save(s); 90 } 91 92 @Test 93 public void testReadBlob() throws Exception{ 94 Students s = (Students)session.get(Students.class, 1); 95 //获取Blob对象 96 Blob image = s.getPicture(); 97 //获取输入流 98 InputStream input = image.getBinaryStream(); 99 //创建输出流 100 File f = new File("e:"+File.separator+"dest.jpg"); 101 //获取输出流 102 OutputStream output = new FileOutputStream(f); 103 //创建缓冲区 104 byte[] buff = new byte[input.available()]; 105 input.read(buff); 106 output.write(buff); 107 input.close(); 108 output.close(); 109 110 } 111 112 }
三、Hibernate使用组件类型
1、写出属性类Address.java,并在实体类Students.java中添加Address属性
1 //地址类 2 public class Address { 3 4 private String postcode;//邮编 5 private String phone;//电话 6 private String address;//地址 7 8 public Address(){ 9 10 } 11 12 public Address(String postcode, String phone, String address) { 13 //super(); 14 this.postcode = postcode; 15 this.phone = phone; 16 this.address = address; 17 } 18 19 public String getPostcode() { 20 return postcode; 21 } 22 23 public void setPostcode(String postcode) { 24 this.postcode = postcode; 25 } 26 27 public String getPhone() { 28 return phone; 29 } 30 31 public void setPhone(String phone) { 32 this.phone = phone; 33 } 34 35 public String getAddress() { 36 return address; 37 } 38 39 public void setAddress(String address) { 40 this.address = address; 41 } 42 43 44 45 }
下面是在实体类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、测试组件类型
1 //这里报错我一直在纠结,其实视频里面这里也有错啊,我浪费时间 2 //多去看视频下面的评论,有告诉我们很多问题的解决方案 3 //运行代码时老犯配置错误,原来配置文件中不支持java注释的写法 4 //我是通过删减犯错位置的代码来发现错误的 5 6 7 8 import java.io.File; 9 import java.io.FileInputStream; 10 import java.io.FileOutputStream; 11 import java.io.InputStream; 12 import java.io.OutputStream; 13 import java.sql.Blob; 14 import java.util.Date; 15 16 import javax.print.DocFlavor.INPUT_STREAM; 17 18 import org.hibernate.Hibernate; 19 import org.hibernate.Session; 20 import org.hibernate.SessionFactory; 21 import org.hibernate.Transaction; 22 import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 23 import org.hibernate.cfg.Configuration; 24 import org.hibernate.service.ServiceRegistry; 25 import org.junit.After; 26 import org.junit.Before; 27 import org.junit.Test; 28 29 30 31 //测试类 32 public class StudentsTest { 33 34 private SessionFactory sessionFactory; 35 private Session session; 36 private Transaction transaction; 37 38 @Before 39 public void init(){ 40 //创建配置对象 41 Configuration config = new Configuration().configure(); 42 //创建服务注册对象 43 ServiceRegistry serviceRegistry = new 44 StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();//这里有点不一样 45 //创建会话工厂对象 46 sessionFactory = config.buildSessionFactory(serviceRegistry); 47 //会话对象 48 session = sessionFactory.openSession(); 49 //开启事务 50 transaction = session.beginTransaction(); 51 52 } 53 54 @After 55 public void destory(){ 56 transaction.commit();//提交事务 57 session.close();//关闭会话 58 sessionFactory.close();//关闭会话工厂 59 } 60 61 62 @Test 63 public void testSaveStudents(){ 64 //生产学生对象 65 // Students s = new Students(1,"饭饭","男",new Date(),"博客园"); 66 Students s = new Students(); 67 s.setSid(1); 68 s.setSname("饭饭"); 69 s.setGender("男"); 70 s.setBirthday(new Date()); 71 //s.setAddress("博客园"); 72 Address address = new Address("400715","1888****749","重庆北碚西南大学"); 73 s.setAddress(address); 74 session.save(s);//保存对象进入数据库 75 } 76 77 }
四、Hibernate的增删改查操作
* save():(增)保存数据 delete():(删)删除数据 update():(改)更新数据 get()/load():(查)取出数据
1 //这里报错我一直在纠结,其实视频里面这里也有错啊,我浪费时间 2 //多去看视频下面的评论,有告诉我们很多问题的解决方案 3 //运行代码时老犯配置错误,原来配置文件中不支持java注释的写法 4 //我是通过删减犯错位置的代码来发现错误的 5 6 7 8 import java.io.File; 9 import java.io.FileInputStream; 10 import java.io.FileOutputStream; 11 import java.io.InputStream; 12 import java.io.OutputStream; 13 import java.sql.Blob; 14 import java.util.Date; 15 16 import javax.print.DocFlavor.INPUT_STREAM; 17 18 import org.hibernate.Hibernate; 19 import org.hibernate.Session; 20 import org.hibernate.SessionFactory; 21 import org.hibernate.Transaction; 22 import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 23 import org.hibernate.cfg.Configuration; 24 import org.hibernate.service.ServiceRegistry; 25 import org.junit.After; 26 import org.junit.Before; 27 import org.junit.Test; 28 29 30 31 //测试类 32 public class StudentsTest { 33 34 private SessionFactory sessionFactory; 35 private Session session; 36 private Transaction transaction; 37 38 @Before 39 public void init(){ 40 //创建配置对象 41 Configuration config = new Configuration().configure(); 42 //创建服务注册对象 43 ServiceRegistry serviceRegistry = new 44 StandardServiceRegistryBuilder().applySettings(config.getProperties()).configure().build();//这里有点不一样 45 //创建会话工厂对象 46 sessionFactory = config.buildSessionFactory(serviceRegistry); 47 //会话对象 48 session = sessionFactory.openSession(); 49 //开启事务 50 transaction = session.beginTransaction(); 51 52 } 53 54 @After 55 public void destory(){ 56 transaction.commit();//提交事务 57 session.close();//关闭会话 58 sessionFactory.close();//关闭会话工厂 59 } 60 61 62 @Test 63 public void testSaveStudents(){ 64 //生产学生对象 65 // Students s = new Students(1,"饭饭","男",new Date(),"博客园"); 66 Students s = new Students(); 67 s.setSid(1); 68 s.setSname("饭饭"); 69 s.setGender("男"); 70 s.setBirthday(new Date()); 71 //s.setAddress("博客园"); 72 Address address = new Address("400715","1888****749","重庆北碚西南大学"); 73 s.setAddress(address); 74 session.save(s);//保存对象进入数据库 75 } 76 77 /* 78 * get和load都是查询单个记录 79 * 1、get方法会向数据库立即发送sql语句,load方法要等到第一次用的时候再发sql语句 80 * 2、get方法返回的是本身对象,load方法返回的是代理对象,代理对象只保存了实例对象的主键id 81 * 3、查询对象不存在时,get返回null,load返回ObjectNotFoundException异常 82 */ 83 84 @Test 85 public void testGetStudents(){//get查询单个记录 86 Students s = (Students)session.get(Students.class, 1); 87 System.out.println(s.getClass().getName());//answer: Students 88 System.out.println(s); 89 //answer: Students [sid=1, sname=饭饭, gender=男, birthday=2017-05-31 06:03:13.0, address=Address@c8b96ec] 90 } 91 92 @Test 93 public void testLoadStudents(){//load查询单个记录 94 /* 95 * 没有后面这个输出s的语句,load方法不向数据库发送sql语句,加上这句话立马就有了 96 * 97 */ 98 Students s = (Students)session.load(Students.class, 1); 99 System.out.println(s.getClass().getName());//answer: Students_$$_jvstd5_0 显然这个结果是一个代理对象 100 System.out.println(s); 101 //answer: Students [sid=1, sname=饭饭, gender=男, birthday=2017-05-31 06:03:13.0, address=Address@c8b96ec] 102 } 103 104 @Test 105 public void testUpdateStudents(){//更新记录 106 Students s = (Students)session.get(Students.class, 1); 107 s.setGender("女"); 108 session.update(s); 109 System.out.println(s); 110 111 } 112 113 @Test 114 public void testDeleteStudents(){//删除记录 115 Students s = (Students)session.get(Students.class, 1); 116 session.delete(s); 117 } 118 }
五、总结
* 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实例二