繁体   English   中英

如何在Spring Boot中使用hibernate / jpa在mysql关系表中插入数据

[英]How to insert the data in mysql relation table using hibernate/jpa in Spring Boot

我有以下架构 在此输入图像描述

首先是对的吗? 像1 供应商有多个付款 ,供应商有1个身份是他的信息

我想插入供应商支付的款项。 我目前正在做的是POST一个json文件,它有以下元素。

{
   "date":"2017-02-17",
   "dueDate":"2018-02-17",
   "payable":2000,
   "paid":1000,
   "supplierId":1
}

现在在控制器中,我正在读取requestJson,提取供应商的ID ,然后找到其类的对象,然后将其传递给付款以添加付款。 这是正确的方法吗?

case "payment": {

            logger.debug("The condition for the insertion of the payment.");
            try {
                logger.debug("Populating the request Map with the request to identify the type of .");
                requestMap = mapper.readValue(requestBody, Map.class);
            } catch (IOException e) {
                e.printStackTrace();
            }


            logger.debug("Identifying the key for the payment is it for customer or supplier.");
            if ((requestMap.containsKey("customerId")) || requestMap.containsKey("pending")){

                logger.debug("The request for the adding payment of the customer has been received.");
                Customer customer = customerRepository.findById(Integer.parseInt(requestMap.get("customerId")));

 //                    Payment payment = new Payment(requestMap.get("dueDate"), requestMap.get("pending"), customer, requestMap.get("data"))
 //                    paymentRepository.save()
            } else if (requestMap.containsKey("supplierId") || requestMap.containsKey("outstanding")){

            }
} 

我在这里有信息模型。

@Entity // This tells Hibernate to make a table out of this class
@Table(name = "Information")
public class Information {

private Integer id;

    private String name;

    private String contactNo;

    private String email;

    private String address;

    private Customer customer;

    private Supplier supplier;


    public Information() {
    }

    public Information(String name, String contactNo, String email, String address) {
        this.name = name;
        this.contactNo = contactNo;
        this.email = email;
        this.address = address;
    }

    public Information(Customer customer) {
        this.customer = customer;
    }

    public Information(Supplier supplier) {
        this.supplier = supplier;
    }

    /**
     *
     * @return
     */

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name="name", nullable = false)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "contact_no", unique = true, nullable = false)
    public String getContactNo() {
        return contactNo;
    }

    public void setContactNo(String contactNo) {
        this.contactNo = contactNo;
    }

    @Column(name = "email", unique = true, nullable = false)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @OneToOne(mappedBy = "information")
    @JsonBackReference(value = "customer-reference")
    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    @OneToOne(mappedBy = "information")
    @JsonBackReference(value = "supplier-reference")
    public Supplier getSupplier() {
        return supplier;
    }

    public void setSupplier(Supplier supplier) {
        this.supplier = supplier;
    }

    @Override
    public String toString() {
        return "Information{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", contactNo='" + contactNo + '\'' +
                ", email='" + email + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

}

在这里,我有客户 ,还有一些与此相关的其他关系忽略它们我想得到这个想法。

@Entity
@Table(name = "Customer") //maps the entity with the table. If no @Table is defined,
// the default value is used: the class name of the entity.
public class Customer {

    private Integer id;

    private Information information;

    private Set<Payment> payments;

    private Set<Sale> sales;

    private Set<Orders> orders;

    public Customer() {
    }

    public Customer(Information information) {
        this.information = information;
    }



    /**
     *
     * @return
     */

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @OneToOne(cascade = CascadeType.ALL ,fetch = FetchType.EAGER)
    @JoinColumn(name = "Information_id")
    @JsonManagedReference(value = "customer-reference")
    public Information getInformation() {
        return information;
    }

    public void setInformation(Information information) {
        this.information = information;
    }

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    public Set<Payment> getPayments() {
        return payments;
    }

    public void setPayments(Set<Payment> payments) {
        this.payments = payments;
    }

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "CustomerSales", joinColumns = @JoinColumn(name = "Customer_id",
            referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "Sale_id", referencedColumnName = "id"))
    public Set<Sale> getSales() {
        return sales;
    }

    public void setSales(Set<Sale> sales) {
        this.sales = sales;
    }

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    public Set<Orders> getOrders() {
        return orders;
    }

    public void setOrders(Set<Orders> orders) {
        this.orders = orders;
    }

    @Override
    public String toString() {
        return String.format("Customer{id = %d, " +
                "name = %s, " +
                "contact_no = %s, " +
                "address = %s, " +
                "email = %s}",
                id,information.getName(), information.getContactNo(), information.getAddress(), information.getEmail());
    }
}

这是供应商模型。

@Entity
@Table(name = "Supplier")
public class Supplier {

    private Integer id;

    private Information information;

    private Set<Payment> payments;

    private Set<Orders> orders;

    private Set<Purchase> purchases;


    public Supplier() {
    }

    public Supplier(Information information) {
        this.information = information;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "InformationId")
    @JsonManagedReference(value = "supplier-reference")
    public Information getInformation() {
        return information;
    }

    public void setInformation(Information information) {
        this.information = information;
    }

    @OneToMany(mappedBy = "supplier", cascade = CascadeType.ALL)
    public Set<Payment> getPayments() {
        return payments;
    }

    public void setPayments(Set<Payment> payments) {
        this.payments = payments;
    }

    @OneToMany(mappedBy = "supplier", cascade = CascadeType.ALL)
    public Set<Orders> getOrders() {
        return orders;
    }

    public void setOrders(Set<Orders> orders) {
        this.orders = orders;
    }

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "SupplierPurchases", joinColumns = @JoinColumn(name = "Supplier_id",
            referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "Purchase_id", referencedColumnName = "id"))
    public Set<Purchase> getPurchases() {
        return purchases;
    }

    public void setPurchases(Set<Purchase> purchases) {
        this.purchases = purchases;
    }
}

然后最后但并非最不重要的是我们有支付模式。

@Entity
@Table(name="Payment")
public class Payment {

    private Integer id;

    private Date dueDate;

    private Long paid;// When you are in debit you have to pay to supplier

    private Long payable; // When you have to take from customer.

    private Date date;

    private Customer customer;

    private Supplier supplier;

    private PaymentMethod paymentMethod;

    public Payment() {
    }

    public Payment(Date dueDate, Long payable, Date date, Customer customer, PaymentMethod paymentMethod) {
        this.dueDate = dueDate;
        this.paid = payable;
        this.date = date;
        this.customer = customer;
        this.paymentMethod = paymentMethod;
    }

    public Payment(Date dueDate, Long paid, Date date, Supplier supplier, PaymentMethod paymentMethod) {
        this.dueDate = dueDate;
        this.paid = paid;
        this.date = date;
        this.supplier = supplier;
        this.paymentMethod = paymentMethod;
    }






    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(nullable = false)
    public Date getDueDate() {
        return dueDate;
    }

    public void setDueDate(Date dueDate) {
        this.dueDate = dueDate;
    }

    public Long getPaid() {
        return paid;
    }

    public void setPaid(Long paid) {
        this.paid = paid;
    }

    public Long getPayable() {
        return payable;
    }

    public void setPayable(Long payable) {
        this.payable = payable;
    }


    @ManyToOne
    @JoinColumn(name = "CustomerId")//mappedBy indicates the entity is the inverse of the relationship.
    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    @ManyToOne
    @JoinColumn(name = "SupplierId")
    public Supplier getSupplier() {
        return supplier;
    }

    public void setSupplier(Supplier supplier) {
        this.supplier = supplier;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @ManyToOne
    @JoinColumn(name = "PaymentMethodId")
    public PaymentMethod getPaymentMethod() {
        return paymentMethod;
    }

    public void setPaymentMethod(PaymentMethod paymentMethod) {
        this.paymentMethod = paymentMethod;
    }

    @Override
    public String toString() {
        return "Payment{" +
                "id=" + id +
                ", dueDate=" + dueDate +
                ", paid=" + paid +
                ", payable=" + payable +
                ", date=" + date +
                '}';
    }

或者有更好的方法来执行此任务吗?

感激:)

我正在读取requestJson提取供应商的ID ,然后查找其类的对象,然后将其传递给付款以添加付款。 这是正确的方法吗?

让Spring框架为您完成工作。 首先修改一下JSON请求:

{
   "date":"2017-02-17",
   "dueDate":"2018-02-17",
   "payable":2000,
   "paid":1000,
   "supplier":{"id":1}
}

我只能猜测你的REST控制器目前是什么样子,但一个示例实现可能如下:

@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private final PaymentRepository paymentRepository;

    public PaymentController(PaymentRepository paymentRepository) {
        this.paymentRepository = paymentRepository;
    }

    @RequestMapping(method = RequestMethod.POST)
    ResponseEntity<?> insert(@RequestBody Payment payment) {
        paymentRepository.save(payment);
        return ResponseEntity.accepted().build();

    }
}

这种方法导致请求的主体直接映射到Payment对象以及自动实例化的Supplier字段,因此它足以将其保存到存储库中。 它易于维护和维护。

显然, PaymentMethod不考虑CustomerPaymentMethod关系,但您可以轻松扩展JSON请求以支持它们。


我有以下架构
...
首先是对的吗? 如1 供应商有多个付款 ,供应商有1个身份是他的信息

一般来说,我没有看到你的架构错误,但通常它取决于你想要实现什么。 这绝对可以工作,但总是存在诸如性能和内存考虑因素等因素对数据建模方式的影响:

  • 插入 - 付款客户供应商提供单独的FK,事实上这两者几乎相同( 销售购买 ),因此最好有一个表承包商汇总客户和供应商及其信息
  • 查询 - 一次请求客户供应商及其信息的付款,更不用说他们的订单销售 / 购买 ,需要跨表的层次结构进行多次连接

在这里,您可以找到利用JPA继承的替代方法:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "ContractorType")
public class Contractor {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "contact_no", unique = true, nullable = false)
    private String contactNo;

    @Column(name = "email", unique = true, nullable = false)
    private String email;

    private String address;
}

上述实体替换了创建下表的CustomerSupplierInformation实体,但仅汇总了它们的公共部分:

Contractor
----------
contractor_type  <----  discriminator column for Customer and Supplier
id
name
contact_no          
email           
address         

其余的特定字段(销售,采购,订单)需要放在派生实体中,比如说CustomerOperationsSupplierOperations 他们像以前一样创建了两个连接表,因此这里没有任

@Entity
@DiscriminatorValue("C")
public class CustomerOperations extends Contractor {

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    private Set<Payment> payments;

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    private Set<Orders> orders;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "CustomerSales", 
       joinColumns = @JoinColumn(name = "Customer_id", referencedColumnName = "id"), 
       inverseJoinColumns = @JoinColumn(name = "Sale_id", referencedColumnName = "id"))
    private Set<Sale> sales;
}

@Entity
@Table(name = "SupplierPurchases ")
@DiscriminatorValue("S")
public class SupplierPurchases extends Contractor {

    @OneToMany(mappedBy = "supplier", cascade = CascadeType.ALL)
    private Set<Payment> payments;

    @OneToMany(mappedBy = "supplier", cascade = CascadeType.ALL)
    private Set<Orders> orders;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "SupplierPurchases", 
        joinColumns = @JoinColumn(name = "Supplier_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "Purchase_id", referencedColumnName = "id"))
    private Set<Purchase> purchases;
}

这种方法往往工作得更快,因为底层SQL需要更少的连接,因此执行计划可能更有效。

值得一提的是JPA提供了其他继承策略。 选择合适的任务并非易事,因为每个都有优点和缺点。 如果你对细微差别感兴趣,请仔细看看这里

暂无
暂无

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

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