[关闭]
@chy282 2017-12-01T14:46:58.000000Z 字数 8903 阅读 2595

Hibernate二次学习二----------session.flush、session.doWork

Hibernate


© 版权声明:本文为博主原创文章,转载请注明出处

1. session

Hibernate是对JDBC的轻量级封装,将JDBC的Connection封装到了Session中,因此Hibernate对数据库的操作大多都是通过session实现的。

2. session.flush

在获取Session对象时,Hibernate默认关闭了自动提交事务。
Hibernate执行SQL时,会将所有SQL存入Session的缓存中,提交事务时,再在数据库中执行SQL
  1. private SessionFactory sessionFactory;
  2. private Session session;
  3. private Transaction transaction;
  4. @Test
  5. public void testSaveStudent() {
  6. // 生成学生对象
  7. Student s = new Student(3, "张三丰", "男", new Date(), "武当山");
  8. session.save(s);
  9. }
  10. Before
  11. public void init() {
  12. // 创建会话工厂对象
  13. sessionFactory = new Configuration().configure().buildSessionFactory();
  14. // 创建会话对象
  15. session = sessionFactory.openSession();
  16. // 开始事务
  17. transaction = session.beginTransaction();
  18. }
  19. @After
  20. public void destory () {
  21. // 提交事务
  22. transaction.commit();
  23. // 关闭会话
  24. session.close();
  25. // 关闭会话工厂
  26. sessionFactory.close();
  27. }
若不开启事务或开启事务不提交,则SQL语句就不能在数据库中执行,此时可以通过session.flush()方法,强制将缓存中的SQL语句刷新到数据库
  1. private SessionFactory sessionFactory;
  2. private Session session;
  3. /**
  4. * 不开启事务,数据无法保存到数据库
  5. */
  6. @Test
  7. public void testSaveStudentNoTransaction() {
  8. // 生成学生对象
  9. Student s = new Student(5, "张三丰", "男", new Date(), "武当山");
  10. session.save(s);
  11. }
  12. /**
  13. * 不开启事务,使用session.flush()强制同步数据到数据库
  14. */
  15. @Test
  16. public void testSaveStudentByflush() {
  17. // 生成学生对象
  18. Student s = new Student(5, "张三丰", "男", new Date(), "武当山");
  19. session.save(s);
  20. session.flush();// 当不使用事务时,需使用flush方法,强制提交
  21. }
  22. /**
  23. * 开启事务,但不使用commit提交,而是使用session.flush()强制提交
  24. */
  25. @Test
  26. public void testSaveStudentTransaction() {
  27. // 开启事务
  28. session.beginTransaction();
  29. // 生成学生对象
  30. Student s = new Student(6, "张三丰", "男", new Date(), "武当山");
  31. session.save(s);
  32. session.flush();// 不提交事务时,直接使用flush方法,也可强制提交
  33. }
  34. Before
  35. public void init() {
  36. // 创建会话工厂对象
  37. sessionFactory = new Configuration().configure().buildSessionFactory();
  38. // 创建会话对象
  39. session = sessionFactory.openSession();
  40. }
  41. @After
  42. public void destory () {
  43. // 关闭会话
  44. session.close();
  45. // 关闭会话工厂
  46. sessionFactory.close();
  47. }

3. session.doWork

Hibernate使用面向对象的思想来进行数据库操作,推荐使用的也是封装的HQL语句,但有时项目需要进行jdbc操作,此时可以使用session.doWork(),在匿名内部类中获取Connection,进行jdbc操作。
  1. /**
  2. * 使用session.doWork()实现jdbc操作
  3. */
  4. @Test
  5. public void testSessionDowork() {
  6. final List<String> list = new ArrayList<String>();
  7. session.doWork(new Work() { // 使用dowork方法进行jdbc操作
  8. @Override
  9. public void execute(Connection connection) throws SQLException {
  10. String sql = "select sname from student";
  11. PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);
  12. ResultSet rs = ps.executeQuery();
  13. try {
  14. while (rs.next()) {
  15. String name = rs.getString(1);
  16. list.add(name);
  17. }
  18. } finally {
  19. if (rs != null) {
  20. rs.close();
  21. }
  22. if (ps != null) {
  23. ps.close();
  24. }
  25. // 此时connection被session管理,不能手动关闭
  26. /*if (connection != null) {
  27. connection.close();
  28. }*/
  29. }
  30. }
  31. });
  32. for (int i = 0; i < list.size(); i++) {
  33. System.out.println(list.get(i));
  34. }
  35. }
  36. Before
  37. public void init() {
  38. // 创建会话工厂对象
  39. sessionFactory = new Configuration().configure().buildSessionFactory();
  40. // 创建会话对象
  41. session = sessionFactory.openSession();
  42. }
  43. @After
  44. public void destory () {
  45. // 关闭会话
  46. session.close();
  47. // 关闭会话工厂
  48. sessionFactory.close();
  49. }

4. 完整代码

pom.xml
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>org.imooc</groupId>
  5. <artifactId>Hibernate_001</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <packaging>jar</packaging>
  8. <properties>
  9. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  10. </properties>
  11. <dependencies>
  12. <!-- junit -->
  13. <dependency>
  14. <groupId>junit</groupId>
  15. <artifactId>junit</artifactId>
  16. <version>4.12</version>
  17. <scope>test</scope>
  18. </dependency>
  19. <!-- Hibernate -->
  20. <dependency>
  21. <groupId>org.hibernate</groupId>
  22. <artifactId>hibernate-core</artifactId>
  23. <version>5.1.5.Final</version>
  24. </dependency>
  25. <!-- mysql-connector-java -->
  26. <dependency>
  27. <groupId>mysql</groupId>
  28. <artifactId>mysql-connector-java</artifactId>
  29. <version>5.1.22</version>
  30. </dependency>
  31. </dependencies>
  32. <build>
  33. <plugins>
  34. <plugin>
  35. <groupId>org.apache.maven.plugins</groupId>
  36. <artifactId>maven-compiler-plugin</artifactId>
  37. <version>3.6.1</version>
  38. <configuration>
  39. <target>1.7</target>
  40. <source>1.7</source>
  41. <encoding>UTF-8</encoding>
  42. </configuration>
  43. </plugin>
  44. </plugins>
  45. </build>
  46. </project>
Student.java
  1. package com.imooc.hibernate.model;
  2. import java.util.Date;
  3. public class Student {
  4. private int sid; // 学号
  5. private String sname; // 姓名
  6. private String gender; // 性别
  7. private Date birthday; // 出生日期
  8. private String address; // 地址
  9. public Student() {
  10. }
  11. public Student(int sid, String sname, String gender, Date birthday, String address) {
  12. this.sid = sid;
  13. this.sname = sname;
  14. this.gender = gender;
  15. this.birthday = birthday;
  16. this.address = address;
  17. }
  18. public int getSid() {
  19. return sid;
  20. }
  21. public void setSid(int sid) {
  22. this.sid = sid;
  23. }
  24. public String getSname() {
  25. return sname;
  26. }
  27. public void setSname(String sname) {
  28. this.sname = sname;
  29. }
  30. public String getGender() {
  31. return gender;
  32. }
  33. public void setGender(String gender) {
  34. this.gender = gender;
  35. }
  36. public Date getBirthday() {
  37. return birthday;
  38. }
  39. public void setBirthday(Date birthday) {
  40. this.birthday = birthday;
  41. }
  42. public String getAddress() {
  43. return address;
  44. }
  45. public void setAddress(String address) {
  46. this.address = address;
  47. }
  48. @Override
  49. public String toString() {
  50. return "Student [sid=" + sid + ", sname=" + sname + ", gender="
  51. + gender + ", birthday=" + birthday + ", address=" + address + "]";
  52. }
  53. }
student.hbm.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <class name="com.imooc.hibernate.model.Student">
  7. <id name="sid" type="int">
  8. <column name="SID"/>
  9. <generator class="assigned"/> <!-- 主键生成策略 -->
  10. </id>
  11. <property name="sname" type="java.lang.String">
  12. <column name="SNAME"/>
  13. </property>
  14. <property name="gender" type="java.lang.String">
  15. <column name="GENDER"></column>
  16. </property>
  17. <property name="birthday" type="java.util.Date">
  18. <column name="BIRTHDAY"/>
  19. </property>
  20. <property name="address" type="java.lang.String">
  21. <column name="ADDRESS"></column>
  22. </property>
  23. </class>
  24. </hibernate-mapping>
hibernate.cfg.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7. <!-- 数据库连接名 -->
  8. <property name="connection.username">root</property>
  9. <!-- 数据库连接密码 -->
  10. <property name="connection.password">20121221</property>
  11. <!-- 数据库驱动 -->
  12. <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  13. <!-- 数据库连接url -->
  14. <property name="connection.url">
  15. jdbc:mysql://localhost:3306/hibernate?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8
  16. </property>
  17. <!-- 方言 -->
  18. <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
  19. <!-- 展示SQL -->
  20. <property name="show_sql">true</property>
  21. <!-- 格式化SQL -->
  22. <property name="format_sql">false</property>
  23. <!-- 建表策略 -->
  24. <property name="hbm2ddl.auto">update</property>
  25. <!-- 指定映射文件 -->
  26. <mapping resource="hbm/student.hbm.xml"/>
  27. </session-factory>
  28. </hibernate-configuration>
StudentTest.java
  1. package com.imooc.hibernate.test;
  2. import java.sql.Connection;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.util.ArrayList;
  6. import java.util.Date;
  7. import java.util.List;
  8. import org.hibernate.Session;
  9. import org.hibernate.SessionFactory;
  10. import org.hibernate.cfg.Configuration;
  11. import org.hibernate.jdbc.Work;
  12. import org.junit.After;
  13. import org.junit.Before;
  14. import org.junit.Test;
  15. import com.imooc.hibernate.model.Student;
  16. import com.mysql.jdbc.PreparedStatement;
  17. public class StudentTest {
  18. private SessionFactory sessionFactory;
  19. private Session session;
  20. /**
  21. * 不开启事务,数据无法保存到数据库
  22. */
  23. @Test
  24. public void testSaveStudentNoTransaction() {
  25. // 生成学生对象
  26. Student s = new Student(5, "张三丰", "男", new Date(), "武当山");
  27. session.save(s);
  28. }
  29. /**
  30. * 不开启事务,使用session.flush()强制同步数据到数据库
  31. */
  32. @Test
  33. public void testSaveStudentByflush() {
  34. // 生成学生对象
  35. Student s = new Student(5, "张三丰", "男", new Date(), "武当山");
  36. session.save(s);
  37. session.flush();// 当不使用事务时,需使用flush方法,强制提交
  38. }
  39. /**
  40. * 开启事务,但不使用commit提交,而是使用session.flush()强制提交
  41. */
  42. @Test
  43. public void testSaveStudentTransaction() {
  44. // 开启事务
  45. session.beginTransaction();
  46. // 生成学生对象
  47. Student s = new Student(6, "张三丰", "男", new Date(), "武当山");
  48. session.save(s);
  49. session.flush();// 不提交事务时,直接使用flush方法,也可强制提交
  50. }
  51. /**
  52. * 使用session.doWork()实现jdbc操作
  53. */
  54. @Test
  55. public void testSessionDowork() {
  56. final List<String> list = new ArrayList<String>();
  57. session.doWork(new Work() { // 使用dowork方法进行jdbc操作
  58. @Override
  59. public void execute(Connection connection) throws SQLException {
  60. String sql = "select sname from student";
  61. PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);
  62. ResultSet rs = ps.executeQuery();
  63. try {
  64. while (rs.next()) {
  65. String name = rs.getString(1);
  66. list.add(name);
  67. }
  68. } finally {
  69. if (rs != null) {
  70. rs.close();
  71. }
  72. if (ps != null) {
  73. ps.close();
  74. }
  75. // 此时connection被session管理,不能手动关闭
  76. /*if (connection != null) {
  77. connection.close();
  78. }*/
  79. }
  80. }
  81. });
  82. for (int i = 0; i < list.size(); i++) {
  83. System.out.println(list.get(i));
  84. }
  85. }
  86. @Before
  87. public void init() {
  88. // 创建会话工厂对象
  89. sessionFactory = new Configuration().configure().buildSessionFactory();
  90. // 创建会话对象
  91. session = sessionFactory.openSession();
  92. }
  93. @After
  94. public void destory () {
  95. // 关闭会话
  96. session.close();
  97. // 关闭会话工厂
  98. sessionFactory.close();
  99. }
  100. }

5. 总结

使用Hibernate时,若需使用jdbc进行操作,则使用session.doWork()
若需提前提交session缓存中的SQL,则使用session.flush()
eg:
  1. Transaction tx = session.beginTransaction();
  2. for (int i = 0; i < 100000; i++) {
  3. Student s = new Student(...);
  4. session.save(s);
  5. if (i % 20 == 0) { // 防止session内存溢出
  6. session.flush();
  7. session.clear();
  8. }
  9. }
  10. tx.commit();
  11. session.close();

参考:Hibernate初探之单表映射

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注