简体   繁体   English

在 JPA/Hibernate 中映射实体而不添加其他字段(仅通过使用 ids)

[英]Mapping entities in JPA/Hibernate without adding additional fields (just by using ids)

I'm trying to map those three entities to each other without adding any additional fields to any of them.我正在尝试将这三个实体相互 map 而不向其中任何一个添加任何其他字段。 They should only contain the fields that already exist.它们应该只包含已经存在的字段。 I'm also trying to only get columns in the tables that represent the currently existing entity fields- and no additional columns.我还尝试仅获取表中代表当前存在的实体字段的列,而不获取其他列。

@Entity
public class Order {
    @Id
    private Integer orderId;
    private String title;
    private Customer customer;
    private List<Comment> comments;
}

@Entity
public class Customer {
    @Id
    private Integer customerId;
    private String name;
}

@Entity
public class Comment {
    @Id
    private Integer commentId;
    private Integer orderId;
    private String details;
}

My understanding is that I can't simply use @OneToOne, @OneToMany and @ManyToOne mappings, because neither Customer nor Comment has a reference to Order .我的理解是,我不能简单地使用 @OneToOne、@OneToMany 和 @ManyToOne 映射,因为CustomerComment都没有对Order的引用。 I'm trying to somehow reference the ids of Customer and Comment directly from Order .我试图以某种方式直接从Order引用CustomerComment的 ID。

I've tried using @MapsId and @JoinColumn but either I don't know how to properly use them, or they don't do what I think they do.我试过使用@MapsId 和@JoinColumn,但要么我不知道如何正确使用它们,要么他们没有做我认为他们做的事情。

Is this task at all possible?这个任务有可能吗? If so, how to map them to each other?如果是这样,如何将它们相互连接起来?

For the reference to Comment you must use @JoinColum对于 Comment 的引用,您必须使用@JoinColum

The Customer reference assumes that there is a customer_id on the order table. Customer 引用假定 order 表上有一个 customer_id。

@Entity
public class Order {
    @Id
    private Integer orderId;
    private String title;

    @ManyToOne
    @JoinColumn(name = "customer_id")
    private Customer customer;

    @OneToMany
    @JoinColumn(name = "comment_id")
    private List<Comment> comments;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM