Hibernate实战——命名SQL查询

比眉伴天荒 2021-07-24 23:20 554阅读 0赞

一 配置文件

  1. <?xml version="1.0" encoding="GBK"?>
  2. <!-- 指定Hibernate配置文件的DTD信息 -->
  3. <!DOCTYPE hibernate-configuration PUBLIC
  4. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  5. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  6. <!-- hibernate-configuration是配置文件的根元素 -->
  7. <hibernate-configuration>
  8. <session-factory>
  9. <!-- 指定连接数据库所用的驱动 -->
  10. <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  11. <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
  12. <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
  13. <!-- 指定连接数据库的用户名 -->
  14. <property name="connection.username">root</property>
  15. <!-- 指定连接数据库的密码 -->
  16. <property name="connection.password">32147</property>
  17. <!-- 指定连接池里最大连接数 -->
  18. <property name="hibernate.c3p0.max_size">20</property>
  19. <!-- 指定连接池里最小连接数 -->
  20. <property name="hibernate.c3p0.min_size">1</property>
  21. <!-- 指定连接池里连接的超时时长 -->
  22. <property name="hibernate.c3p0.timeout">5000</property>
  23. <!-- 指定连接池里最大缓存多少个Statement对象 -->
  24. <property name="hibernate.c3p0.max_statements">100</property>
  25. <property name="hibernate.c3p0.idle_test_period">3000</property>
  26. <property name="hibernate.c3p0.acquire_increment">2</property>
  27. <property name="hibernate.c3p0.validate">true</property>
  28. <!-- 指定数据库方言 -->
  29. <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
  30. <!-- 根据需要自动创建数据库 -->
  31. <property name="hbm2ddl.auto">update</property>
  32. <!-- 显示Hibernate持久化操作所生成的SQL -->
  33. <property name="show_sql">true</property>
  34. <!-- 将SQL脚本进行格式化后再输出 -->
  35. <property name="hibernate.format_sql">true</property>
  36. <!-- 罗列所有持久化类的类名 -->
  37. <mapping class="org.crazyit.app.domain.Enrolment"/>
  38. <mapping class="org.crazyit.app.domain.Student"/>
  39. <mapping class="org.crazyit.app.domain.Course"/>
  40. </session-factory>
  41. </hibernate-configuration>

二 PO

Student

  1. package org.crazyit.app.domain;
  2. import java.util.*;
  3. import javax.persistence.*;
  4. @Entity
  5. @Table(name="student_inf")
  6. public class Student
  7. {
  8. // 代表学生学号的成员变量,将作为标识属性
  9. @Id @Column(name="student_id")
  10. private Integer studentNumber;
  11. // 代表学生姓名的成员变量
  12. private String name;
  13. // 该学生的所有选课记录对应的关联实体
  14. @OneToMany(targetEntity=Enrolment.class
  15. , mappedBy="student" , cascade=CascadeType.REMOVE)
  16. private Set<Enrolment> enrolments
  17. = new HashSet<>();
  18. // 无参数的构造器
  19. public Student()
  20. {
  21. }
  22. // 初始化全部成员变量的构造器
  23. public Student(Integer studentNumber , String name)
  24. {
  25. this.studentNumber = studentNumber;
  26. this.name = name;
  27. }
  28. // studentNumber的setter和getter方法
  29. public void setStudentNumber(Integer studentNumber)
  30. {
  31. this.studentNumber = studentNumber;
  32. }
  33. public Integer getStudentNumber()
  34. {
  35. return this.studentNumber;
  36. }
  37. // name的setter和getter方法
  38. public void setName(String name)
  39. {
  40. this.name = name;
  41. }
  42. public String getName()
  43. {
  44. return this.name;
  45. }
  46. // enrolments的setter和getter方法
  47. public void setEnrolments(Set<Enrolment> enrolments)
  48. {
  49. this.enrolments = enrolments;
  50. }
  51. public Set<Enrolment> getEnrolments()
  52. {
  53. return this.enrolments;
  54. }
  55. }

Enrolment

  1. package org.crazyit.app.domain;
  2. import javax.persistence.*;
  3. @Entity
  4. @Table(name = "enrolment_inf")
  5. public class Enrolment
  6. {
  7. // 定义标识属性
  8. @Id
  9. @Column(name = "enrolment_id")
  10. @GeneratedValue(strategy = GenerationType.IDENTITY)
  11. private Integer enrolmentId;
  12. // 定义选课记录所属的学年
  13. private int year;
  14. // 定义选课记录所属的学期
  15. private int semester;
  16. // 定义选课记录关联的学生实体
  17. @ManyToOne(targetEntity = Student.class)
  18. @JoinColumn(name = "student_id")
  19. private Student student;
  20. // 定义选课记录关联的课程实体
  21. @ManyToOne(targetEntity = Course.class)
  22. @JoinColumn(name = "course_code")
  23. private Course course;
  24. // enrolmentId的setter和getter方法
  25. public void setEnrolmentId(Integer enrolmentId) {
  26. this.enrolmentId = enrolmentId;
  27. }
  28. public Integer getEnrolmentId() {
  29. return this.enrolmentId;
  30. }
  31. // year的setter和getter方法
  32. public void setYear(int year) {
  33. this.year = year;
  34. }
  35. public int getYear() {
  36. return this.year;
  37. }
  38. // semester的setter和getter方法
  39. public void setSemester(int semester) {
  40. this.semester = semester;
  41. }
  42. public int getSemester() {
  43. return this.semester;
  44. }
  45. // student的setter和getter方法
  46. public void setStudent(Student student) {
  47. this.student = student;
  48. }
  49. public Student getStudent() {
  50. return this.student;
  51. }
  52. // course的setter和getter方法
  53. public void setCourse(Course course) {
  54. this.course = course;
  55. }
  56. public Course getCourse() {
  57. return this.course;
  58. }
  59. }

Course

  1. package org.crazyit.app.domain;
  2. import javax.persistence.*;
  3. @Entity
  4. @Table(name="course_inf")
  5. public class Course
  6. {
  7. // 代表课程编号的成员变量,将作为标识属性
  8. @Id @Column(name="course_code")
  9. private String courseCode;
  10. // 代表课程名成员变量
  11. private String name;
  12. // 无参数的构造器
  13. public Course()
  14. {
  15. }
  16. // 初始化全部成员变量的构造器
  17. public Course(String courseCode , String name)
  18. {
  19. this.courseCode = courseCode;
  20. this.name = name;
  21. }
  22. // courseCode的setter和getter方法
  23. public void setCourseCode(String courseCode)
  24. {
  25. this.courseCode = courseCode;
  26. }
  27. public String getCourseCode()
  28. {
  29. return this.courseCode;
  30. }
  31. // name的setter和getter方法
  32. public void setName(String name)
  33. {
  34. this.name = name;
  35. }
  36. public String getName()
  37. {
  38. return this.name;
  39. }
  40. }

三 VO

  1. package org.crazyit.app.vo;
  2. public class StudentCourse
  3. {
  4. private String stuName;
  5. private String courseName;
  6. // stuName的setter和getter方法
  7. public void setStuName(String stuName)
  8. {
  9. this.stuName = stuName;
  10. }
  11. public String getStuName()
  12. {
  13. return this.stuName;
  14. }
  15. // courseName的setter和getter方法
  16. public void setCourseName(String courseName)
  17. {
  18. this.courseName = courseName;
  19. }
  20. public String getCourseName()
  21. {
  22. return this.courseName;
  23. }
  24. }

四 测试

1 工具类

  1. package lee;
  2. import org.hibernate.*;
  3. import org.hibernate.cfg.*;
  4. import org.hibernate.service.*;
  5. import org.hibernate.boot.registry.*;
  6. public class HibernateUtil
  7. {
  8. public static final SessionFactory sessionFactory;
  9. static
  10. {
  11. try
  12. {
  13. // 使用默认的hibernate.cfg.xml配置文件创建Configuration实例
  14. Configuration cfg = new Configuration()
  15. .configure();
  16. // 以Configuration实例来创建SessionFactory实例
  17. ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
  18. .applySettings(cfg.getProperties()).build();
  19. sessionFactory = cfg.buildSessionFactory(serviceRegistry);
  20. }
  21. catch (Throwable ex)
  22. {
  23. System.err.println("Initial SessionFactory creation failed." + ex);
  24. throw new ExceptionInInitializerError(ex);
  25. }
  26. }
  27. // ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
  28. public static final ThreadLocal<Session> session
  29. = new ThreadLocal<Session>();
  30. public static Session currentSession()
  31. throws HibernateException
  32. {
  33. Session s = session.get();
  34. // 如果该线程还没有Session,则创建一个新的Session
  35. if (s == null)
  36. {
  37. s = sessionFactory.openSession();
  38. // 将获得的Session变量存储在ThreadLocal变量session里
  39. session.set(s);
  40. }
  41. return s;
  42. }
  43. public static void closeSession()
  44. throws HibernateException
  45. {
  46. Session s = session.get();
  47. if (s != null)
  48. s.close();
  49. session.set(null);
  50. }
  51. }

2 测试类

  1. package lee;
  2. import org.hibernate.*;
  3. import org.hibernate.transform.*;
  4. import java.util.*;
  5. import org.crazyit.app.domain.*;
  6. public class NamedSQLTest {
  7. public static void main(String[] args) {
  8. NamedSQLTest test = new NamedSQLTest();
  9. System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
  10. test.simpleQuery();
  11. System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
  12. test.query();
  13. System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
  14. test.callProcedure();
  15. HibernateUtil.sessionFactory.close();
  16. }
  17. // 执行简单的命名SQL查询
  18. private void simpleQuery() {
  19. // 打开Session和事务
  20. Session session = HibernateUtil.currentSession();
  21. Transaction tx = session.beginTransaction();
  22. // 调用命名查询,直接返回结果
  23. List list = session.getNamedQuery("simpleQuery").list();
  24. tx.commit();
  25. HibernateUtil.closeSession();
  26. // 遍历结果集
  27. for (Object ele : list) {
  28. // 每个集合元素是Student对象
  29. Student s = (Student) ele;
  30. System.out.println(s.getName() + "\t");
  31. }
  32. }
  33. // 执行命名SQL查询
  34. private void query() {
  35. // 打开Session和事务
  36. Session session = HibernateUtil.currentSession();
  37. Transaction tx = session.beginTransaction();
  38. // 调用命名查询,直接返回结果
  39. List list = session.getNamedQuery("queryTest").setInteger("targetYear", 2005).list();
  40. tx.commit();
  41. HibernateUtil.closeSession();
  42. // 遍历结果集
  43. for (Object ele : list) {
  44. // 每个集合元素是Student、Enrolment
  45. // 和stuName三个元素的数组
  46. Object[] objs = (Object[]) ele;
  47. Student s = (Student) objs[0];
  48. Enrolment e = (Enrolment) objs[1];
  49. Course c = (Course) objs[2];
  50. String stuName = (String) objs[3];
  51. System.out.println(s.getName() + "\t" + e.getYear() + "\t" + e.getSemester() + "\t="
  52. + e.getCourse().getName() + "=\t" + stuName);
  53. }
  54. }
  55. // 调用存储过程
  56. private void callProcedure() {
  57. // 打开Session和事务
  58. Session session = HibernateUtil.currentSession();
  59. Transaction tx = session.beginTransaction();
  60. // 调用命名查询,直接返回结果
  61. List list = session.getNamedQuery("callProcedure").list();
  62. tx.commit();
  63. HibernateUtil.closeSession();
  64. // 遍历结果集
  65. for (Object ele : list) {
  66. // 每个集合元素是Student对象
  67. Student s = (Student) ele;
  68. System.out.println(s.getName());
  69. }
  70. }
  71. }

四 数据脚本

  1. drop database if exists hibernate;
  2. create database hibernate;
  3. use hibernate;
  4. CREATE TABLE course_inf (
  5. course_code varchar(255) NOT NULL,
  6. name varchar(255) default NULL,
  7. PRIMARY KEY (course_code)
  8. );
  9. INSERT INTO course_inf VALUES
  10. ('001','疯狂Java讲义'),
  11. ('002','轻量级Java EE企业应用实战'),
  12. ('003','疯狂Android讲义');
  13. CREATE TABLE student_inf (
  14. student_id int NOT NULL,
  15. name varchar(255) NOT NULL,
  16. PRIMARY KEY (student_id)
  17. );
  18. INSERT INTO student_inf VALUES
  19. (20050231,'孙悟空'),
  20. (20050232,'猪八戒'),
  21. (20050233,'牛魔王');
  22. CREATE TABLE enrolment_inf (
  23. enrolment_id int(11) NOT NULL auto_increment,
  24. semester int(11) NOT NULL,
  25. year int(11) NOT NULL,
  26. student_id int default NULL,
  27. course_code varchar(255) default NULL,
  28. PRIMARY KEY (enrolment_id),
  29. KEY FKEB4882C47EDE09EE (course_code),
  30. KEY FKEB4882C4109881D8 (student_id),
  31. FOREIGN KEY (student_id) REFERENCES student_inf (student_id),
  32. FOREIGN KEY (course_code) REFERENCES course_inf (course_code)
  33. );
  34. INSERT INTO enrolment_inf VALUES
  35. (1,3,2005,20050232,'001'),
  36. (2,2,2005,20050232,'003'),
  37. (3,2,2005,20050233,'002'),
  38. (4,3,2005,20050233,'003'),
  39. (5,1,2005,20050231,'002');
  40. -- 创建一个简单的存储过程
  41. create procedure select_all_student()
  42. select *
  43. from student_inf;

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5ncWl1bWluZw_size_16_color_FFFFFF_t_70

五 测试

  1. Hibernate:
  2. select
  3. s.student_id ,
  4. s.name
  5. from
  6. student_inf s
  7. 孙悟空
  8. 猪八戒
  9. 牛魔王
  10. ++++++++++++++++++++++++++++++++++++++++++++++++++++++
  11. Hibernate:
  12. select
  13. s.*,
  14. e.*,
  15. c.*
  16. from
  17. student_inf s,
  18. enrolment_inf e,
  19. course_inf c
  20. where
  21. s.student_id = e.student_id
  22. and e.course_code = c.course_code
  23. and e.year=?
  24. 猪八戒 2005 3 =疯狂Java讲义= 猪八戒
  25. 猪八戒 2005 2 =疯狂Android讲义= 猪八戒
  26. 牛魔王 2005 2 =轻量级Java EE企业应用实战= 牛魔王
  27. 牛魔王 2005 3 =疯狂Android讲义= 牛魔王
  28. 孙悟空 2005 1 =轻量级Java EE企业应用实战= 孙悟空
  29. ++++++++++++++++++++++++++++++++++++++++++++++++++++++
  30. Hibernate:
  31. {call select_all_student()}
  32. 孙悟空
  33. 猪八戒
  34. 牛魔王

发表评论

表情:
评论列表 (有 0 条评论,554人围观)

还没有评论,来说两句吧...

相关阅读

    相关 hibernatesql查询

    hibernate有的时候用起来貌似不是那么顺手,像sql查询在hibernate中就是一大缺陷,稍微复杂点的查询hibernate几乎做不到。这次整理了一些关于hiberna