简体   繁体   中英

How do I map one entity to two tables?

The primary key has to be mapped to two tables; with the first table I got Many to One, and the second one it is One to One; how do I do that? Im giving you my class

package salepoint.model;

/*i've deleted imports*/

@Entity
@Table (name = "sales")
@SecondaryTables({
    @SecondaryTable(name = "sold_products", pkJoinColumns = {
        @PrimaryKeyJoinColumn(name = "sales_id")})})
public class Sale implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @ManyToOne
    @JoinTable(name = "user_sales", joinColumns = @JoinColumn(name =                         "sale_id"))
private Integer id;

@Column (name = "amount")
private Double amount;

@Column (name = "date")
private Date date;

@Column (name = "user_id")
private Integer user_id;

public Sale() {
}

public Sale(Double amount, Date date, Integer user_id) {
    this.amount = amount;
    this.date = date;
    this.user_id = user_id;
}

public Sale(Integer id, Double amount, Date date, Integer user_id) {
    this.id = id;
    this.amount = amount;
    this.date = date;
    this.user_id = user_id;
}

@Override
public String toString() {
    return "Sale{"
            + "id = " + id
            +", amount = " + amount
            + ", date = " + date
            + ", user_id = " + user_id + '}';
}
/*i've deleted getters and setters, stack overflow didn't want me to put it*/
}

Hope you can help me, guys; i'm desperated

Please correct me i am wrong here,

you are trying to map users and their sales tables. Then you why you need to create many-to-one mapping in sales table it should be in user pojo with an

list<sale> sales;

The above attribute should be annotated with many to one. and in sale pojo,

User user;

Annotate with one to many thats it.

Are you looking something like this ?

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