如何在hbm.xml文件中的hibernate中创建复合主键 [英] How do I create a composite primary key in hibernate within the hbm.xml file

查看:234
本文介绍了如何在hbm.xml文件中的hibernate中创建复合主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下三个简单的类。
我如何着手在Rating.hbm.xml文件中映射Rating类和更具体的组合键?
我目前在hibernate文档中很遗憾(5.1.2.1。复合标识符)

每个评分可以有一本书和一个用户做出特定评分。
每个用户可以做很多评分。
每本书可以有很多评分。


课程



评分课程

  public class评级{
私人用户用户;
私人图书;
私人诠释评级;
私人日期时间戳;

public Rating(){} //对于hibernate没有arg构造函数
...
}

User class

  public class User {
private long userId;
私人字符串电子邮件,密码;
public User(){}
...
}

Book class

  public class Book {
private long bookId;
私有字符串标题;

public Book(){}
...
}




 公共类RatingId实现Serializable {
私有用户用户;
私人图书;
私人诠释评级;
//一个简单的初始化构造函数
public PurchasedTestId(用户用户,Book book,int rating){
this.user = user;
this.book = book;
this.rating = rating;


创建你的getter和setter加重写equals和hashCode()方法* /


}

现在创建您的主评级课程: public class RatingBook {
RatingId RatingId;
私人日期时间戳;

/ *为这两种方法产生getter和setters * /

}

您可以尝试以下操作:

 < composite-id name =ratingId> 
< key-property name =usercolumn =user/>
< key-property name =bookcolumn =book/>
< key-property name =ratingcolumn =pid/>
< / composite-id>

然后看看是否适合您


I have the following three simple classes. How do I go about mapping the Rating class and more specifically its composite key in my Rating.hbm.xml file? I'm currently getting quite lost in the hibernate documentation (5.1.2.1. Composite identifiers)

Each rating can have one book and one user making that specific rating. Each user can make many ratings. Each book can have many ratings.

Classes

Rating class

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

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

User class

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

Book class

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

    public Book() {}
    ...
}

解决方案

Firstly you should create a composite primary key class like this:

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 */ 


}

Now create your main Rating class like this:

public class RatingBook {
RatingId RatingId;
private Date timestamp;

/* generate getters and setters for these two methods*/

}

You may try the following:

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

and see if that works for you

这篇关于如何在hbm.xml文件中的hibernate中创建复合主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆