如果同时保存的两个实体父子实体映射为一对多关系,则抛出 id not found 父类异常

Posted

技术标签:

【中文标题】如果同时保存的两个实体父子实体映射为一对多关系,则抛出 id not found 父类异常【英文标题】:If two entity parent and child saved at same time which mapped with one to many relationship throw id not found exception of parent class 【发布时间】:2021-04-30 18:24:00 【问题描述】:

我的关系如图所示: enter image description here

我在数据库中插入数据时遇到了麻烦,因为帐单 ID 保存得有点晚,而且当时还购买帐单同时保存在数据库中,并且希望帐单 ID 保存在关系中并抛出异常,例如未找到发票 ID,只有我的账单数据保存在数据库中,buybill thrwo 没有找到账单 ID,所以请帮帮我。

谢谢,

还有一件事我包括我的后期映射:

这--->

@PostMapping(value="/customers/customerId/bills/InvoiceNo/buyBills",produces="application/json",consumes="application/json")

这--->

@PostMapping(value="/customers/customerId/bills/InvoiceNo/bills",produces="application/json",consumes="application/json")

通过两个 $http.post() 同时在 html 中使用一个 angularjs 提交按钮。

这是我通过 $scope.purchase 函数的 angular.js onclick 发布两个 http 请求的 javascript 代码,其中我发布了两个 url,它们映射到 URL1 和 URL2 上方,带有 json 数据和 BillData,buyBillFormss.html 代码:

<script type="text/javascript">
var invoice = angular.module('invoice', []);
invoice.controller('InvoiceController', function($scope,$window,$http)

$scope.purchase = function()
    if(!$scope.myForm.$valid)
        console.log("Invalid")
        $scope.err = "Invaid Transaction Please Insert valid field or Refresh!!!";
        
    if($scope.myForm.$valid)
        angular.forEach($scope.invoice.items, function(item)
            var Bill = []; 
            $scope.am = (((item.qty * item.price)+((item.qty * item.price)*item.gst)/100)-item.dis).toFixed(2);
            angular.forEach($scope.invoice.items, function (value, key) 
                var am = (((value.qty * value.price)+((value.qty * value.price)*value.gst)/100)-value.dis).toFixed(2);
                Bill.push(
                    "proId" : value.proId,
                     "name" : value.name,
                     "description" : value.description,
                     "qty" : value.qty,
                     "unit" : value.unit,
                     "price" : value.price,
                     "dis" : value.dis,
                     "gst" : value.gst,
                     "amount" : am
                     );
                );
                console.log("Bill ::");
                console.log(Bill);
                localStorage.setItem("data",JSON.stringify(Bill));
                ///////////////////////////////////////////////////////
                var id = document.getElementById("ids").innerText;
                var InvoiceNo = document.getElementById("InvoiceNo").innerText;
                var data=
                        "proId" : item.proId,
                        "name" : item.name,
                        "description" : item.description,
                        "qty" : item.qty,
                        "unit" : item.unit,
                        "price" : item.price,
                        "dis" : item.dis,
                        "gst" : item.gst,
                        "amount" : $scope.am
                        ;
                console.log("Data ::");
                console.log(data);
                $scope.CustomerId = id;
                $scope.InvoiceNo  = InvoiceNo;
                var URL1 = "http://localhost:8083/cust/customers/"+$scope.CustomerId+"/bills/"+$scope.InvoiceNo+"/buyBills";
                $http.post(URL1, data);
                
        );
        //angular.forEach($scope.invoice.items, function(item)
            var id = document.getElementById("ids").innerText;
            var name = document.getElementById("name").innerText;
            var InvoiceNo = document.getElementById("InvoiceNo").innerText;
            var address = document.getElementById("address").innerText;
            var mobileNo = document.getElementById("mobileNo").innerText;
            var note = document.getElementById("n").value;
            var InterestRate = document.getElementById("i").value;
            var CredibilityStatus = "very Good";
            var guarantorName = document.getElementById("g").value;
            var BillData=
                    "invoiceNo" : InvoiceNo,
                     "name" : name,
                     "address" : address,
                     "mobileNo" : mobileNo,
                     "totalGSTAmount" : ($scope.GST()).toFixed(2),
                     "totalDiscountAmount" : $scope.Dis(),
                     "guarantorName" : guarantorName,
                     "totalAmount" : ($scope.TotalAmount()).toFixed(2),
                     "paidAmount" :  ($scope.PaidAmount()).toFixed(2),
                     "dueAmount" :  ($scope.DueAmount()).toFixed(2),
                     "status" : $scope.Status(),
                     "interestRate" : InterestRate,
                     "credibilityStatus" : CredibilityStatus, 
                     "note"   : note
                     ;
            console.log("BillData ::");
            console.log(BillData);
            $scope.CustomerId = id;
            $scope.InvoiceNo  = InvoiceNo;
            var URL2 = "http://localhost:8083/cust/customers/"+$scope.CustomerId+"/bills/"+$scope.InvoiceNo+"/bills";
            $http.post(URL2, BillData);
            localStorage.setItem("dataAct",JSON.stringify(BillData));
            //);
        $window.location.href = "/Bill"
        
        
   
);
</script>

我的代码在这里:

这是我的 customer.java 实体:

package com.alpha.demo.model;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import java.util.UUID;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.CreationTimestamp;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@Table(name = "customers")
@JsonIgnoreProperties("hibernateLazyInitializer", "handler") 
public class Customer implements Serializable 
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    
    @Column(name = "uniqueId", updatable = false, nullable = false)
    private UUID uniqueId = UUID.randomUUID();
    @Column(columnDefinition = "TEXT")
    private String photos;
    private String fullName;
    private String aadhaarNo;
    private String guarantor;
    private String address;
    private String mobileNo;
    private String note;
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "create_date",updatable=false)
    private Date createDate;
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.LAZY) 
    private Set<Bill> Bill;

    public Long getId() 
        return id;
    
    public void setId(Long id) 
        this.id = id;
    
    public UUID getUniqueId() 
        return uniqueId;
    
    public void setUniqueId(UUID uniqueId) 
        this.uniqueId = uniqueId;
    
    public String getFullName() 
        return fullName;
    
    public void setFullName(String fullName) 
        this.fullName = fullName;
    
    
    public String getPhotos() 
        return photos;
    
    public void setPhotos(String photos) 
        this.photos = photos;
    
    public String getAadhaarNo() 
        return aadhaarNo;
    
    public void setAadhaarNo(String aadhaarNo) 
        this.aadhaarNo = aadhaarNo;
    
    public String getGuarantor() 
        return guarantor;
    
    public void setGuarantor(String guarantor) 
        this.guarantor = guarantor;
    
    public String getAddress() 
        return address;
    
    public void setAddress(String address) 
        this.address = address;
    
    public String getMobileNo() 
        return mobileNo;
    
    public void setMobileNo(String mobileNo) 
        this.mobileNo = mobileNo;
    
    public String getNote() 
        return note;
    
    public void setNote(String note) 
        this.note = note;
    
    public Date getCreateDate() 
        return createDate;
    
    public void setCreateDate(Date createDate) 
        this.createDate = createDate;
    

    public static long getSerialversionuid() 
        return serialVersionUID;
    
    
    public Set<Bill> getBill() 
        return Bill;
    
    public void setBill(Set<Bill> bill) 
        Bill = bill;
    
    public Customer(String photos, String fullName, String aadhaarNo, String guarantor, String address, String mobileNo,
            String note, Date createDate) 
        super();
        this.photos = photos;
        this.fullName = fullName;
        this.aadhaarNo = aadhaarNo;
        this.guarantor = guarantor;
        this.address = address;
        this.mobileNo = mobileNo;
        this.note = note;
        this.createDate = createDate;
    
    public Customer() 
    


这是我的 Bill.java 实体:

package com.alpha.demo.model;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.CreationTimestamp;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@Table(name = "bills")
@JsonIgnoreProperties("hibernateLazyInitializer", "handler") 
public class Bill implements Serializable
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long invoiceNo;
    private String guarantorName;
    private String TotalGSTAmount;
    private String TotalDiscountAmount;
    private String TotalAmount;
    private String PaidAmount;
    private String DueAmount;
    private String InterestRate;
    private String TotalInterestAmount;
    private String Status;
    private String CredibilityStatus;
    private String Note;
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "billing_date",updatable=false)
    private Date BillingDate;
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "customer_id", nullable = false)
    @JsonIgnore
    private Customer customer;
    @OneToMany(mappedBy = "bill", cascade = CascadeType.ALL, fetch = FetchType.LAZY) 
    private Set<BuyBill> BuyBill;
  
    

    
    public Bill() 
        
    
    public Long getId() 
        return id;
    
    public void setId(Long id) 
        this.id = id;
    

    
    public Long getInvoiceNo() 
        return invoiceNo;
    
    public void setInvoiceNo(Long invoiceNo) 
        this.invoiceNo = invoiceNo;
    
    public String getGuarantorName() 
        return guarantorName;
    
    public void setGuarantorName(String guarantorName) 
        this.guarantorName = guarantorName;
    
    public String getTotalAmount() 
        return TotalAmount;
    
    public void setTotalAmount(String totalAmount) 
        TotalAmount = totalAmount;
    
    public String getPaidAmount() 
        return PaidAmount;
    
    public void setPaidAmount(String paidAmount) 
        PaidAmount = paidAmount;
    
    public String getDueAmount() 
        return DueAmount;
    
    public void setDueAmount(String dueAmount) 
        DueAmount = dueAmount;
    
    public String getInterestRate() 
        return InterestRate;
    
    public void setInterestRate(String interestRate) 
        InterestRate = interestRate;
    
    public String getTotalInterestAmount() 
        return TotalInterestAmount;
    
    public void setTotalInterestAmount(String totalInterestAmount) 
        TotalInterestAmount = totalInterestAmount;
    
    public String getStatus() 
        return Status;
    
    public void setStatus(String status) 
        Status = status;
    
    
    
    public String getTotalGSTAmount() 
        return TotalGSTAmount;
    
    public void setTotalGSTAmount(String totalGSTAmount) 
        TotalGSTAmount = totalGSTAmount;
    
    public String getTotalDiscountAmount() 
        return TotalDiscountAmount;
    
    public void setTotalDiscountAmount(String totalDiscountAmount) 
        TotalDiscountAmount = totalDiscountAmount;
    
    public Date getBillingDate() 
        return BillingDate;
    
    public void setBillingDate(Date billingDate) 
        BillingDate = billingDate;
    
    public Customer getCustomer() 
        return customer;
    
    public void setCustomer(Customer customer) 
        this.customer = customer;
    
    public Set<BuyBill> getBuyBill() 
        return BuyBill;
    
    public void setBuyBill(Set<BuyBill> buyBill) 
        BuyBill = buyBill;
    
    public static long getSerialversionuid() 
        return serialVersionUID;
    
    public String getCredibilityStatus() 
        return CredibilityStatus;
    
    public void setCredibilityStatus(String credibilityStatus) 
        CredibilityStatus = credibilityStatus;
    
    public String getNote() 
        return Note;
    
    public void setNote(String note) 
        Note = note;
    
    
    public Bill(Long id, Long invoiceNo, String guarantorName, String totalGSTAmount, String totalDiscountAmount,
            String totalAmount, String paidAmount, String dueAmount, String interestRate, String totalInterestAmount,
            String status, String credibilityStatus, String note, Date billingDate, Customer customer,
            Set<com.alpha.demo.model.BuyBill> buyBill) 
        super();
        this.id = id;
        this.invoiceNo = invoiceNo;
        this.guarantorName = guarantorName;
        TotalGSTAmount = totalGSTAmount;
        TotalDiscountAmount = totalDiscountAmount;
        TotalAmount = totalAmount;
        PaidAmount = paidAmount;
        DueAmount = dueAmount;
        InterestRate = interestRate;
        TotalInterestAmount = totalInterestAmount;
        Status = status;
        CredibilityStatus = credibilityStatus;
        Note = note;
        BillingDate = billingDate;
        this.customer = customer;
        BuyBill = buyBill;
    
    @Override
    public String toString() 
        return "Bill [id=" + id + ", invoiceNo=" + invoiceNo + ", guarantorName=" + guarantorName + ", TotalGSTAmount="
                + TotalGSTAmount + ", TotalDiscountAmount=" + TotalDiscountAmount + ", TotalAmount=" + TotalAmount
                + ", PaidAmount=" + PaidAmount + ", DueAmount=" + DueAmount + ", InterestRate=" + InterestRate
                + ", TotalInterestAmount=" + TotalInterestAmount + ", Status=" + Status + ", CredibilityStatus="
                + CredibilityStatus + ", Note=" + Note + ", BillingDate=" + BillingDate + ", customer=" + customer
                + ", BuyBill=" + BuyBill + "]";
    
    

这是我的 BuyBill 实体:

package com.alpha.demo.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@Table(name = "buyBills")
@JsonIgnoreProperties("hibernateLazyInitializer", "handler") 
public class BuyBill implements Serializable 
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Long proId;
    private String name;
    private String description;
    private String qty;
    private String unit;
    private String price;
    private String dis;
    private String gst;
    private String amount;
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "bill_id", nullable = false)
    @JsonIgnore
    private Bill bill;

    

    public BuyBill(Long id, Long proId, String name, String description, String qty, String unit, String price,
            String dis, String gst, String amount, Bill bill) 
        super();
        this.id = id;
        this.proId = proId;
        this.name = name;
        this.description = description;
        this.qty = qty;
        this.unit = unit;
        this.price = price;
        this.dis = dis;
        this.gst = gst;
        this.amount = amount;
        this.bill = bill;
    

    public BuyBill() 
    

    public Long getId() 
        return id;
    

    public void setId(Long id) 
        this.id = id;
    

    public String getName() 
        return name;
    

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

    public String getDescription() 
        return description;
    

    public void setDescription(String description) 
        this.description = description;
    

    public String getQty() 
        return qty;
    

    public void setQty(String qty) 
        this.qty = qty;
    

    public String getUnit() 
        return unit;
    

    public void setUnit(String unit) 
        this.unit = unit;
    

    public String getPrice() 
        return price;
    

    public void setPrice(String price) 
        this.price = price;
    

    public String getDis() 
        return dis;
    

    public void setDis(String dis) 
        this.dis = dis;
    

    public String getGst() 
        return gst;
    

    public void setGst(String gst) 
        this.gst = gst;
    

    public String getAmount() 
        return amount;
    

    public void setAmount(String amount) 
        this.amount = amount;
    

    public Bill getBill() 
        return bill;
    

    public void setBill(Bill bill) 
        this.bill = bill;
    

    public static long getSerialversionuid() 
        return serialVersionUID;
    

    public Long getProId() 
        return proId;
    

    public void setProId(Long proId) 
        this.proId = proId;
    

    
    


这是我的账单的 JPA 存储库:

package com.alpha.demo.Repository;

import java.util.List;
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import com.alpha.demo.model.Bill;


public interface BillRepository extends JpaRepository<Bill, Long>
    List<Bill> findByCustomerId(Long custoemrId);
    
    @Query(value = "SELECT MAX(id) FROM bills", nativeQuery = true) 
    Long getNextSeriesId();
    
    Optional <Bill> findByinvoiceNo(Long invoiceNo);


这是我执行 crud 操作的账单控制器:

package com.alpha.demo.controller;

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alpha.demo.Repository.BillRepository;
import com.alpha.demo.Repository.BuyBillRepository;
import com.alpha.demo.Repository.CustomerRepository;
import com.alpha.demo.exception.NotFoundException;
import com.alpha.demo.model.Bill;
import com.alpha.demo.model.BuyBill;
import com.alpha.demo.model.Customer;


@RestController
@RequestMapping("/cust")
public class BillController 
    @Autowired
    private BillRepository BillRepository;
    

    @Autowired
    private BuyBillRepository buyBillRepository;

    @Autowired
    private CustomerRepository customerRepository;
    
    

    @GetMapping("/customersBuyBill/id")
    public ModelAndView showUpdateForm(@PathVariable("id") long id, @ModelAttribute @Valid @RequestBody Bill bill,
            @ModelAttribute @Valid @RequestBody BuyBill buyBill, Model model) 
        ModelAndView mv = new ModelAndView("buyBillFormss.html");
        Customer ct = customerRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
        model.addAttribute("ct", ct);
        model.addAttribute("bill", bill);
        model.addAttribute("buyBill", buyBill);
        //BillRepository.getNextSeriesId();
        if(BillRepository.getNextSeriesId()==null) 
            Long InvoiceNo = (long) 1;
            model.addAttribute("invoiceNo", InvoiceNo);
        
        if(BillRepository.getNextSeriesId()!=null) 
            Long InvoiceNo = BillRepository.getNextSeriesId() + 1;
            model.addAttribute("invoiceNo", InvoiceNo);
        
        return mv;
    
    
    @PostMapping(value="/customers/customerId/bills/invoiceNo/bills",produces="application/json",consumes="application/json")
    @ResponseBody
    public ModelAndView addBillRequest(@PathVariable Long customerId, @PathVariable Long invoiceNo,@Valid @RequestBody Bill bill) 
        return customerRepository.findById(customerId) .map(customer -> 
             bill.setCustomer(customer); 
             BillRepository.save(bill);  
             ModelAndView mv = new ModelAndView("redirect:/cust/customersBuyBill/customerId"); 
             return mv;
             ).orElseThrow(() -> new NotFoundException("Customer not found!"));
        
    
    @PostMapping(value="/customers/customerId/bills/invoiceNo/buyBills",produces="application/json",consumes="application/json")
    @ResponseBody
    public ModelAndView addBuyBillRequest(@PathVariable Long customerId, @PathVariable Long invoiceNo,@Valid @RequestBody BuyBill buyBill)
        System.out.println(invoiceNo);
        System.out.println(BillRepository.findByinvoiceNo(invoiceNo));
        return BillRepository.findByinvoiceNo(invoiceNo).map(bills -> 
               buyBill.setBill(bills); 
               buyBillRepository.save(buyBill); 
               ModelAndView mv = new ModelAndView("redirect:/cust/customersBuyBill/customerId"); return mv;
        ).orElseThrow(() -> new NotFoundException("Invoice No not found!"));
        
    
    

抛出这个异常: 5 Hibernate:选择 bill0_.id 作为 id1_0_,bill0_.billing_date 作为 billing_2_0_,bill0_.credibility_status 作为 credibil3_0_,bill0_.due_amount 作为 due_amou4_0_,bill0_.interest_rate 作为 interest5_0_,bill0_.note 作为 note6_0_,bill0_.paid_amount 作为paid_amo7_0_,bill0_.status 作为 status8 ,bill0_.total_amount如total_am9_0_,bill0_.total_discount_amount如total_d10_0_,bill0_.totalgstamount如totalgs11_0_,bill0_.total_interest_amount如total_i12_0_,bill0_.customer_id如custome15_0_,bill0_.guarantor_name如guarant13_0_,bill0_.invoice_no从票据invoice14_0_ bill0_其中bill0_.invoice_no = ? 可选的.empty Hibernate:选择 bill0_.id 作为 id1_0_,bill0_.billing_date 作为 billing_2_0_,bill0_.credibility_status 作为 credibil3_0_,bill0_.due_amount 作为 due_amou4_0_,bill0_.interest_rate 作为 interest5_0_,bill0_.note 作为 note6_0_,bill0_.paid_amount 作为paid_amo7_0_,bill0_.status 作为 status8 ,bill0_.total_amount如total_am9_0_,bill0_.total_discount_amount如total_d10_0_,bill0_.totalgstamount如totalgs11_0_,bill0_.total_interest_amount如total_i12_0_,bill0_.customer_id如custome15_0_,bill0_.guarantor_name如guarant13_0_,bill0_.invoice_no从票据invoice14_0_ bill0_其中bill0_.invoice_no = ? 2021-01-27 16:58:05.945 WARN 7652 --- [nio-8083-exec-9] .w.s.m.a.ResponseStatusExceptionResolver:已解决 [com.alpha.demo.exception.NotFoundException:未找到发票!] 休眠:选择 customer0_.id 作为 id1_3_0_,customer0_.aadhaar_no 作为 aadhaar_2_3_0_,customer0_.address 作为 address3_3_0_,customer0_.create_date 作为 create_d4_3_0_,customer0_.full_name 作为 full_nam5_3_0_,customer0_.guarantor 作为 guaranto6_3_0_,customer0_.mobile_no 作为 mobile_n7_3 , customer0_.photos as photos9_3_0_, customer0_.unique_id as unique_10_3_0_ from customers customer0_ where customer0_.id=? 休眠:插入账单(billing_date,credit_status,due_amount,interest_rate,note,paid_amount,status,total_amount,total_discount_amount,totalgstamount,total_interest_amount,customer_id,guarantor_name,invoice_no)值(?,?,?,?,?,?,?, ?, ?, ?, ?, ?, ?, ?)


主要问题::

当 bill 和 buybill 同时保存时,“BillRepository.findById(InvoiceNo)”中的 Bill id 为空。

【问题讨论】:

查找相关部分有点复杂,尤其是所有注释掉的代码。您能否提取执行的相关代码行?您的问题是您 save(bill) 之后您直接尝试通过发票没有检索该账单?请清理您发布的代码。会有帮助的 【参考方案1】:

我假设您的异常发生在此时?

// return BillRepository.findById(InvoiceNo).map(bills -> 
    //       buyBill.setBill(bills); 
    //       buyBillRepository.save(buyBill); 
    //       ModelAndView mv = new ModelAndView("redirect:/cust/customersBuyBill/customerId"); return mv;
    //       ).orElseThrow(() -> new NotFoundException("Invoice No not found!"));

如果是这样,那么您尝试通过 id (BillRepository.findById) 查找 Bill,但提供 invoiceNo 而不是具体的 id

repository.findById 指的是@Id 注释列。在你的情况下:

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;

因此,您需要使用/实现方法findByInvoiceNo 来通过提供的invoiceNo 而不是findById 获得具体的Bill

编辑

您的账单存储库应包含此方法

public interface BillRepository extends JpaRepository<Bill, Long> 
    Bill findByInvoiceNo(String invoiceNo);

然后

return BillRepository.findB<InvoiceNo(InvoiceNo).map(bills -> 
           buyBill.setBill(bills); 
           buyBillRepository.save(buyBill); 
           ModelAndView mv = new ModelAndView("redirect:/cust/customersBuyBill/customerId"); return mv;
    ).orElseThrow(() -> new NotFoundException("Invoice No not found!"));

编辑#2

 @PostMapping(value="/customers/customerId/bills/invoiceNo/buyBills",produces="application/json",consumes="application/json")
@ResponseBody
public ModelAndView addBuyBillRequest(@PathVariable Long customerId, @PathVariable Long invoiceNo,@Valid @RequestBody BuyBill buyBill)
    System.out.println(invoiceNo);
    System.out.println(BillRepository.findByinvoiceNo(invoiceNo));
    return BillRepository.findByinvoiceNo(invoiceNo).map(bills -> 
           buyBill.setBill(bills); 
           buyBillRepository.save(buyBill); 
           ModelAndView mv = new ModelAndView("redirect:/cust/customersBuyBill/customerId"); return mv;
    ).orElseThrow(() -> new NotFoundException("Invoice No not found!"));
    

不应该

return BillRepository.findByinvoiceNo(invoiceNo).map(bills -> 
               bills.addBuyBill(buyBill);
               billsRepository.save(bills); 

在 Bill 类中:

public class Bill implements Serializable 
  public void addBuyBill(BuyBill buyBill) 
    this.BuyBill.add(buyBill);
    buyBill.setBill(this)
  

这部分也是如此

 return customerRepository.findById(customerId) .map(customer -> 
             bill.setCustomer(customer); 
             BillRepository.save(bill);  
             ModelAndView mv = new ModelAndView("redirect:/cust/customersBuyBill/customerId"); 
             return mv;
             ).orElseThrow(() -> new NotFoundException("Customer not found!"));
        

由于客户没有或更多的账单,您需要像以前一样添加同步方法:

 return customerRepository.findById(customerId) .map(customer -> 
             customer.addBill(bill); 
             CustomerRepository.save(customer);  
             ModelAndView mv = new ModelAndView("redirect:/cust/customersBuyBill/customerId"); 
             return mv;
             ).orElseThrow(() -> new NotFoundException("Customer not found!"));
        

在客户中

public class Customer implements Serializable 
  public void addBill(Bill newBill) 
    this.Bill.add(newBill);
    newBill.setCustomer(this)
  

当您使用双向关联时,您应该保持它们同步。否则实体的状态转换可能不起作用。

很抱歉进行长期调查。但是代码很难识别。

您绝对应该考虑进行一些重构。但这超出了这个问题的范围。

【讨论】:

谢谢!是的,你是对的,我尝试了代码“BillRepository.findById(InvoiceNo)”的那部分问题,但对我没有任何帮助。 您是否尝试过在您的BillRepository 中定义一个方法findByInvoiceNo 并改为调用该方法? 问题是 InvoiceNo 在哪里保存了账单数据库中没有找到的购买账单,因为我同时保存了父母和孩子,比如账单和购买账单。我尝试在执行 bill 和 buybill 之间使用线程睡眠,但是当我将 10 个 buybill 添加到显示未找到异常 id 但 2 到 3 个 buybill 保存好的票据 id 时,这并不灵活 再次回来:您是否尝试在 BillRepository 中定义一个方法 findByInvoiceNo 并调用该方法?目前,您正在使用 invoiceNo 通过该账单的 ID 查找账单,而不是您在代码中使用的 invoice no。进一步请显示控制器的相关代码部分。目前很难找到对应的部分到期 是的,但只有在引用代码并插入一些数据但再次插入显示为空“BillRepository.findById(InvoiceNo)”的数据时完美工作时才会出现问题,我不知道为什么。 【参考方案2】:

我注意到在Bill 中你在invoiceId 上有@generatedValue。我认为您不能在非 @Id 字段上使用 @generatedValue 。见this post。

【讨论】:

谢谢,但事实并非如此,因为 invoiceNo 只是与账单 ID 异常无关的字段。我还检查了从账单中删除 InvoiceNo。但根本没有用。

以上是关于如果同时保存的两个实体父子实体映射为一对多关系,则抛出 id not found 父类异常的主要内容,如果未能解决你的问题,请参考以下文章

JPA的一对多,多对多用法

4.一对多关联映射

Hibernate多对多关系映射(建表)

关于JPA一对一,一对多(多对一),多对多的详解

hibernate 一对多 多对一映射关系

Hibernate 映射及查询