各种关联映射的实例

前端之家收集整理的这篇文章主要介绍了各种关联映射的实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

代码

1.Hibernate框架配置文件

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://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5.  
  6. <!-- Generated by MyEclipse Hibernate Tools. -->
  7. <hibernate-configuration>
  8.  
  9. <session-factory>
  10. <property name="show_sql">true</property>
  11. <property name="myeclipse.connection.profile">bookshop</property>
  12. <property name="connection.url">
  13. jdbc:MysqL://localhost:3306/bookshop
  14. </property>
  15. <property name="connection.username">root</property>
  16. <property name="connection.password">1234</property>
  17. <property name="connection.driver_class">
  18. com.MysqL.jdbc.Driver
  19. </property>
  20. <property name="dialect">
  21. org.hibernate.dialect.MysqLDialect
  22. </property>
  23. <mapping resource="com/hibtest2/entity/Users.hbm.xml" />
  24. <mapping resource="com/hibtest2/entity/Books.hbm.xml" />
  25. <mapping resource="com/hibtest2/entity/Publishers.hbm.xml" />
  26. <mapping resource="com/hibtest2/entity/Student.hbm.xml" />
  27. <mapping resource="com/hibtest2/entity/Course.hbm.xml" />
  28.  
  29. </session-factory>
  30.  
  31. </hibernate-configuration>

2.基类

BaseHibernateDAO.java

  1. package com.hibtest2.dao;
  2.  
  3. import java.io.Serializable;
  4. import java.util.List;
  5.  
  6. import org.hibernate.HibernateException;
  7. import org.hibernate.Session;
  8. import org.hibernate.Transaction;
  9. import org.hibernate.criterion.Example;
  10.  
  11. import com.hibtest2.HibernateSessionFactory;
  12. public abstract class BaseHibernateDAO {
  13. /*
  14. * 添加数据
  15. */
  16. protected void add(Object object){
  17. Transaction tran=null;
  18. //获取session
  19. Session session=HibernateSessionFactory.getSession();
  20. try{
  21. //开始事务
  22. tran=session.beginTransaction();
  23. //持久化操作
  24. session.save(object);
  25. //提交事务
  26. tran.commit();
  27. }catch (Exception e) {
  28. if(tran!=null){
  29. //事务回滚
  30. tran.rollback();
  31. }
  32. e.printStackTrace();
  33. }finally{
  34. //关闭session
  35. session.close();
  36. }
  37. }
  38. /*
  39. * 加载数据
  40. */
  41. protected Object get(Class cla,Serializable id){
  42. Object object=null;
  43. Session session=HibernateSessionFactory.getSession();
  44. try {
  45. object=session.get(cla,id);
  46. } catch (HibernateException e) {
  47. // TODO Auto-generated catch block
  48. e.printStackTrace();
  49. }
  50. finally {
  51. session.close();
  52. }
  53. return object;
  54. }
  55. /*
  56. * 删除数据
  57. */
  58. protected void delete(Object object){
  59. Transaction tran=null;
  60. Session session=HibernateSessionFactory.getSession();
  61. try {
  62. tran=session.beginTransaction();
  63. session.delete(object);
  64. tran.commit();
  65. } catch (HibernateException e) {
  66. // TODO Auto-generated catch block
  67. if(tran!=null){
  68. tran.rollback();
  69. }
  70. e.printStackTrace();
  71. }
  72. finally {
  73. session.close();
  74. }
  75. }
  76. /*
  77. * 修改数据
  78. */
  79. protected void update(Object object){
  80. Transaction tran=null;
  81. Session session=HibernateSessionFactory.getSession();
  82. try {
  83. tran=session.beginTransaction();
  84. session.update(object);
  85. tran.commit();
  86. } catch (HibernateException e) {
  87. // TODO Auto-generated catch block
  88. if(tran!=null){
  89. tran.rollback();
  90. }
  91. e.printStackTrace();
  92. }
  93. finally {
  94. session.close();
  95. }
  96. }
  97. /*
  98. * 查询数据
  99. */
  100. protected List search(Class cla,Object condition){
  101. Session session=null;
  102. List list=null;
  103. try {
  104. session=HibernateSessionFactory.getSession();
  105. list=session.createCriteria(cla).add(Example.create(condition)).list();
  106. } catch (Exception e) {
  107. // TODO: handle exception
  108. } finally{
  109. session.close();
  110. }
  111. return list;
  112. }
  113. }

3.实体类

Users.java

  1. package com.hibtest2.entity;
  2. /**
  3. * Users entity. @author MyEclipse Persistence Tools
  4. */
  5. public class Users implements java.io.Serializable {
  6. // Fields
  7. private Integer id;
  8. private String loginName;
  9. private String loginPwd;
  10. // Constructors
  11. /** default constructor */
  12. public Users() {
  13. }
  14. /** full constructor */
  15. public Users(String loginName,String loginPwd) {
  16. this.loginName = loginName;
  17. this.loginPwd = loginPwd;
  18. }
  19. // Property accessors
  20. public Integer getId() {
  21. return this.id;
  22. }
  23. public void setId(Integer id) {
  24. this.id = id;
  25. }
  26. public String getLoginName() {
  27. return this.loginName;
  28. }
  29. public void setLoginName(String loginName) {
  30. this.loginName = loginName;
  31. }
  32. public String getLoginPwd() {
  33. return this.loginPwd;
  34. }
  35. public void setLoginPwd(String loginPwd) {
  36. this.loginPwd = loginPwd;
  37. }
  38. }

Student.java

  1. package com.hibtest2.entity;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. /**
  5. * Student entity. @author MyEclipse Persistence Tools
  6. */
  7. public class Student implements java.io.Serializable {
  8. // Fields
  9. private Integer studentId;
  10. private String studentName;
  11. private Set courses=new HashSet();
  12. // Constructors
  13. public Set getCourses() {
  14. return courses;
  15. }
  16. public void setCourses(Set courses) {
  17. this.courses = courses;
  18. }
  19. /** default constructor */
  20. public Student() {
  21. }
  22. /** full constructor */
  23. public Student(String studentName) {
  24. this.studentName = studentName;
  25. }
  26. // Property accessors
  27. public Integer getStudentId() {
  28. return this.studentId;
  29. }
  30. public void setStudentId(Integer studentId) {
  31. this.studentId = studentId;
  32. }
  33. public String getStudentName() {
  34. return this.studentName;
  35. }
  36. public void setStudentName(String studentName) {
  37. this.studentName = studentName;
  38. }
  39. }

Publishers.java

  1. package com.hibtest2.entity;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. /**
  5. * Publishers entity. @author MyEclipse Persistence Tools
  6. */
  7. public class Publishers implements java.io.Serializable {
  8. // Fields
  9. private Integer id;
  10. private String name;
  11. private Set bks=new HashSet();
  12. // Constructors
  13. public Set getBks() {
  14. return bks;
  15. }
  16. public void setBks(Set bks) {
  17. this.bks = bks;
  18. }
  19. /** default constructor */
  20. public Publishers() {
  21. }
  22. /** full constructor */
  23. public Publishers(String name) {
  24. this.name = name;
  25. }
  26. // Property accessors
  27. public Integer getId() {
  28. return this.id;
  29. }
  30. public void setId(Integer id) {
  31. this.id = id;
  32. }
  33. public String getName() {
  34. return this.name;
  35. }
  36. public void setName(String name) {
  37. this.name = name;
  38. }
  39. }

Course.java

  1. package com.hibtest2.entity;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. /**
  5. * Course entity. @author MyEclipse Persistence Tools
  6. */
  7. public class Course implements java.io.Serializable {
  8. // Fields
  9. private Integer courseId;
  10. private String courseName;
  11. private Set students=new HashSet();
  12. // Constructors
  13. public Set getStudents() {
  14. return students;
  15. }
  16. public void setStudents(Set students) {
  17. this.students = students;
  18. }
  19. /** default constructor */
  20. public Course() {
  21. }
  22. /** full constructor */
  23. public Course(String courseName) {
  24. this.courseName = courseName;
  25. }
  26. // Property accessors
  27. public Integer getCourseId() {
  28. return this.courseId;
  29. }
  30. public void setCourseId(Integer courseId) {
  31. this.courseId = courseId;
  32. }
  33. public String getCourseName() {
  34. return this.courseName;
  35. }
  36. public void setCourseName(String courseName) {
  37. this.courseName = courseName;
  38. }
  39. }

Books.java

  1. package com.hibtest2.entity;
  2. /**
  3. * Books entity. @author MyEclipse Persistence Tools
  4. */
  5. public class Books implements java.io.Serializable {
  6. // Fields
  7. private Integer id;
  8. private String title;
  9. private String author;
  10. //private Integer publisherId;
  11. private Publishers publishers;
  12. public Publishers getPublishers() {
  13. return publishers;
  14. }
  15. public void setPublishers(Publishers publishers) {
  16. this.publishers = publishers;
  17. }
  18. private Integer publisherDate;
  19. private String isbn;
  20. private Integer wordsCount;
  21. private Integer unitPrice;
  22. private String contentDescription;
  23. // Constructors
  24. /** default constructor */
  25. public Books() {
  26. }
  27. /** minimal constructor */
  28. public Books(String title,String author,Integer publisherId) {
  29. this.title = title;
  30. this.author = author;
  31. //this.publisherId = publisherId;
  32. }
  33. /** full constructor */
  34. public Books(String title,Integer publisherId,Integer publisherDate,String isbn,Integer wordsCount,Integer unitPrice,String contentDescription) {
  35. this.title = title;
  36. this.author = author;
  37. //this.publisherId = publisherId;
  38. this.publisherDate = publisherDate;
  39. this.isbn = isbn;
  40. this.wordsCount = wordsCount;
  41. this.unitPrice = unitPrice;
  42. this.contentDescription = contentDescription;
  43. }
  44. // Property accessors
  45. public Integer getId() {
  46. return this.id;
  47. }
  48. public void setId(Integer id) {
  49. this.id = id;
  50. }
  51. public String getTitle() {
  52. return this.title;
  53. }
  54. public void setTitle(String title) {
  55. this.title = title;
  56. }
  57. public String getAuthor() {
  58. return this.author;
  59. }
  60. public void setAuthor(String author) {
  61. this.author = author;
  62. }
  63. /*public Integer getPublisherId() {
  64. return this.publisherId;
  65. }
  66. public void setPublisherId(Integer publisherId) {
  67. this.publisherId = publisherId;
  68. }*/
  69. public Integer getPublisherDate() {
  70. return this.publisherDate;
  71. }
  72. public void setPublisherDate(Integer publisherDate) {
  73. this.publisherDate = publisherDate;
  74. }
  75. public String getIsbn() {
  76. return this.isbn;
  77. }
  78. public void setIsbn(String isbn) {
  79. this.isbn = isbn;
  80. }
  81. public Integer getWordsCount() {
  82. return this.wordsCount;
  83. }
  84. public void setWordsCount(Integer wordsCount) {
  85. this.wordsCount = wordsCount;
  86. }
  87. public Integer getUnitPrice() {
  88. return this.unitPrice;
  89. }
  90. public void setUnitPrice(Integer unitPrice) {
  91. this.unitPrice = unitPrice;
  92. }
  93. public String getContentDescription() {
  94. return this.contentDescription;
  95. }
  96. public void setContentDescription(String contentDescription) {
  97. this.contentDescription = contentDescription;
  98. }
  99. }

4.实体类映射文件

Users.hbm.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  4. <!--
  5. Mapping file autogenerated by MyEclipse Persistence Tools
  6. -->
  7. <hibernate-mapping>
  8. <class name="com.hibtest2.entity.Users" table="users" catalog="bookshop">
  9. <id name="id" type="java.lang.Integer">
  10. <column name="Id" />
  11. <generator class="native"></generator>
  12. </id>
  13. <property name="loginName" type="java.lang.String">
  14. <column name="LoginName" length="50" />
  15. </property>
  16. <property name="loginPwd" type="java.lang.String">
  17. <column name="LoginPwd" length="16" />
  18. </property>
  19. </class>
  20. </hibernate-mapping>

Student.hbm.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  4. <!--
  5. Mapping file autogenerated by MyEclipse Persistence Tools
  6. -->
  7. <hibernate-mapping>
  8. <class name="com.hibtest2.entity.Student" table="student" catalog="bookshop">
  9. <id name="studentId" type="java.lang.Integer">
  10. <column name="StudentId" />
  11. <generator class="native"></generator>
  12. </id>
  13. <property name="studentName" type="java.lang.String">
  14. <column name="StudentName" length="16" />
  15. </property>
  16. <set name="courses" table="sc" lazy="false" inverse="false">
  17. <key column="Sid" not-null="true" />
  18. <many-to-many column="Cid" class="com.hibtest2.entity.Course" />
  19. </set>
  20. </class>
  21. </hibernate-mapping>

Publishers.hbm.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  4. <!--
  5. Mapping file autogenerated by MyEclipse Persistence Tools
  6. -->
  7. <hibernate-mapping>
  8. <class name="com.hibtest2.entity.Publishers" table="publishers" catalog="bookshop">
  9. <id name="id" type="java.lang.Integer">
  10. <column name="Id" />
  11. <generator class="native"></generator>
  12. </id>
  13. <property name="name" type="java.lang.String">
  14. <column name="Name" length="16" not-null="true" />
  15. </property>
  16. <set name="bks" lazy="false" cascade="all" inverse="true">
  17. <key column="PublisherId" not-null="true"/>
  18. <one-to-many class="com.hibtest2.entity.Books"/>
  19. </set>
  20. </class>
  21. </hibernate-mapping>

Course.hbm.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  4. <!--
  5. Mapping file autogenerated by MyEclipse Persistence Tools
  6. -->
  7. <hibernate-mapping>
  8. <class name="com.hibtest2.entity.Course" table="course" catalog="bookshop">
  9. <id name="courseId" type="java.lang.Integer">
  10. <column name="CourseId" />
  11. <generator class="native"></generator>
  12. </id>
  13. <property name="courseName" type="java.lang.String">
  14. <column name="CourseName" length="16" />
  15. </property>
  16. <set name="students" table="sc" lazy="false" inverse="true">
  17. <key column="Cid" not-null="true" />
  18. <many-to-many column="Sid" class="com.hibtest2.entity.Student" />
  19. </set>
  20. </class>
  21. </hibernate-mapping>

Books.hbm.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  4. <!--
  5. Mapping file autogenerated by MyEclipse Persistence Tools
  6. -->
  7. <hibernate-mapping>
  8. <class name="com.hibtest2.entity.Books" table="books" catalog="bookshop">
  9. <id name="id" type="java.lang.Integer">
  10. <column name="Id" />
  11. <generator class="native"></generator>
  12. </id>
  13. <property name="title" type="java.lang.String">
  14. <column name="Title" length="16" not-null="true" />
  15. </property>
  16. <property name="author" type="java.lang.String">
  17. <column name="Author" length="16" not-null="true" />
  18. </property>
  19. <!--
  20. <property name="publisherId" type="java.lang.Integer">
  21. <column name="PublisherId" not-null="true" />
  22. </property>
  23. -->
  24. <many-to-one name="publishers" column="PublisherId" class="com.hibtest2.entity.Publishers" insert="true" update="true" lazy="false"/>
  25. <property name="publisherDate" type="java.lang.Integer">
  26. <column name="PublisherDate" />
  27. </property>
  28. <property name="isbn" type="java.lang.String">
  29. <column name="ISBN" length="16" />
  30. </property>
  31. <property name="wordsCount" type="java.lang.Integer">
  32. <column name="WordsCount" />
  33. </property>
  34. <property name="unitPrice" type="java.lang.Integer">
  35. <column name="UnitPrice" precision="8" scale="0" />
  36. </property>
  37. <property name="contentDescription" type="java.lang.String">
  38. <column name="ContentDescription" length="16" />
  39. </property>
  40. </class>
  41. </hibernate-mapping>

5.各种关联映射示例

5.1多对一映射示例

  1. package com.hibtest2;
  2.  
  3. import com.hibtest2.dao.BaseHibernateDAO;
  4. import com.hibtest2.entity.Books;
  5.  
  6. public class TestManyToOne extends BaseHibernateDAO {
  7.  
  8. /**
  9. * @param args
  10. */
  11. public static void main(String[] args) {
  12. TestManyToOne mto=new TestManyToOne();
  13. mto.testManyToOne();
  14. }
  15. public void testManyToOne(){
  16. //根据id获取Books对象
  17. Books books=(Books) super.get(Books.class,new Integer(4947));
  18. //根据多对一映射,从Books对象中获取指定图书的出版社
  19. System.out.println("编号是4947的图书出版社是:"+books.getPublishers().getName().toString());
  20. }
  21.  
  22.  
  23. }

5.2一对多映射示例
  1. package com.hibtest2;
  2.  
  3. import java.util.Iterator;
  4.  
  5. import com.hibtest2.dao.BaseHibernateDAO;
  6. import com.hibtest2.entity.Books;
  7. import com.hibtest2.entity.Publishers;
  8.  
  9. public class TestOneToMany extends BaseHibernateDAO {
  10.  
  11. /**
  12. * @param args
  13. */
  14. public static void main(String[] args) {
  15. TestOneToMany otm=new TestOneToMany();
  16. otm.testOneToMany();
  17. }
  18. public void testOneToMany(){
  19. //根据id获取Publishers对象
  20. Publishers publishers=(Publishers) super.get(Publishers.class,new Integer(1));
  21. System.out.println(publishers.getName()+"出版社出版的图书包括:");
  22. //根据一对多映射,从Publishers对象中获取出版图书名称
  23. Iterator iter=publishers.getBks().iterator();
  24. while(iter.hasNext()){
  25. Books books=(Books)iter.next();
  26. System.out.println(books.getTitle());
  27. }
  28. }
  29.  
  30.  
  31. }

5.3多对多映射示例
  1. package com.hibtest2;
  2.  
  3. import java.util.Iterator;
  4.  
  5. import com.hibtest2.dao.BaseHibernateDAO;
  6. import com.hibtest2.entity.Course;
  7. import com.hibtest2.entity.Student;
  8.  
  9. public class TestManyToMany extends BaseHibernateDAO {
  10.  
  11. /**
  12. * @param args
  13. */
  14. public static void main(String[] args) {
  15. // TODO Auto-generated method stub
  16. TestManyToMany m2m=new TestManyToMany();
  17. //m2m.testAdd_1();
  18. //m2m.testAdd_2();
  19. //m2m.testAdd_3();
  20. //m2m.testDelete_1();
  21. m2m.testDelete_2();
  22. }
  23. public void testAdd_1(){
  24. //创建两个Student对象
  25. Student s1=new Student();
  26. s1.setStudentName("韦小宝");
  27. Student s2=new Student();
  28. s2.setStudentName("令狐冲");
  29. //创建四个Course对象
  30. Course c1=new Course();
  31. c1.setCourseName("数据结构");
  32. Course c2=new Course();
  33. c2.setCourseName("操作系统");
  34. Course c3=new Course();
  35. c3.setCourseName("计算机组成原理");
  36. Course c4=new Course();
  37. c4.setCourseName("离散数学");
  38. //设定s1与c1和c2之间的相互关联
  39. s1.getCourses().add(c1);
  40. s1.getCourses().add(c2);
  41. /*c1.getStudents().add(s1);
  42. c2.getStudents().add(s1);*/
  43. //设定s2与c1、c3和c4之间的相互关联
  44. s2.getCourses().add(c1);
  45. s2.getCourses().add(c3);
  46. s2.getCourses().add(c4);
  47. /*c1.getStudents().add(s2);
  48. c3.getStudents().add(s2);
  49. c4.getStudents().add(s2);*/
  50. //保存c1、c2、c3和c4
  51. super.add(c1);
  52. super.add(c2);
  53. super.add(c3);
  54. super.add(c4);
  55. //保存s1和s2对象
  56. super.add(s1);
  57. super.add(s2);
  58. }
  59. public void testAdd_2(){
  60. //创建"东方不败"对象
  61. Student newStu=new Student();
  62. newStu.setStudentName("东方不败");
  63. //加载"计算机组成原理"对象
  64. Course c=(Course)super.get(Course.class,new Integer(3));
  65. //设置newStu和c对象之间的关联
  66. newStu.getCourses().add(c);
  67. //保存对象newStu
  68. super.add(newStu);
  69. //更新对象c
  70. super.update(c);
  71. }
  72. public void testAdd_3(){
  73. //加载"韦小宝"和"东方不败"对象
  74. Student wxb=(Student)super.get(Student.class,new Integer(1));
  75. Student dfbb=(Student)super.get(Student.class,new Integer(3));
  76. //创建"编译原理"课程对象
  77. Course byyl=new Course();
  78. byyl.setCourseName("编译原理");
  79. //设定wxb、dfbb与byyl对象之间的关联
  80. wxb.getCourses().add(byyl);
  81. dfbb.getCourses().add(byyl);
  82. //保存byyl对象
  83. super.add(byyl);
  84. //更新wxb和dfbb对象
  85. super.update(wxb);
  86. super.update(dfbb);
  87. }
  88. public void testDelete_1(){
  89. //加载"韦小宝"对象,并获得其选课集合
  90. Student student=(Student)super.get(Student.class,new Integer(1));
  91. Iterator courses=student.getCourses().iterator();
  92. //删除中介表sc中与"韦小宝"关联的记录
  93. while(courses.hasNext()){
  94. Course course=(Course)courses.next();
  95. course.getStudents().remove(student);
  96. }
  97. //将"韦小宝"对象删除
  98. super.delete(student);
  99. }
  100. public void testDelete_2(){
  101. //加载"令狐冲"对象
  102. Student student=(Student)super.get(Student.class,new Integer(2));
  103. //将"令狐冲"对象删除
  104. super.delete(student);
  105.  
  106. }
  107. }

5.4双向关联映射示例
  1. package com.hibtest2;
  2.  
  3. import com.hibtest2.dao.BaseHibernateDAO;
  4. import com.hibtest2.entity.Books;
  5. import com.hibtest2.entity.Publishers;
  6.  
  7. public class TestM2OAndO2M extends BaseHibernateDAO {
  8.  
  9. /**
  10. * 双向关联映射
  11. */
  12. public static void main(String[] args) {
  13. TestM2OAndO2M m2o_o2m=new TestM2OAndO2M();
  14. //m2o_o2m.testAdd_1();
  15. //m2o_o2m.testAdd_2();
  16. //m2o_o2m.testAdd_3();
  17. //m2o_o2m.testAdd_4();
  18. //m2o_o2m.testDelete_1();
  19. //m2o_o2m.testDelete_2();
  20. m2o_o2m.testUpdate();
  21. }
  22. public void testAdd_1(){
  23. //添加出版社信息
  24. Publishers publishers=new Publishers();
  25. publishers.setName("电子工业出版社");
  26. super.add(publishers);
  27. }
  28. public void testAdd_2(){
  29. //加载得到电子工业出版社实体对象
  30. Publishers dzgy=(Publishers)super.get(Publishers.class,new Integer(4));
  31. //新建图书对象
  32. Books book1=new Books();
  33. book1.setTitle("单元测试之道C#版");
  34. book1.setAuthor("(美)托马斯等");
  35. //将电子工业出版社对象设置到实体对象Books的publishers属性
  36. book1.setPublishers(dzgy);
  37. //将图书对象保存到数据库
  38. super.add(book1);
  39. //新建图书对象
  40. Books book2=new Books();
  41. book2.setTitle("C++网络编程,卷1");
  42. book2.setAuthor("(美)施密特");
  43. //将电子工业出版社对象设置到实体对象Books的publishers属性
  44. book2.setPublishers(dzgy);
  45. //将图书对象保存到数据库
  46. super.add(book2);
  47. }
  48.  
  49. public void testAdd_3(){
  50. //创建水利水电出版社对象
  51. Publishers publishers=new Publishers();
  52. publishers.setName("水利水电出版社");
  53. //创建第一个Books对象
  54. Books book1=new Books();
  55. book1.setTitle("二级C语言程序设计");
  56. book1.setAuthor("侯东昌,宋智玲等");
  57. //创建第二个Book对象
  58. Books book2=new Books();
  59. book2.setTitle("Visual Basic.NET");
  60. book2.setAuthor("徐振明主编");
  61. //建立Publishers对象和Books对象的一对多双向关联关系,
  62. //只需从Publishers一方进行维护即可
  63. publishers.getBks().add(book1);
  64. publishers.getBks().add(book2);
  65. //保存Publishers对象
  66. super.add(publishers);
  67. }
  68. public void testAdd_4(){
  69. //创建一个Publishers对象
  70. Publishers publishers=new Publishers();
  71. publishers.setName("西安电子科技大学出版社");
  72. //创建两个Books对象
  73. Books book1=new Books();
  74. book1.setTitle("Windows CE应用程序设计");
  75. book1.setAuthor("张勇,许波编著");
  76. Books book2=new Books();
  77. book2.setTitle("MATLAB及其在...");
  78. book2.setAuthor("陈怀琛 编著");
  79. //由于将关联关系交给Books来维护,所以在存储时必须明确地
  80. //将Publishers设定给Books,即Books必须调用setPublishers()方法
  81. book1.setPublishers(publishers);
  82. book2.setPublishers(publishers);
  83. //建立Publishers对象和Books对象的一对多双向关联关系,并保存Publishers对象
  84. publishers.getBks().add(book1);
  85. publishers.getBks().add(book2);
  86. super.add(publishers);
  87. }
  88. public void testDelete_1(){
  89. //加载待删除的Books对象
  90. Books book=(Books)super.get(Books.class,new Integer(4939));
  91. //调用父类的delete方法删除对象
  92. super.delete(book);
  93. }
  94. public void testDelete_2(){
  95. //加载水利水电出版社对象
  96. Publishers publisher=(Publishers)super.get(Publishers.class,new Integer(5));
  97. super.delete(publisher);
  98. }
  99. public void testUpdate(){
  100. //加载"Windows CE应用程序设计"图书实体对象
  101. Books web_yykf=(Books)super.get(Books.class,new Integer(4958));
  102. //加载"西安电子科技大学出版社"和"机械工业出版社"两个出版社实体对象
  103. Publishers xadz=(Publishers)super.get(Publishers.class,new Integer(6));
  104. Publishers jxgy=(Publishers)super.get(Publishers.class,new Integer(3));
  105. //从"西安电子科技大学出版社"对象的 bks属性删除图书"Windows CE应用程序设计",
  106. //并添加到"机械工业出版社"的bks属性中,同时将"机械工业出版社"设置到该图书对象中
  107. xadz.getBks().remove(web_yykf);
  108. jxgy.getBks().add(web_yykf);
  109. web_yykf.setPublishers(jxgy);
  110. //更新"Windows CE应用程序设计"图书对象
  111. super.update(web_yykf);
  112. }
  113.  
  114.  
  115. }

5.5HQL查询示例
  1. package com.hibtest2;
  2.  
  3. import java.util.Iterator;
  4. import java.util.List;
  5.  
  6. import org.hibernate.Query;
  7. import org.hibernate.Session;
  8.  
  9. import com.hibtest2.entity.Books;
  10.  
  11. public class TestHQL {
  12.  
  13. /**
  14. * HQL查询
  15. */
  16. public static void main(String[] args) {
  17. TestHQL tHql=new TestHQL();
  18. //tHql.testHql_1();
  19. //tHql.testHql_2();
  20. //tHql.testHql_3();
  21. //tHql.testHql_4();
  22. //tHql.testHql_5();
  23. //tHql.testHql_6();
  24. //tHql.pagedSearch(2,3);
  25. tHql.testHql_7();
  26. }
  27. public void testHql_1(){
  28. //获取session
  29. Session session=HibernateSessionFactory.getSession();
  30. //编写HQL语句
  31. String hql="from Books";
  32. //创建Query对象
  33. Query query=session.createQuery(hql);
  34. //执行查询,获得结果
  35. List list=query.list();
  36. //遍历查找结果
  37. Iterator itor=list.iterator();
  38. while(itor.hasNext()){
  39. Books book=(Books)itor.next();
  40. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  41. }
  42. }
  43. /**
  44. * 属性查询
  45. */
  46. public void testHql_2(){
  47. Session session=HibernateSessionFactory.getSession();
  48. //编写HQL语句,使用属性查询
  49. String hql="select books.title,books.author from Books as books";
  50. Query query=session.createQuery(hql);
  51. List list=query.list();
  52. Iterator itor=list.iterator();
  53. //每天记录封装成一个Object数组
  54. while(itor.hasNext()){
  55. Object[] object=(Object[])itor.next();
  56. System.out.println(object[0]+" "+object[1]);
  57. }
  58. }
  59. /**
  60. * 参数查询,按参数位置查询
  61. */
  62. public void testHql_3(){
  63. Session session=HibernateSessionFactory.getSession();
  64. //编写HQL语句,使用参数查询
  65. String hql="from Books books where books.title like ? ";
  66. Query query=session.createQuery(hql);
  67. //给HQL语句中“?”代表的参数设置值
  68. query.setString(0,"%C++%");
  69. List list=query.list();
  70. Iterator itor=list.iterator();
  71. while(itor.hasNext()){
  72. Books book=(Books)itor.next();
  73. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  74. }
  75. }
  76.  
  77. /**
  78. * 参数查询,按参数名字查询
  79. */
  80. public void testHql_4(){
  81. Session session=HibernateSessionFactory.getSession();
  82. //通过":bookTitle"定义命名参数"bookTitle"
  83. String hql="from Books books where books.title=:bookTitle";
  84. Query query=session.createQuery(hql);
  85. //给命名参数设置值
  86. query.setString("bookTitle","C++ Primer中文版");
  87. List list=query.list();
  88. Iterator itor=list.iterator();
  89. while(itor.hasNext()){
  90. Books book=(Books)itor.next();
  91. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  92. }
  93. }
  94. /**
  95. * 连接查询
  96. */
  97. public void testHql_5(){
  98. Session session=HibernateSessionFactory.getSession();
  99. //编写HQL语句,使用连接查询
  100. String hql="select b from Books b,Publishers p where b.publishers=p and p.name='清华大学出版社'";
  101. Query query=session.createQuery(hql);
  102. List list=query.list();
  103. Iterator itor=list.iterator();
  104. while(itor.hasNext()){
  105. Books book=(Books)itor.next();
  106. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  107. }
  108. }
  109. /**
  110. * 分页查询
  111. */
  112. public void testHql_6(){
  113. Session session=HibernateSessionFactory.getSession();
  114. //按书名升序查询图书对象
  115. String hql="from Books b order by b.title asc";
  116. Query query=session.createQuery(hql);
  117. //从第一个对象开始查询
  118. query.setFirstResult(0);
  119. //从查询结果中一次返回3个对象
  120. query.setMaxResults(3);
  121. //执行查询
  122. List list=query.list();
  123. //遍历查询结果
  124. Iterator itor=list.iterator();
  125. while(itor.hasNext()){
  126. Books book=(Books)itor.next();
  127. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  128. }
  129. }
  130. public void pagedSearch(int pageIndex,int pageSize){
  131. Session session=HibernateSessionFactory.getSession();
  132. String hql="from Books b order by b.title asc";
  133. Query query=session.createQuery(hql);
  134. int startIndex=(pageIndex-1)*pageSize;
  135. query.setFirstResult(startIndex);
  136. query.setMaxResults(pageSize);
  137. List list=query.list();
  138. Iterator itor=list.iterator();
  139. while(itor.hasNext()){
  140. Books book=(Books)itor.next();
  141. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  142. }
  143. }
  144. /**
  145. * 聚集函数
  146. */
  147. public void testHql_7(){
  148. Session session=HibernateSessionFactory.getSession();
  149. //统计记录总数
  150. String hql1="select count(b) from Books b";
  151. Query query1=session.createQuery(hql1);
  152. Long count=(Long)query1.uniqueResult();
  153. //统计书的平均金额
  154. String hql2="select avg(b.unitPrice) from Books b";
  155. Query query2=session.createQuery(hql2);
  156. Double money=(Double)query2.uniqueResult();
  157. //统计最贵和最便宜的图书
  158. String hql3="select min(b.unitPrice),max(b.unitPrice) from Books b";
  159. Query query3=session.createQuery(hql3);
  160. Object[] price=(Object[])query3.uniqueResult();
  161. System.out.println("记录总数"+count.toString()+" 平均金额"+
  162. money.toString()+" 书价最低为"+price[0].toString()+
  163. " 书价最高为"+price[1].toString());
  164. }
  165.  
  166.  
  167.  
  168. }

5.6Criteria查询示例
  1. package com.hibtest2;
  2.  
  3. import java.util.*;
  4. import org.hibernate.*;
  5. import org.hibernate.criterion.*;
  6. import com.hibtest2.entity.Books;
  7.  
  8. public class TestCriteria {
  9.  
  10. /**
  11. * Criteria查询
  12. */
  13. public static void main(String[] args) {
  14. TestCriteria tc=new TestCriteria();
  15. //使用对象封装查询条件
  16. /*Books books=new Books();
  17. books.setTitle("Web应用");
  18. tc.testCriteria_1(books);*/
  19. //tc.testCriteria_2();
  20. //tc.testCriteria_2_1();
  21. //tc.testCriteria_3();
  22. //tc.testCriteria_4();
  23. tc.testDetachedCriteria();
  24.  
  25. }
  26. /**
  27. * 使用Criteria对象进行简单查询
  28. * @param condition
  29. */
  30. public void testCriteria_1(Books condition){
  31. //获得session
  32. Session session=HibernateSessionFactory.getSession();
  33. //创建Criteria对象
  34. Criteria criteria=session.createCriteria(Books.class);
  35. //使用Restrictions对象编写查询条件,并将查询条件加入Criteria对象
  36. if(condition!=null){
  37. if(condition.getTitle()!=null && !condition.getTitle().equals("")){
  38. //按书名进行筛选
  39. criteria.add(Restrictions.like("title",condition.getTitle(),MatchMode.ANYWHERE));
  40. }
  41. if(condition.getAuthor()!=null && !condition.getAuthor().equals("")){
  42. //按作者进行筛选
  43. criteria.add(Restrictions.like("author",condition.getAuthor(),MatchMode.ANYWHERE));
  44. }
  45. }
  46. //排序
  47. criteria.addOrder(Order.asc("id"));
  48. //执行查询,获得结果
  49. List list=criteria.list();
  50. //遍历查询结果
  51. Iterator itor=list.iterator();
  52. while(itor.hasNext()){
  53. Books book=(Books)itor.next();
  54. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  55. }
  56. }
  57. /**
  58. * 使用Criterion 并通过 Restrictions 工具类,实现关联查询
  59. */
  60. public void testCriteria_2(){
  61. Session session=HibernateSessionFactory.getSession();
  62. Criteria bookCriteria=session.createCriteria(Books.class);
  63. //设置从Books类中查询的条件
  64. bookCriteria.add(Restrictions.like("title","C++",MatchMode.ANYWHERE));
  65. //创建一个新的Criteria实例,以引用pulishers集合中的元素
  66. Criteria publishersCriteria=bookCriteria.createCriteria("publishers");
  67. //设置从关联的Publishers类中查询的条件
  68. publishersCriteria.add(Restrictions.like("name","清华大学出版社"));
  69. List list=publishersCriteria.list();
  70. Iterator itor=list.iterator();
  71. while(itor.hasNext()){
  72. Books book=(Books)itor.next();
  73. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  74. }
  75. }
  76. /**
  77. * 采用方法链编程风格,使用Criteria对象进行查询
  78. */
  79. public void testCriteria_2_1(){
  80. Session session=HibernateSessionFactory.getSession();
  81. List list=session.createCriteria(Books.class)
  82. .add(Restrictions.like("title",MatchMode.ANYWHERE))
  83. .createCriteria("publishers")
  84. .add(Restrictions.like("name","清华大学出版社")).list();
  85. Iterator itor=list.iterator();
  86. while(itor.hasNext()){
  87. Books book=(Books)itor.next();
  88. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  89. }
  90. }
  91. /**
  92. * 使用Criterion 并通过 Restrictions 工具类,实现分页查询
  93. */
  94. public void testCriteria_3(){
  95. Session session=HibernateSessionFactory.getSession();
  96. Criteria criteria=session.createCriteria(Books.class);
  97. //从第一个对象开始查询
  98. criteria.setFirstResult(0);
  99. //每次从查询结果中返回4个对象
  100. criteria.setMaxResults(4);
  101. List list=criteria.list();
  102. Iterator itor=list.iterator();
  103. while(itor.hasNext()){
  104. Books book=(Books)itor.next();
  105. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  106. }
  107. }
  108. /**
  109. * 使用Expression类实现查询
  110. */
  111. public void testCriteria_4(){
  112. Session session=HibernateSessionFactory.getSession();
  113. List list=session.createCriteria(Books.class)
  114. //使用Expression类编写查询条件
  115. .add(Expression.like("title",MatchMode.ANYWHERE))
  116. //对查询结果进行排序
  117. .addOrder(Order.asc("id")).list();
  118. Iterator itor=list.iterator();
  119. while(itor.hasNext()){
  120. Books book=(Books)itor.next();
  121. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  122. }
  123. }
  124. /**
  125. * 使用DetachedCriteria查询
  126. */
  127. public void testDetachedCriteria(){
  128. //创建离线查询DetachedCriteria实例
  129. DetachedCriteria query=DetachedCriteria.forClass(Books.class)
  130. .add(Property.forName("title").eq("Web应用开发技术"));
  131. //创建Hibernate Session
  132. Session session=HibernateSessionFactory.getSession();
  133. //执行查询
  134. List list=query.getExecutableCriteria(session).list();
  135. Iterator itor=list.iterator();
  136. while(itor.hasNext()){
  137. Books book=(Books)itor.next();
  138. System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
  139. }
  140. }
  141.  
  142. }
总结:通过练习,基本了解Hibernate框架的运行原理,熟练掌握Hibernate框架的基本数据库操作。

猜你在找的XML相关文章