JPA一对多和多对一关系

1-m:多的一方为关系维护端,关系维护端负责外键纪录的更新,关系被维护端没有权力更新外键纪录.

维护端注解

@OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REFRESH,
CascadeType.MERGE, CascadeType.REMOVE },
fetch = FetchType.EAGER,
mappedBy = "order")


被维护端注解

@ManyToOne(cascade = { CascadeType.MERGE, CascadeType.REFRESH }, optional = false)
@JoinColumn(name = "order_id")

public class Order {
    @id
    private long id;
 
    @ManyToOne
    @JoinColumn(name="customer", nullable=false)
    private Customer customer;
 
    public void setId(long id) {
        this.id = id;
    }
 
    public long getId() {
        return this.id;
    }
 
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
 
    public Customer getCustomer() {
        return this.customer;
    }
}
 
public class Customer{
    @id
    private long id;
 
    @OneToMany(mappedBy="customer")
    private Set<Order> orders;
 
    public void setId(long id) {
        this.id = id;
    }
 
    public long getId() {
        return this.id;
    }
 
    public void setOrders(Set<Order> orders) {
        this.orders = orders;
    }
 
    public Set<Order> getOrders() {
        return this.orders;
    }
}

多出一个mappedBy和JoinColumn, 就是告诉JPA实现者,orders是通过order里的customer映射来的,每次查找orders通过Order里的customer联接。这样就不会生成Customer_Order关联表了

你可能感兴趣的:(JPA一对多和多对一关系)