Java开发之路

文章32 |   阅读 14707 |   点赞0

来源:https://blog.csdn.net/sunnyyoona

[Hibernate开发之路](5)联合主键

x33g5p2x  于2021-03-13 发布在 其他  
字(6.3k)|赞(0)|评价(0)|浏览(409)

现在大家都不推荐使用联合主键,关键是因为其需要自己手工维护,比较麻烦。但是一个项目可能因为历史遗留原因,你不得不面对联合主键。 

Hibernate联合主键问题解决如下:

可以使用一个组件作为一个实体类的标识符。你的组件类必须满足以下要求: 

(1)它必须实现 java.io.Serializable 接口 

(2)它必须重新实现 equals() 和 hashCode() 方法,始终和组合关键字在数据库中的概念保持一致 

注意:在 Hibernate3 中,第二个要求并非是 Hibernate 强制必须的。但最好这样做。 

不能使用一个 IdentifierGenerator 产生组合关键字。一个应用程序必须分配它自己的标识符。

将主键所对应属性提取出一个类(称之为主键类),并且主键类需要实现Serializable接口,重写equals方法与hashCode方法,原因:

在于Hibernate要根据数据库的联合主键来判断某两行记录是否是一样,如果一样那么就认为是同一个对象,如果不一样,那么就认为是不同的对象。

一 .XML配置方式

具体做法如下步骤:

(1)将主键所对应属性提取出一个类(称之为主键类),并且主键类需要实现Serializable接口,重写equals方法与hashCode方法 

实例如下:

  1. package com.model;
  2. import java.io.Serializable;
  3. //ScoreInfo主键类
  4. //composite-id class must implement Serializable: com.model.ScorePK
  5. public class ScorePK implements Serializable{
  6. private static final long serialVersionUID = 1L;
  7. private Integer studentID;
  8. private Integer courseID;
  9. public int getStudentID() {
  10. return studentID;
  11. }
  12. public void setStudentID(int studentID) {
  13. this.studentID = studentID;
  14. }
  15. public int getCourseID() {
  16. return courseID;
  17. }
  18. public void setCourseID(int courseID) {
  19. this.courseID = courseID;
  20. }
  21. @Override
  22. public boolean equals(Object o){
  23. if(o instanceof ScorePK){
  24. ScorePK scorePK = (ScorePK)o;
  25. if(this.studentID == scorePK.studentID && this.courseID == scorePK.courseID){
  26. return true;
  27. }
  28. }
  29. return false;
  30. }
  31. @Override
  32. public int hashCode(){
  33. int result = 1;
  34. result = result + ((this.studentID == null) ? 0 : this.studentID.hashCode());
  35. result = result + ((this.courseID == null) ? 0 : this.courseID.hashCode());
  36. return result;
  37. }
  38. }

这里要特别注意,如hibernate API文档所述,主键类必须实现java.io.Serializable接口,而且重写equals和hashCode方法,保证主键的唯一性.

(2)实体类(这里不用包含主键所对应的属性)

  1. package com.model;
  2. public class ScoreInfo {
  3. //联合主键
  4. private ScorePK scorePK;
  5. private int score;
  6. public ScorePK getScorePK() {
  7. return scorePK;
  8. }
  9. public void setScorePK(ScorePK scorePK) {
  10. this.scorePK = scorePK;
  11. }
  12. public int getScore() {
  13. return score;
  14. }
  15. public void setScore(int score) {
  16. this.score = score;
  17. }
  18. }

(3)配置Hibernate配置文件ScoreInfo.hbm.xml,实例如下:

  1. <?xml version="1.0"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <class name="com.model.ScoreInfo" table="ScoreInfo">
  7. <composite-id name = "ScorePK" class = "com.model.ScorePK">
  8. <key-property name="StudentID"></key-property>
  9. <key-property name="CourseID"></key-property>
  10. </composite-id>
  11. <property name="score" column = "Score"/>
  12. </class>
  13. </hibernate-mapping>

如果表使用联合主键,你可以映射类的多个属性为标识符属性。 <composite-id>元素接受<key-property> 属性映射和<key-many-to-one>属性映射作为子元素。

  1. <composite-id name = "ScorePK" class = "com.model.ScorePK">
  2. <key-property name="StudentID"></key-property>
  3. <key-property name="CourseID"></key-property>
  4. </composite-id>

这个联合主键就是由StudentID和CourseID构成。

(4)不要忘记在hibernate配置文件中引用映射文件。

  1. <!-- XML配置方式 -->
  2. <mapping resource="com/model/ScoreInfo.hbm.xml"/>

(5)测试

  1. package com.test;
  2. import org.hibernate.Session;
  3. import com.model.ScoreInfo;
  4. import com.model.ScorePK;
  5. import com.util.HibernateUtil;
  6. public class Test {
  7. public static void main(String[] args) {
  8. Test mgr = new Test();
  9. mgr.createAndStoreEvent();
  10. HibernateUtil.getSessionFactory().close();
  11. }
  12. private void createAndStoreEvent() {
  13. Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  14. session.beginTransaction();
  15. ScorePK scorePK = new ScorePK();
  16. scorePK.setStudentID(2);
  17. scorePK.setCourseID(1);
  18. ScoreInfo score = new ScoreInfo();
  19. score.setScorePK(scorePK);
  20. score.setScore(98);
  21. session.save(score);
  22. session.getTransaction().commit();
  23. }
  24. }

辅助类:HibernateUtil

  1. package com.util;
  2. import org.hibernate.SessionFactory;
  3. import org.hibernate.cfg.Configuration;
  4. public class HibernateUtil {
  5. private static final SessionFactory sessionFactory;
  6. static
  7. {
  8. try
  9. {
  10. // Create the SessionFactory from hibernate.cfg.xml
  11. sessionFactory = new Configuration().configure().buildSessionFactory();
  12. }
  13. catch (Throwable ex)
  14. {
  15. // Make sure you log the exception, as it might be swallowed
  16. System.err.println("Initial SessionFactory creation failed." + ex);
  17. throw new ExceptionInInitializerError(ex);
  18. }
  19. }
  20. public static SessionFactory getSessionFactory() {
  21. return sessionFactory;
  22. }
  23. }

二 .Annotation注解方式

下面是定义联合主键的几种方式:

(1)将组件类(主键类)注解为@Embeddable,并在实体类中将组件的属性注解为@Id

(2)在实体类中将组件的属性注解为@EmbeddedId

(3)将实体类注解为@IdClass(value = ScorePk.class),并将该实体中所有属于主键的属性都注解为@Id

对于EJB2的开发人员来说@IdClass是很常见的,但是对于Hibernate用户来说就是一个崭新的用法。

组合主键类对应一个实体类的多个字段或属性,而且主键类中定义主键的字段或属性和实体类中对应的字段或属性早类型上必须一致。

实例如下:

(1)将组件类(主键类)注解为@Embeddable

  1. package com.model;
  2. import java.io.Serializable;
  3. import javax.persistence.Embeddable;
  4. //ScoreInfo主键类
  5. //composite-id class must implement Serializable: com.model.ScorePK
  6. @Embeddable
  7. public class ScorePK implements Serializable{
  8. private static final long serialVersionUID = 1L;
  9. private Integer studentID;
  10. private Integer courseID;
  11. public int getStudentID() {
  12. return studentID;
  13. }
  14. public void setStudentID(int studentID) {
  15. this.studentID = studentID;
  16. }
  17. public int getCourseID() {
  18. return courseID;
  19. }
  20. public void setCourseID(int courseID) {
  21. this.courseID = courseID;
  22. }
  23. @Override
  24. public boolean equals(Object o){
  25. if(o instanceof ScorePK){
  26. ScorePK scorePK = (ScorePK)o;
  27. if(this.studentID == scorePK.studentID && this.courseID == scorePK.courseID){
  28. return true;
  29. }
  30. }
  31. return false;
  32. }
  33. @Override
  34. public int hashCode(){
  35. int result = 1;
  36. result = result + ((this.studentID == null) ? 0 : this.studentID.hashCode());
  37. result = result + ((this.courseID == null) ? 0 : this.courseID.hashCode());
  38. return result;
  39. }
  40. }

将在实体类中组件的属性注解为@Id

  1. public class ScoreInfo {
  2. private int studentID;
  3. private ScorePK scorePK;
  4. @Id
  5. public ScorePK getScorePK() {
  6. return scorePK;
  7. }
  8. public void setScorePK(ScorePK scorePK) {
  9. this.scorePK = scorePK;
  10. }
  11. public int getScore() {
  12. return score;
  13. }
  14. public void setScore(int score) {
  15. this.score = score;
  16. }
  17. }

(2)在实体类中将组件的属性注解为@EmbeddedId

  1. public class ScoreInfo {
  2. private int studentID;
  3. private ScorePK scorePK;
  4. @EmbeddedId
  5. public ScorePK getScorePK() {
  6. return scorePK;
  7. }
  8. public void setScorePK(ScorePK scorePK) {
  9. this.scorePK = scorePK;
  10. }
  11. public int getScore() {
  12. return score;
  13. }
  14. public void setScore(int score) {
  15. this.score = score;
  16. }
  17. }

(3)将实体类注解为@IdClass(value = ScorePk.class),并将该实体中所有属于主键的属性都注解为@Id

  1. @Entity
  2. @IdClass(value = ScorePk.class)
  3. public class ScoreInfo {
  4. private int studentID;
  5. private int courseID;
  6. private int score;
  7. @Id
  8. public int getStudentID() {
  9. return studentID;
  10. }
  11. public void setStudentID(int studentID) {
  12. this.studentID = studentID;
  13. }
  14. @Id
  15. public int getCourseID() {
  16. return courseID;
  17. }
  18. public void setCourseID(int courseID) {
  19. this.courseID = courseID;
  20. }
  21. public int getScore() {
  22. return score;
  23. }
  24. public void setScore(int score) {
  25. this.score = score;
  26. }
  27. }

相关文章