需要帮助了解外键

时间:2014-08-10 17:14:49

标签: spring hibernate

我有一个带有外键的消息类,该外键应该是编写消息的作者的id。据我了解,消息类中的外键应该类似于下面的类。

将外键设置为如下所示的作者对象,似乎很荒谬,因为我没有像" 5"这样的简短和人类可读的ID,而是在一个非常长的字符串中数据库不是人类可读的。

我错过了什么,对吧?

消息类:

public class Message {
...
private Author author; // this is the foreign key

...
@ManyToOne
@JoinColumn(name = "USERNAME")
public User getAuthor() {
    return author;
}

public void setAuthor(Author author) {
    this.author = author;
}
...

创建要保存的消息对象:

Author author = ...
message.setAuthor(author);

2 个答案:

答案 0 :(得分:1)

假设您只是在寻找多对一的单向关系

@Entity
public class Message {
...
@ManyToOne
@JoinColumn(name="USERNAME")
private Author author;

@Entity
public class Author {
@Id
@GeneratedValue
@Column(name="USERNAME")
private Long USERNAME;

答案 1 :(得分:0)

您不会发布作者类的注释。您很可能在Author类网站上缺少注释。不过请看下面:

@Entity
@Table(name = "bill")
public class BillModel {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "bill_id")
    private Integer billId;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "fk_shop_id")
    private Shop shop;

// getters and setters

}

和班级商店

@Entity
@Table(name = "shop")
public class Shop {

    @Id
    @GeneratedValue
    @Column(name = "shop_id")
    private Integer shopId;

    @Column(name = "shop_name")
    private String shopName;

    @OneToMany(mappedBy = "shop", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<BillModel> billModels = new HashSet<BillModel>();

// getters and setters
}