简体   繁体   中英

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. 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 . I'm trying to somehow reference the ids of Customer and Comment directly from Order .

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.

Is this task at all possible? If so, how to map them to each other?

For the reference to Comment you must use @JoinColum

The Customer reference assumes that there is a customer_id on the order table.

@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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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