Hibernate实战——基于复合主键的关联关系

£神魔★判官ぃ 2021-07-25 00:53 526阅读 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.Person"/>
  38. <mapping class="org.crazyit.app.domain.Address"/>
  39. </session-factory>
  40. </hibernate-configuration>

二 PO

Person

  1. package org.crazyit.app.domain;
  2. import java.util.*;
  3. import javax.persistence.*;
  4. @Entity
  5. @Table(name="person_inf")
  6. public class Person
  7. implements java.io.Serializable
  8. {
  9. // 定义first成员变量,作为标识属性的成员
  10. @Id
  11. private String first;
  12. // 定义last成员变量,作为标识属性的成员
  13. @Id
  14. private String last;
  15. private int age;
  16. // 记录该Person实体关联的所有Address实体
  17. @OneToMany(targetEntity=Address.class, mappedBy="person"
  18. , cascade=CascadeType.ALL)
  19. private Set<Address> addresses
  20. = new HashSet<>();
  21. // first的setter和getter方法
  22. public void setFirst(String first)
  23. {
  24. this.first = first;
  25. }
  26. public String getFirst()
  27. {
  28. return this.first;
  29. }
  30. // last的setter和getter方法
  31. public void setLast(String last)
  32. {
  33. this.last = last;
  34. }
  35. public String getLast()
  36. {
  37. return this.last;
  38. }
  39. // age的setter和getter方法
  40. public void setAge(int age)
  41. {
  42. this.age = age;
  43. }
  44. public int getAge()
  45. {
  46. return this.age;
  47. }
  48. // addresses的setter和getter方法
  49. public void setAddresses(Set<Address> addresses)
  50. {
  51. this.addresses = addresses;
  52. }
  53. public Set<Address> getAddresses()
  54. {
  55. return this.addresses;
  56. }
  57. // 重写equals()方法,根据first、last进行判断
  58. public boolean equals(Object obj)
  59. {
  60. if (this == obj)
  61. {
  62. return true;
  63. }
  64. if (obj != null && obj.getClass() == Person.class)
  65. {
  66. Person target = (Person)obj;
  67. return target.getFirst().equals(this.first)
  68. && target.getLast().equals(this.last);
  69. }
  70. return false;
  71. }
  72. // 重写hashCode()方法,根据first、last计算hashCode值
  73. public int hashCode()
  74. {
  75. return getFirst().hashCode() * 31
  76. + getLast().hashCode();
  77. }
  78. }

Address

  1. package org.crazyit.app.domain;
  2. import javax.persistence.*;
  3. @Entity
  4. @Table(name="address_inf")
  5. public class Address
  6. {
  7. // 标识属性
  8. @Id @Column(name="address_id")
  9. @GeneratedValue(strategy=GenerationType.IDENTITY)
  10. private int addressId;
  11. // 定义代表地址详细信息的成员变量
  12. private String addressDetail;
  13. // 记录该Address实体关联的Person实体
  14. @ManyToOne(targetEntity=Person.class)
  15. // 使用@JoinColumns包含多个@JoinColumn定义外键列
  16. @JoinColumns({
  17. // 由于主表使用了复合主键(有多个主键列)
  18. // 因此需要使用多个@JoinColumn定义外键列来参照person_inf表的多个主键列
  19. @JoinColumn(name="person_first"
  20. , referencedColumnName="first" , nullable=false),
  21. @JoinColumn(name="person_last"
  22. , referencedColumnName="last" , nullable=false)
  23. })
  24. private Person person;
  25. // 无参数的构造器
  26. public Address()
  27. {
  28. }
  29. // 初始化全部成员变量的构造器
  30. public Address(String addressDetail)
  31. {
  32. this.addressDetail = addressDetail;
  33. }
  34. // addressId的setter和getter方法
  35. public void setAddressId(int addressId)
  36. {
  37. this.addressId = addressId;
  38. }
  39. public int getAddressId()
  40. {
  41. return this.addressId;
  42. }
  43. // addressDetail的setter和getter方法
  44. public void setAddressDetail(String addressDetail)
  45. {
  46. this.addressDetail = addressDetail;
  47. }
  48. public String getAddressDetail()
  49. {
  50. return this.addressDetail;
  51. }
  52. // person的setter和getter方法
  53. public void setPerson(Person person)
  54. {
  55. this.person = person;
  56. }
  57. public Person getPerson()
  58. {
  59. return this.person;
  60. }
  61. }

三 测试

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.Transaction;
  3. import org.hibernate.Session;
  4. import java.util.*;
  5. import org.crazyit.app.domain.*;
  6. public class PersonManager
  7. {
  8. public static void main(String[] args)
  9. {
  10. PersonManager mgr = new PersonManager();
  11. mgr.createAndStorePerson();
  12. HibernateUtil.sessionFactory.close();
  13. }
  14. private void createAndStorePerson()
  15. {
  16. Session session = HibernateUtil.currentSession();
  17. Transaction tx = session.beginTransaction();
  18. // 创建Person对象
  19. Person person = new Person();
  20. person.setAge(29);
  21. // 为复合主键的两个成员设置值
  22. person.setFirst("crazyit.org");
  23. person.setLast("疯狂Java联盟");
  24. Address a1 = new Address("广州天河");
  25. a1.setPerson(person);
  26. Address a2 = new Address("上海虹口");
  27. a2.setPerson(person);
  28. // 先保存主表实体
  29. session.save(person);
  30. // 再保存从表实体
  31. session.save(a1);
  32. session.save(a2);
  33. tx.commit();
  34. HibernateUtil.closeSession();
  35. }
  36. }

四 测试

  1. Hibernate:
  2. insert
  3. into
  4. person_inf
  5. (age, last, first)
  6. values
  7. (?, ?, ?)
  8. Hibernate:
  9. insert
  10. into
  11. address_inf
  12. (addressDetail, person_last, person_first)
  13. values
  14. (?, ?, ?)
  15. Hibernate:
  16. insert
  17. into
  18. address_inf
  19. (addressDetail, person_last, person_first)
  20. values
  21. (?, ?, ?)

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5ncWl1bWluZw_size_16_color_FFFFFF_t_70

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5ncWl1bWluZw_size_16_color_FFFFFF_t_70 1

发表评论

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

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

相关阅读