0

My relationship like this which is shown in image : enter image description here

I'm having troubling with insert data in database because of bill id saved little bit late and that time also buybill save simultaneously in database and which want to bill id to save in relationship and throw exception like invoice id not found and only my bill data saved in database and buybill thrwo exception of not found bill id so please help me out.

Thanks,

And one more thing that i include that my postmapping of :

This--->

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

and

This--->

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

by two $http.post() simultaneously with one angularjs submit button in html.

This is my javascript code of post two http request by angular.js onclick of $scope.purchase function where there i post two url which mapped above URL1 and URL2 with json data and BillData, buyBillFormss.html code :

<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>

My code is here :

This is my customer.java entity :

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() {
    }

}

This is my Bill.java entity :

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 + "]";
    }
    
}

This is my BuyBill entity :

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;
    }

    
    

}

This is my JPA Repositories of bill :

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);

}

This is my bill Controller where i perform crud operations :

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!"));
        }
    
    }

Throw this exception : 5 Hibernate: select bill0_.id as id1_0_, bill0_.billing_date as billing_2_0_, bill0_.credibility_status as credibil3_0_, bill0_.due_amount as due_amou4_0_, bill0_.interest_rate as interest5_0_, bill0_.note as note6_0_, bill0_.paid_amount as paid_amo7_0_, bill0_.status as status8_0_, bill0_.total_amount as total_am9_0_, bill0_.total_discount_amount as total_d10_0_, bill0_.totalgstamount as totalgs11_0_, bill0_.total_interest_amount as total_i12_0_, bill0_.customer_id as custome15_0_, bill0_.guarantor_name as guarant13_0_, bill0_.invoice_no as invoice14_0_ from bills bill0_ where bill0_.invoice_no=? Optional.empty Hibernate: select bill0_.id as id1_0_, bill0_.billing_date as billing_2_0_, bill0_.credibility_status as credibil3_0_, bill0_.due_amount as due_amou4_0_, bill0_.interest_rate as interest5_0_, bill0_.note as note6_0_, bill0_.paid_amount as paid_amo7_0_, bill0_.status as status8_0_, bill0_.total_amount as total_am9_0_, bill0_.total_discount_amount as total_d10_0_, bill0_.totalgstamount as totalgs11_0_, bill0_.total_interest_amount as total_i12_0_, bill0_.customer_id as custome15_0_, bill0_.guarantor_name as guarant13_0_, bill0_.invoice_no as invoice14_0_ from bills bill0_ where bill0_.invoice_no=? 2021-01-27 16:58:05.945 WARN 7652 --- [nio-8083-exec-9] .w.s.m.a.ResponseStatusExceptionResolver : Resolved [com.alpha.demo.exception.NotFoundException: Invoice No not found!] Hibernate: select customer0_.id as id1_3_0_, customer0_.aadhaar_no as aadhaar_2_3_0_, customer0_.address as address3_3_0_, customer0_.create_date as create_d4_3_0_, customer0_.full_name as full_nam5_3_0_, customer0_.guarantor as guaranto6_3_0_, customer0_.mobile_no as mobile_n7_3_0_, customer0_.note as note8_3_0_, customer0_.photos as photos9_3_0_, customer0_.unique_id as unique_10_3_0_ from customers customer0_ where customer0_.id=? Hibernate: insert into bills (billing_date, credibility_status, due_amount, interest_rate, note, paid_amount, status, total_amount, total_discount_amount, totalgstamount, total_interest_amount, customer_id, guarantor_name, invoice_no) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)


Main problem ::

In Brief Bill id in "BillRepository.findById(InvoiceNo)" is empty when both bill and buybill save simultaneously.

Shyam Gupta
  • 27
  • 1
  • 9
  • Its a little bit complicated to find the relating parts, especially with all that commented out code. Could you please extract the relevant code lines which are performed? Your problem is that you `save(bill)` and after that you directly try to retrieve that bill by invoice no? Please clean up your posted code. Would be helpful – Daniel Rafael Wosch Jan 27 '21 at 06:20

2 Answers2

0

I notice that in Bill you have @generatedValue on invoiceId. I don't think you can use @generatedValue on a non @Id field. See this post.

Ari Ohsie
  • 66
  • 6
  • Thanks , But that is not the case because invoiceNo is only feild which is not relation with the bill id exception. i also checked with remove the InvoiceNo from bill. but did not work at all. – Shyam Gupta Jan 27 '21 at 04:29
0

I assume your exception occurs at this point?

// 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!"));

If so then you try to find a Bill by id (BillRepository.findById) but providing a invoiceNo instead of the concrete id

repository.findById refers to the @Id annotated column. In your case:

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

Therefore you need to use / implement the method findByInvoiceNo to get your concrete Bill by the provided invoiceNo instead of findById

Edit

Your Bill repository shall contain this method

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

and then

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!"));

Edit #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!"));
    }

Shouldn't it be

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

and in the Bill class:

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

Same goes for this part

 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!"));
        }

As customer holds none or more bills you need to add a synchronization method like before:

 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!"));
        }

And in customer

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

As you are using a bi-directional association you should keep them synchronized. Otherwise the state transitions of the entities may not work.

Sorry for the long term investigation. But the code makes it hard to identify.

You should definitely think about some refactoring. But this would go beyond the scope of this question.

  • Thanks! Yes you are right my problem in that portion of code "BillRepository.findById(InvoiceNo)" I try but nothing help full for me. – Shyam Gupta Jan 27 '21 at 09:52
  • Have you tried define a method `findByInvoiceNo` in your `BillRepository` and call that method instead? – Daniel Rafael Wosch Jan 27 '21 at 09:54
  • Problem is that InvoiceNo where save the buybill not found in bills database because of i saving both parent and child like bill and buybill save at a time. i try with thread sleep between execution of bill and buybill but this is no flexible when i add to 10 buybill to bill id that show exception id not found but 2 to 3 buybills saved ok – Shyam Gupta Jan 27 '21 at 09:58
  • To come back again: Have you tried define a method findByInvoiceNo in your BillRepository and call that method instead? Currently you are using the invoiceNo to find a Bill by the ID of that bill instead of the invoice no which you are using in the code. Further please show the relevant code parts of the controller. Currently it is hard to find the corresponding parts due – Daniel Rafael Wosch Jan 27 '21 at 10:00
  • yup define but there is problem only once the perfectly work when referesh the code and insert some data but again insert data that shows empty "BillRepository.findById(InvoiceNo)" i don't konw why. – Shyam Gupta Jan 27 '21 at 10:01
  • Then please edit your post and point out the code parts which are used to reproduce your problem with the corresponding invocation order. Currently its a little bit of stubbing in the dark. – Daniel Rafael Wosch Jan 27 '21 at 10:03
  • The method map(( bills) -> {}) is undefined for the type Bill this error show me on .map – Shyam Gupta Jan 27 '21 at 10:15
  • Thanks !!! I will edit then post for better understanding. – Shyam Gupta Jan 27 '21 at 10:25
  • I don't know why you don't answer the questions... Further your findById returns ONE entity. therefore this makes no sense `BillRepository.findById(InvoiceNo).map(bills -> { buyBill.setBill(bills); buyBillRepository.save(buyBill);` – Daniel Rafael Wosch Jan 27 '21 at 10:26
  • Thanks !!! but issue not solve may be request of both mapping same time inserted occure error. please looking into my http post and post mapping above – Shyam Gupta Jan 27 '21 at 13:06
  • See my updated Edit#2 ;). Further: Both endpoints are invoked simultaneously? – Daniel Rafael Wosch Jan 27 '21 at 13:17
  • Actually issue in bill and buybill portion customer has many bill worked fine because there customer already inserted and this customerId saved in bill entity but the problem is bill has many buybill like example product and bill no. and bill data and buybill(product) save at a time by ajax http post with single submit button which send two post request two server end and that post mapping work at a same time and bill data saved but the buybill looking for bill id which is not present and throw exception of not found. that is the scenario what i do ? help thanks. – Shyam Gupta Jan 27 '21 at 15:33
  • Sorry, but to be honest It is hard for me to follow what you are actually doing. if `public ModelAndView addBuyBillRequest` is executed before `public ModelAndView addBillRequest` how should a `Bill` exists as a `Bill` gets created AFAIU at `public ModelAndView addBillRequest` – Daniel Rafael Wosch Jan 27 '21 at 15:44
  • Any Idea What id do? – Shyam Gupta Jan 27 '21 at 16:30