【问题标题】:How do I create a composite primary key in hibernate within the hbm.xml file如何在 hbm.xml 文件中的 hibernate 中创建复合主键
【发布时间】:2015-02-22 21:05:23
【问题描述】:

我有以下三个简单的类。 如何在我的 Rating.hbm.xml 文件中映射 Rating 类,更具体地说是它的复合键? 我目前在休眠文档中迷失了(5.1.2.1.复合标识符)

每个评级可以有一本书和一个用户进行特定评级。 每个用户可以进行许多评级。 每本书可以有多个评分。

评级等级

    public class Rating {
        private User user;
        private Book book;
        private int rating;
        private Date timestamp;

        public Rating() {}  //No arg contructor for hibernate
    ... 
}

用户类

public class User {
    private long userId;
    private String email, password;
    public User() {}
    ...
}

图书课

public class Book {
    private long bookId;
    private String title;

    public Book() {}
    ...
}

【问题讨论】:

    标签: java mysql hibernate orm composite-primary-key


    【解决方案1】:

    首先你应该像这样创建一个复合主键类:

    public class RatingId implements Serializable{
    private User user;
    private Book book;
    private int rating;
    // an easy initializing constructor
    public PurchasedTestId(User user, Book book, int rating){
    this.user = user;
    this.book = book;
    this.rating= rating;
    }
    
    /*create your getter and setters plus override the equals and hashCode()  methods */ 
    
    
    }
    

    现在像这样创建您的主要评级类:

    public class RatingBook {
    RatingId RatingId;
    private Date timestamp;
    
    /* generate getters and setters for these two methods*/
    
    }
    

    您可以尝试以下方法:

    <composite-id name=”ratingId”>
    <key-property name="user" column="user"  />
    <key-property name="book" column="book" />
    <key-property name="rating" column="pid" />
    </composite-id>
    

    看看是否适合你

    【讨论】:

    • 谢谢,我现在就试试。评级在 RatingId 类中而不是在 RatingBook 类中是否有任何原因?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 2011-04-24
    • 2019-03-08
    • 2015-05-25
    相关资源
    最近更新 更多