JPA:如何处理与其他两个表有关系的表的Map?

ar5n3qh5  于 2022-12-13  发布在  其他
关注(0)|答案(2)|浏览(106)

我有三个表,表A(产品)、表B(发票)和表C(发票_信息),其中包含引用invoice_idproduct_id的两列。如何插入新条目(新发票),同时将产品插入相应的表并将发票信息插入相应的表?
以下是实体类:产品名称

@Entity
@Table(name = "product")
public class Product {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "family_id")
private long familyId;   
@Column(name = "product_name")
private String productName;
@Column(name = "product_category")
private String productCategory;
@Column(name = "product_quantity")
private int productQuantity;
//getters and setters
}

发票

@Entity
@Table(name = "invoice")
public class Invoice {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "invoice_id")
private Long id;
@Column(name = "provider_id")
private Long providerId;
@Column(name = "total")
private int invoiceTotal;
@Column(name = "date")
private Date invoiceDate;
//getters and setters
}

发票信息

@Entity
@Table(name = "invoice_info")
public class InvoiceInfo {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "item_id")
private long id;   
@Column(name = "product_id")
private long productId;
@Column(name = "invoice_id")
private long invoiceId;

//getters and setters
}
nlejzf6q

nlejzf6q1#

InvoiceInfo应为联接表,根据您要求使用@OneToMany,@ManyToOne注解定义实体Product和Invoice关系

olqngx59

olqngx592#

您必须使用一组注解来建立实体之间的关系,例如:@ManyToOne@OneToMany@ManyToMany@OneToOne ...以及其他注解(如果需要)。
在您的情况下,我不确定是否需要InvoiceInfo表,因为Invoice表已经可以(或应该)包含产品列表。
我建议您建立以下关系:

产品名称

@Entity
@Table(name = "product")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "family_id")
    private long familyId;   
    @Column(name = "product_name")
    private String productName;
    @Column(name = "product_category")
    private String productCategory;
    @Column(name = "product_quantity") 
    private int productQuantity;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "invoice_id", referencedColumnName = "id")
    private Invoice invoice;
    //getters and setters
}

发票

@Entity
@Table(name = "invoice")
public class Invoice {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "invoice_id")
    private Long id;
    @Column(name = "provider_id")
    private Long providerId;
    @Column(name = "total")
    private int invoiceTotal;
    @Column(name = "date")
    private Date invoiceDate;
    @OneToMany(mappedBy = "product")
    private List<Product> products;
    //getters and setters
}

由于您的表InvoiceInfo已不存在,您只需将数据插入两个表中,如下所示:

Invoice invoice = invoiceRepository.save(invoice);
Product product = new Product();
// Set the other properties
product.setInvoice(invoice);
productRepository.save(product);

相关问题