如何在 spring boot hibernate 中创建一对多关系

How to create one to many relationship in spring boot hibernate

我想在我的 spring boot hibernate 项目中创建一对多映射,例如客户有很多账单,账单有很多产品 如何创建实体 class 以及如何执行插入等 crud 操作,更新,删除。 请检查下面我要创建的关系图像。

谢谢。 enter image description here

enter code here 

这是我的 Customer.java Class :

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

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.SequenceGenerator;
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 String 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(Long id, String 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;
        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;
    }
    public Bill() {
        
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getInvoiceNo() {
        return InvoiceNo;
    }
    public void setInvoiceNo(String invoiceNo) {
        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;
    }
    
    
    
}
enter code here

这是我的购买Bill.java Class:

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

}

enter code here

这是我的 Customer、Bill、BuyBill 的 JPA 存储库:

package com.alpha.demo.Repository;

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

import com.alpha.demo.model.Customer;

public interface CustomerRepository extends JpaRepository<Customer, Long> {

}

package com.alpha.demo.Repository;

import java.util.List;

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 bill", nativeQuery = true)
    Long getNextSeriesId();

}


package com.alpha.demo.Repository;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.alpha.demo.model.BuyBill;

public interface BuyBillRepository extends JpaRepository<BuyBill, Long> {
    List<BuyBill> findByBillId(Long BillId);

}

enter code here

这是我的账单管理员:

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.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();
        // Long InvoiceNo = BillRepository.getNextSeriesId() + 1;
        // model.addAttribute("invoiceNo", InvoiceNo);
        model.addAttribute("invoiceNo", "1");
        return mv;
    }
    
    @PostMapping(value="/customers/{customerId}/bills/{InvoiceNo}/buyBills",produces="application/json",consumes="application/json")
    public ModelAndView addBuyBill(@PathVariable Long customerId, @PathVariable Long InvoiceNo,@Valid @RequestBody Bill bill,@Valid @RequestBody BuyBill buyBill) {
        return customerRepository.findById(customerId)
                    .map(customer -> {
                        bill.setCustomer(customer);
                        BillRepository.save(bill);
                        buyBill.setBill(bill); 
                        buyBillRepository.save(buyBill);
                        ModelAndView mv = new ModelAndView("redirect:/cust/customersBuyBill/{customerId}");
                        return mv;
                    }).orElseThrow(() -> new NotFoundException("Customer not found!"));
        }
    }   


enter code here

这是我的客户控制器:

package com.alpha.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;


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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import com.alpha.demo.Repository.CustomerRepository;
import com.alpha.demo.exception.NotFoundException;
import com.alpha.demo.helper.FileUploadHelper;
import com.alpha.demo.model.Customer;

@RestController
@RequestMapping("/cust")
public class CustomerController {
    
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private FileUploadHelper fileUploadHelper;
    
    //private final Path DIR = Paths.get("uploads");
    //String UPLOAD_DIR=new ClassPathResource("static/image/").getFile().getAbsolutePath();
    @GetMapping("/customer")
    public List<Customer> getAllCustomer() {
        return customerRepository.findAll();
   }
    

    @GetMapping("/customers")
    public ModelAndView getAllCustomers(Customer customer, Model model) {
        ModelAndView mv = new ModelAndView("showCustomers.html");
        long count_Customers = customerRepository.count();
        /*
         * for (int i = 0; i < count_Customers; i++) { System.out.println(i+1); long no
         * = i+1; model.addAttribute("no", no); }
         */
        //System.out.println(count_Customers);
        model.addAttribute("customer", customerRepository.findAll());
        model.addAttribute("count_Customers", count_Customers);
        return mv;
    }
    
    /*
     * @GetMapping("/student") public List<Student> getAllStudentsJson() {
     * 
     * return studentRepository.findAll(); }
     */
    
    
    @GetMapping("/customers/{id}")
    public Customer getCustomerByID(@PathVariable Long id) {
        Optional<Customer> optCustomer = customerRepository.findById(id);
        if(optCustomer.isPresent()) {
            return optCustomer.get();
        }else {
            throw new NotFoundException("Customer not found with id " + id);
        }
    }
    
    @PostMapping("/customersAdd")
    public ModelAndView createCustomer(@ModelAttribute @Valid @RequestBody @RequestParam("file") MultipartFile multipartFile, Customer customer, Model model) throws IOException {
        ModelAndView mv = new ModelAndView("redirect:/cust/customers");
        //System.out.println(multipartFile.getOriginalFilename());
     try {

         // validation
         if (multipartFile.isEmpty()) {
            ModelAndView mvc = new ModelAndView("redirect:/cust/customers");
            String img = File.separator+"first.jpg";
            customer.setPhotos(img);
             customerRepository.save(customer);
            model.addAttribute("customer", customer);
            //model.addAttribute("customer_error", customer);
             return mvc;
             
         }


         boolean f= fileUploadHelper.uploadFile(multipartFile);
         if(f)
         {
             
             // return ResponseEntity.ok("File is successfully uploaded");
            ServletUriComponentsBuilder.fromCurrentContextPath().path("/image/").path(multipartFile.getOriginalFilename()).toUriString();
            /*
             * System.out.println(a); System.out.println(fileUploadHelper.UPLOAD_DIR);
             * String b = StringUtils.cleanPath(multipartFile.getOriginalFilename());
             * System.out.println(b); String uploadRootPath =
             * servletContext.getContextPath();
             */
            //String n = new FileSystemResource("").getFile().getAbsolutePath();
            //System.out.println("uploadRoot=" + n);
            /* System.out.println("uploadRootPath=" + uploadRootPath); */
            String img = multipartFile.getOriginalFilename();
            customer.setPhotos(img);
            //ModelAndView mvc = new ModelAndView("redirect:/cust/customers");
            model.addAttribute("customer_success", customer);
            


         }

     } catch (Exception e) {
         e.printStackTrace();
     }

     customerRepository.save(customer);
        model.addAttribute("customer", customer);
  return mv;
    
        }
         
        
    @GetMapping("/customersUpdateImg/{id}")
    public ModelAndView  showCustomerUpdateImgForm(@PathVariable("id") long id, @ModelAttribute @Valid @RequestBody Customer customer,Model model) {
        ModelAndView mv = new ModelAndView("customerUpdateImgForm.html");
        
        Customer ct = customerRepository.findById(id)
          .orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
        System.out.println(ct.getId());
        System.out.println(ct.getFullName());
        //String v = StringUtils.replace(ct.getPhotos(), oldPattern, newPattern);
        //System.out.println(v);
        String Path = fileUploadHelper.UPLOAD_DIR;
        model.addAttribute("ct", ct);
        model.addAttribute("Path", Path);
        return mv;
    }
    
    @GetMapping("/edit/{id}")
    public ModelAndView  showUpdateForm(@PathVariable("id") long id, @ModelAttribute @Valid @RequestBody Customer customer,Model model) {
        ModelAndView mv = new ModelAndView("customerUpdateForm.html");
        
        Customer ct = customerRepository.findById(id)
          .orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
        System.out.println(ct.getId());
        System.out.println(ct.getFullName());
        model.addAttribute("ct", ct);
        return mv;
    }
    @PostMapping("/customersUpdateImage/{id}")
    //@RequestMapping(value = "/studentsUpdate/{id}", method = RequestMethod.POST)
    public ModelAndView updateCustomerImage(@RequestParam("file") MultipartFile multipartFile, @PathVariable Long id,@Valid Customer customerUpdated,Model model) {
        /*
         * return customerRepository.findById(id) .map(customer -> { try {
         * 
         * // validation if (multipartFile.isEmpty()) { ModelAndView mvc = new
         * ModelAndView("/cust/customersUpdateImg/{id}");
         * model.addAttribute("customer_error", customer); return mvc; }
         * 
         * 
         * boolean f= fileUploadHelper.uploadFile(multipartFile); if(f) {
         * 
         * // return ResponseEntity.ok("File is successfully uploaded");
         * ServletUriComponentsBuilder.fromCurrentContextPath().path("/image/").path(
         * multipartFile.getOriginalFilename()).toUriString(); String img =
         * File.separator+multipartFile.getOriginalFilename(); customer.setPhotos(img);
         * model.addAttribute("customer_success", customer); }
         * 
         * } catch (Exception e) { e.printStackTrace(); }
         * 
         * 
         * 
         * ModelAndView mv = new ModelAndView("redirect:/cust/customers");
         * customerRepository.save(customer); return mv; }).orElseThrow(() -> new
         * NotFoundException("Customer not found with id " + id));
         */
         return customerRepository.findById(id)
                 .map(customer -> {
                     try {

                         // validation
                         if (multipartFile.isEmpty()) {
                            ModelAndView mvc = new ModelAndView("redirect:/cust/customersUpdateImg/{id}");
                            model.addAttribute("customer_error", customer);
                            return mvc;
                             
                         }


                         boolean f= fileUploadHelper.uploadFile(multipartFile);
                         if(f)
                         {
                            String img = multipartFile.getOriginalFilename();
                            customer.setPhotos(img);
                            //ModelAndView mvc = new ModelAndView("redirect:/cust/customers");
                            model.addAttribute("customer_success", customer);
                            


                         }

                     } catch (Exception e) {
                         e.printStackTrace();
                     }
                     
                     ModelAndView mv = new ModelAndView("redirect:/cust/customers");
                     customerRepository.save(customer);
                     return mv;
                 }).orElseThrow(() -> new NotFoundException("Customer not found with id " + id));
        
    }
    @PostMapping("/customersUpdate/{id}")
    //@RequestMapping(value = "/studentsUpdate/{id}", method = RequestMethod.POST)
    public ModelAndView updateCustomer(@PathVariable Long id,
                                   @Valid Customer customerUpdated) {
        return customerRepository.findById(id)
                .map(customer -> {
                    customer.setFullName(customerUpdated.getFullName());
                    customer.setAadhaarNo(customerUpdated.getAadhaarNo());
                    customer.setGuarantor(customerUpdated.getGuarantor());
                    customer.setAddress(customerUpdated.getAddress());
                    customer.setNote(customerUpdated.getNote());
                    ModelAndView mv = new ModelAndView("redirect:/cust/customers");
                    customerRepository.save(customer);
                    return mv;
                }).orElseThrow(() -> new NotFoundException("Customer not found with id " + id));
    }
    
    @RequestMapping(value = "/customersDel/{id}", method = RequestMethod.GET)
  //  @DeleteMapping("/studentsDel/{id}")
    public ModelAndView deleteCustomer(@PathVariable Long id) {
        return customerRepository.findById(id)
                .map(customer -> {
                    customerRepository.delete(customer);
                    ModelAndView mv = new ModelAndView("redirect:/cust/customers");
                    return mv;
                }).orElseThrow(() -> new NotFoundException("Customer not found with id " + id));
    }
    

}
public class Customer {

    //...     
 
    @OneToMany(mappedBy="customer")
    private Set<Bill> bills;
    
    //...

}

public class Bill{

    //...     
 
    @OneToMany(mappedBy="bill")
    private Set<BuyBill> buybills;
    
    @ManyToOne
    @JoinColumn(name="customer_id", nullable=false)
    private Customer customer;
    //...

}

public class Bill{

    //...     
    
    @ManyToOne
    @JoinColumn(name="bill_id", nullable=false)
    private Bill bill;
    //...

}