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.
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.
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.
{
"data": [
{
"id": 4,
"customer_id": 3,
"service_type_id": 1,
"full_name": "Teja Babu S",
"email": "testemail#gmail.com",
camera_types": 1,
"dvr_types": 1,
"created_at": "2020-01-04 14:18:30",
"updated_at": "2020-01-04 14:18:30",
"camera_type": {
"id": 1,
"name": "Analogue hd",
"description": null,
"status": 1,
"deleted_at": null,
"created_at": "2020-01-04 08:03:45",
"updated_at": "2020-01-04 08:54:23"
},
"dvr_type": {
"id": 1,
"name": "XVR - nvr",
"description": "desc",
"status": 1,
"deleted_at": null,
"created_at": "2020-01-04 08:28:04",
"updated_at": "2020-01-04 08:57:17"
}
}
]
}
I am using the http://www.jsonschema2pojo.org/ for converion. I am not pasting the result to keep the question simple.
package - package
com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
ClassName - OrderDetailsResponse
Target language: Java
Source type: JSON
Annotation style: Moshi
I would like to access the Name from Both camera_type and dvr_type
I am using Moshi + retrofit
OrderDetail
package com.tesmachino.saycure;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.tesmachino.saycure.Auth.TokenManager;
import com.tesmachino.saycure.entities.OrderHistory.OrderDetail.OrderDetailsResponse;
import com.tesmachino.saycure.entities.OrderHistory.OrderHistoryResponse;
import com.tesmachino.saycure.entities.UserDetails.UserDetailsGetResponse;
import com.tesmachino.saycure.network.ApiService;
import com.tesmachino.saycure.network.RetrofitBuilder;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class OrderDetail extends AppCompatActivity {
ApiService service;
TokenManager tokenManager;
Call<OrderDetailsResponse> call;
private static final String TAG = "OrderDetail";
#BindView(R.id.orderdetails_id)
TextView orderId;
#BindView(R.id.orderdetails_client_name)
TextView orderDetailsClientName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_detail);
ButterKnife.bind(this);
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager);
}
#Override
protected void onResume() {
//Get the Data from the Intent
if (getIntent().hasExtra("order_id")) {
int order_id = getIntent().getIntExtra("order_id", 1);
Log.d(TAG, "IntentWorking" + order_id);
call = service.orderDetails(order_id);
call.enqueue(new Callback<OrderDetailsResponse>() {
#Override
public void onResponse(Call<OrderDetailsResponse> call, Response<OrderDetailsResponse> response) {
OrderDetailsResponse orderDetails = response.body();
if (orderDetails != null){
}
Log.w(TAG, "onResponse123: " + orderDetails.getData().get(0).getId());
Toast.makeText(OrderDetail.this, "" + response.body().toString(), Toast.LENGTH_SHORT).show();
orderId.setText(String.valueOf(orderDetails.getData().get(0).getId()));
orderDetailsClientName.setText(orderDetails.getData().get(0).getFullName());
Log.w(TAG, "onResponse45321: "+ orderDetails.getData().get(0).getCameraType());
}
#Override
public void onFailure(Call<OrderDetailsResponse> call, Throwable t) {
Log.w(TAG, "onFailure: " + t.getMessage());
Toast.makeText(OrderDetail.this, "Failure" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "There seems to be an error while fetching the Order Id. Please Try Again", Toast.LENGTH_SHORT).show();
}
super.onResume();
}
}
OrderDetailsResponse
package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
import com.squareup.moshi.Json;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.List;
public class OrderDetailsResponse {
#Json(name = "data")
private List<OrderDetailsGet> data = null;
public List<OrderDetailsGet> getData() {
return data;
}
public void setData(List<OrderDetailsGet> data) {
this.data = data;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("data", data).toString();
}
}
OrderDetailsGet
package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
import com.squareup.moshi.Json;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class OrderDetailsGet {
#Json(name = "id")
private Integer id;
#Json(name = "customer_id")
private Integer customerId;
#Json(name = "service_type_id")
private Integer serviceTypeId;
#Json(name = "full_name")
private String fullName;
#Json(name = "email")
private String email;
#Json(name = "address_line_1")
private String addressLine1;
#Json(name = "address_line_2")
private String addressLine2;
#Json(name = "phone_no")
private String phoneNo;
#Json(name = "alternate_phone_no")
private Object alternatePhoneNo;
#Json(name = "land_mark")
private Object landMark;
#Json(name = "area")
private Object area;
#Json(name = "district")
private String district;
#Json(name = "city")
private String city;
#Json(name = "state")
private String state;
#Json(name = "pincode")
private Integer pincode;
#Json(name = "type_of_property")
private Integer typeOfProperty;
#Json(name = "camera_types")
private Integer cameraTypes;
#Json(name = "no_of_cameras")
private Integer noOfCameras;
#Json(name = "dvr_types")
private Integer dvrTypes;
#Json(name = "dvr_channel")
private Integer dvrChannel;
#Json(name = "notes")
private Object notes;
#Json(name = "deleted_at")
private Object deletedAt;
#Json(name = "created_at")
private String createdAt;
#Json(name = "updated_at")
private String updatedAt;
#Json(name = "camera_type")
private CameraType cameraType;
#Json(name = "dvr_type")
private DvrType dvrType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Integer getServiceTypeId() {
return serviceTypeId;
}
public void setServiceTypeId(Integer serviceTypeId) {
this.serviceTypeId = serviceTypeId;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public Object getAlternatePhoneNo() {
return alternatePhoneNo;
}
public void setAlternatePhoneNo(Object alternatePhoneNo) {
this.alternatePhoneNo = alternatePhoneNo;
}
public Object getLandMark() {
return landMark;
}
public void setLandMark(Object landMark) {
this.landMark = landMark;
}
public Object getArea() {
return area;
}
public void setArea(Object area) {
this.area = area;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public Integer getTypeOfProperty() {
return typeOfProperty;
}
public void setTypeOfProperty(Integer typeOfProperty) {
this.typeOfProperty = typeOfProperty;
}
public Integer getCameraTypes() {
return cameraTypes;
}
public void setCameraTypes(Integer cameraTypes) {
this.cameraTypes = cameraTypes;
}
public Integer getNoOfCameras() {
return noOfCameras;
}
public void setNoOfCameras(Integer noOfCameras) {
this.noOfCameras = noOfCameras;
}
public Integer getDvrTypes() {
return dvrTypes;
}
public void setDvrTypes(Integer dvrTypes) {
this.dvrTypes = dvrTypes;
}
public Integer getDvrChannel() {
return dvrChannel;
}
public void setDvrChannel(Integer dvrChannel) {
this.dvrChannel = dvrChannel;
}
public Object getNotes() {
return notes;
}
public void setNotes(Object notes) {
this.notes = notes;
}
public Object getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public CameraType getCameraType() {
return cameraType;
}
public void setCameraType(CameraType cameraType) {
this.cameraType = cameraType;
}
public DvrType getDvrType() {
return dvrType;
}
public void setDvrType(DvrType dvrType) {
this.dvrType = dvrType;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("id", id).append("customerId", customerId).append("serviceTypeId", serviceTypeId).append("fullName", fullName).append("email", email).append("addressLine1", addressLine1).append("addressLine2", addressLine2).append("phoneNo", phoneNo).append("alternatePhoneNo", alternatePhoneNo).append("landMark", landMark).append("area", area).append("district", district).append("city", city).append("state", state).append("pincode", pincode).append("typeOfProperty", typeOfProperty).append("cameraTypes", cameraTypes).append("noOfCameras", noOfCameras).append("dvrTypes", dvrTypes).append("dvrChannel", dvrChannel).append("notes", notes).append("deletedAt", deletedAt).append("createdAt", createdAt).append("updatedAt", updatedAt).append("cameraType", cameraType).append("dvrType", dvrType).toString();
}
}
If you are just trying to the the name from camera_type and dvr_type, you can do:
//This assumes that you have a getCameraType & getDvrTypes method in your OrderDetailsGet class
String camera_name = orderDetails.getData().get(0).getCameraType().getName()
String dvr_name = orderDetails.getData().get(0).getDvrTypes().getName()
I created spring boot project where I am making rest application. I have used My SQL database and I am using spring data. There is one method which adds orders based on customer id. So I am not able to figure out it will work based on spring data query or custom query and how it will be?
I have attached required codes only,
Customer.java
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "customers")
#NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "cust_ID_PK")
#GeneratedValue(strategy = GenerationType.AUTO)
private int custIDPK;
#Column(name = "billing_city")
private String billingCity;
#Column(name = "billing_country")
private String billingCountry;
#Column(name = "billing_state")
private String billingState;
#Column(name = "billing_street")
private String billingStreet;
#Column(name = "billing_zip")
private String billingZip;
private String company;
#Column(name = "display_name")
private String displayName;
private String email;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "other_details")
private String otherDetails;
#Column(name = "print_on_check_as")
private String printOnCheckAs;
#Column(name = "shipping_city")
private String shippingCity;
#Column(name = "shipping_country")
private String shippingCountry;
#Column(name = "shipping_state")
private String shippingState;
#Column(name = "shipping_street")
private String shippingStreet;
#Column(name = "shipping_zip")
private String shippingZip;
private String suffix;
private String title;
// bi-directional many-to-one association to Order
#OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private List<Order> orders;
public Customer() {
}
public int getCustIDPK() {
return this.custIDPK;
}
public void setCustIDPK(int cust_ID_PK) {
this.custIDPK = cust_ID_PK;
}
public String getBillingCity() {
return this.billingCity;
}
public void setBillingCity(String billingCity) {
this.billingCity = billingCity;
}
public String getBillingCountry() {
return this.billingCountry;
}
public void setBillingCountry(String billingCountry) {
this.billingCountry = billingCountry;
}
public String getBillingState() {
return this.billingState;
}
public void setBillingState(String billingState) {
this.billingState = billingState;
}
public String getBillingStreet() {
return this.billingStreet;
}
public void setBillingStreet(String billingStreet) {
this.billingStreet = billingStreet;
}
public String getBillingZip() {
return this.billingZip;
}
public void setBillingZip(String billingZip) {
this.billingZip = billingZip;
}
public String getCompany() {
return this.company;
}
public void setCompany(String company) {
this.company = company;
}
public String getDisplayName() {
return this.displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getOtherDetails() {
return this.otherDetails;
}
public void setOtherDetails(String otherDetails) {
this.otherDetails = otherDetails;
}
public String getPrintOnCheckAs() {
return this.printOnCheckAs;
}
public void setPrintOnCheckAs(String printOnCheckAs) {
this.printOnCheckAs = printOnCheckAs;
}
public String getShippingCity() {
return this.shippingCity;
}
public void setShippingCity(String shippingCity) {
this.shippingCity = shippingCity;
}
public String getShippingCountry() {
return this.shippingCountry;
}
public void setShippingCountry(String shippingCountry) {
this.shippingCountry = shippingCountry;
}
public String getShippingState() {
return this.shippingState;
}
public void setShippingState(String shippingState) {
this.shippingState = shippingState;
}
public String getShippingStreet() {
return this.shippingStreet;
}
public void setShippingStreet(String shippingStreet) {
this.shippingStreet = shippingStreet;
}
public String getShippingZip() {
return this.shippingZip;
}
public void setShippingZip(String shippingZip) {
this.shippingZip = shippingZip;
}
public String getSuffix() {
return this.suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Order> getOrders() {
return this.orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
public Order addOrder(Order order) {
getOrders().add(order);
order.setCustomer(this);
return order;
}
public Order removeOrder(Order order) {
getOrders().remove(order);
order.setCustomer(null);
return order;
}
}
Order.java
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#Entity
#Table(name = "orders")
#NamedQuery(name = "Order.findAll", query = "SELECT o FROM Order o")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "order_ID_PK")
#GeneratedValue(strategy = GenerationType.AUTO)
private int order_ID_PK;
#Column(name = "custom_message")
private String customMessage;
#Temporal(TemporalType.DATE)
#Column(name = "delivery_due_date")
private Date deliveryDueDate;
#Temporal(TemporalType.DATE)
#Column(name = "invoice_creation_date")
private Date invoiceCreationDate;
#Temporal(TemporalType.DATE)
#Column(name = "payment_due_date")
private Date paymentDueDate;
// bi-directional many-to-one association to Customer
#ManyToOne
#JoinColumn(name = "cust_ID_FK")
private Customer customer;
// bi-directional many-to-many association to Product
#ManyToMany(mappedBy = "orders")
private List<Product> products;
public Order() {
}
public int getOrder_ID_PK() {
return this.order_ID_PK;
}
public void setOrder_ID_PK(int order_ID_PK) {
this.order_ID_PK = order_ID_PK;
}
public String getCustomMessage() {
return this.customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
public Date getDeliveryDueDate() {
return this.deliveryDueDate;
}
public void setDeliveryDueDate(Date deliveryDueDate) {
this.deliveryDueDate = deliveryDueDate;
}
public Date getInvoiceCreationDate() {
return this.invoiceCreationDate;
}
public void setInvoiceCreationDate(Date invoiceCreationDate) {
this.invoiceCreationDate = invoiceCreationDate;
}
public Date getPaymentDueDate() {
return this.paymentDueDate;
}
public void setPaymentDueDate(Date paymentDueDate) {
this.paymentDueDate = paymentDueDate;
}
public Customer getCustomer() {
return this.customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
OrderOperation.java
package com.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.model.Order;
public interface OrderOperation extends JpaRepository<Order, Long> {
#Query("SELECT c.orders FROM Customer c where c.custIDPK = :id")
public List<Order> findOrderbyID(#Param("id") int id);
}
CustomerController.java
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
ICutomerService customerDAO;
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = { "/", "" }, method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<?> getAllCustomer() {
return new ResponseEntity(customerDAO.getAllCustomer(), HttpStatus.ACCEPTED);
}
#RequestMapping(value = "/{CustomerById}", method = RequestMethod.GET, produces = { "application/json" })
public Customer getCustomerbyId(#PathVariable("CustomerById") String cid) {
return customerDAO.findCustomerById(Integer.parseInt(cid));
}
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = "{CustomerById}/order", method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<?> getAllOrder(#PathVariable("CustomerById") String cid) {
return new ResponseEntity(customerDAO.getOrdersbyId(Integer.parseInt(cid)), HttpStatus.ACCEPTED);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#RequestMapping(value = "order/{CustomerById}/product", method = RequestMethod.GET, produces = {
"application/json" })
public ResponseEntity<?> getAllProduct(#PathVariable("CustomerById") String cid) {
return new ResponseEntity(customerDAO.getProductsById(Integer.parseInt(cid)), HttpStatus.ACCEPTED);
}
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<?> addCustomer(#RequestBody Customer c) {
boolean flag = customerDAO.addCustomer(c);
if (flag)
return new ResponseEntity(HttpStatus.CREATED);
else
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/{CustomerById}/orders", method = RequestMethod.POST)
public ResponseEntity<?> addOrders(#PathVariable("CustomerById") String cid, #RequestBody Order c) {
// c.getCustomer().setCustIDPK(Integer.parseInt(cid));
boolean flag = customerDAO.addOrder(c);
if (flag) {
return new ResponseEntity(HttpStatus.CREATED);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
How should I design this addOrders method?
If you are using Spring Data then you will need to create a CrudRepository for each table you which to access. The CrudRepository allows you to easily manipulate data in your table using standard ORM practices. Here is a link with more details.
For more detailed info on how to use Spring Data check out this wonderful guide. This guide has become indispensable when working with Spring Data.
There are many options to this but i have used below approach so hope it helps you. The #Query annotation allows to execute native queries by setting the nativeQuery flag to true.
#Query(value = "select o.* from customer c inner join order o on c.customer_id = o.customer_id where o. = ?1", nativeQuery = true)
Please write sql according to your requirement.
I want to order the data descending in hibernate,
but not working at all,
this is my code,
#SuppressWarnings("unchecked")
#Override
public List<MPNValas> listAllMPNValas() throws Exception{
DetachedCriteria criteria = DetachedCriteria.forClass(MPNValas.class);
criteria.addOrder(Order.desc("ID"));
List<MPNValas> mpnvalasList = getHibernateTemplate().findByCriteria(criteria);
return mpnvalasList;
}
this is my controller,
#RequestMapping("/admin/mpn-valas.html")
public ModelAndView listMPNValas(ModelMap model)throws Exception
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String sessionUser = user.getUsername();
try{
UserAdmin dataUser = userService.get(sessionUser);
model.addAttribute("userData", dataUser);
} catch(Exception e){
e.printStackTrace();
}
ModelAndView mav = new ModelAndView("mpnvalas");
List<MPNValas> mpnvalas = mpnvalasService.listAllMPNValas();
mav.addObject("mpnvalas", mpnvalas);
return mav;
}
and this is the class,
package prod.support.model.gwprod;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="LOOKUP")
public class MPNValas {
private Integer ID;
private String TIPE;
private String KODE_PERUSAHAAN;
private String CODE;
private String NAME;
private String VALUE;
#Id
#Column(name="ID", unique=true, nullable=false)
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
#Column(name="TIPE")
public String getTIPE() {
return TIPE;
}
public void setTIPE(String TIPE) {
this.TIPE = TIPE;
}
#Column(name="KODE_PERUSAHAAN")
public String getKODE_PERUSAHAAN() {
return KODE_PERUSAHAAN;
}
public void setKODE_PERUSAHAAN(String KODE_PERUSAHAAN) {
this.KODE_PERUSAHAAN = KODE_PERUSAHAAN;
}
#Column(name="CODE")
public String getCODE() {
return CODE;
}
public void setCODE(String CODE) {
this.CODE = CODE;
}
#Column(name="NAME")
public String getNAME() {
return NAME;
}
public void setNAME(String NAME) {
this.NAME = NAME;
}
#Column(name="VALUE")
public String getVALUE() {
return VALUE;
}
public void setVALUE(String VALUE) {
this.VALUE = VALUE;
}
/**
* #param args
*/
}
and this the list of data
that I miss something??
any help will be pleasure :))
You miss nothing, just note that the argument to the desc method is case sensitive and should match the name of the attribute to sort by.
Criteria criteria = session.createCriteria(Foo.class, "FOO");
criteria.addOrder(Order.desc("id"));
Good day! I'm having a problem when updating an entity. When I click the "update" button, the changes are saved. However, when I go a different page, the recently changed (or added) items are there but the old items (that should be changed or removed) are also there. Particularly the relatedTags (the name and notes are updating just fine). Why is it not persistent or permanent?
Here is where the updating happens.
Form<Tag> filledForm = tagForm.fill(Tag.find.byId(id)).bindFromRequest();
Tag editedTag = RelatedTag.findTag(id);
if(filledForm.hasErrors()) {
return badRequest(editTagForm.render(user, editedTag, filledForm, tags));
}
else {
List<RelatedTag> relatedTagsAlloc = new ArrayList<RelatedTag>();
java.util.Map<String, String[]> map = request().body().asFormUrlEncoded();
String[] relatedTags = map.get("relatedTags.tag.name");
String[] relationship = map.get("relatedTags.relationship");
String[] relatedNotes = map.get("relatedTags.relatedNotes");
if (relatedTags != null) {
for (int i = 0; i < relatedTags.length; i++) {
if (RelatedTag.exists(relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "))) {
relatedTagsAlloc.add(RelatedTag.findByLabel(
relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "), relationship[i], relatedNotes[i].trim()));
} else {
Tag unknown = new Tag(relatedTags[i], "");
Tag.create(unknown);
relatedTagsAlloc.add(RelatedTag.findByLabel(
relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "), relationship[i], relatedNotes[i].trim()));
}
}
editedTag.getRelatedTags().clear();
}
editedTag.setName(filledForm.get().getName().toLowerCase().replaceAll("\\s+", " "));
editedTag.setRelatedTags(relatedTagsAlloc);
editedTag.update();
Application.log(user, editedTag, action);
writeToFile(editedTag);
return ok(summary.render(user, editedTag));
}
And here are the models:
Tag model:
package models;
import java.sql.Timestamp;
import java.util.*;
import javax.persistence.*;
import javax.validation.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import scala.Int;
#Entity
public class Tag extends Model{
#Id
private int id;
#Required
#MaxLength(value=100)
#Column(unique=true)
private String name;
#MaxLength(value=200)
private String notes;
#OneToMany(cascade=CascadeType.ALL)
public List<RelatedTag> relatedTags = new ArrayList<RelatedTag>();
#Version
public Timestamp lastUpdate;
public static Finder<Integer, Tag> find = new Finder(Int.class, Tag.class);
public Tag() {
}
public Tag(String name, String notes){
this.name = name;
this.notes = notes;
}
public Tag(int id, String name, String notes, List<RelatedTag> relatedTags) {
this.id = id;
this.name = name;
this.notes = notes;
this.relatedTags = relatedTags;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public List<RelatedTag> getRelatedTags() {
return relatedTags;
}
public void setRelatedTags(List<RelatedTag> relatedTags) {
this.relatedTags = relatedTags;
}
public static List<Tag> all() {
return find.all();
}
public static void create(Tag tag){
tag.save();
}
public static void delete(int id){
find.ref(id).delete();
}
public static void update(int id, Tag tag) {
tag.update(id); // updates this entity, by specifying the entity ID
}
public static boolean exists(Tag newTag) {
for(Tag allTags : Tag.find.all()) {
if(allTags.getName().equals(newTag.getName()))
return true;
}
return false;
}
}
RelatedTag model
package models;
import java.sql.Timestamp;
import java.util.*;
import javax.persistence.*;
import javax.validation.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import scala.Int;
#Entity
public class RelatedTag extends Model {
#Id
public int rtID;
private int id; //same as Tag's id
private String relationship;
private String relatedNotes;
#Version
public Timestamp lastUpdate;
public RelatedTag() {}
public RelatedTag(int id, String relationship, String relatedNotes) {
this.id = id;
this.relationship = relationship;
this.relatedNotes = relatedNotes;
}
public void setId(int id){
this.id = id;
}
public void setRelationship(String relationship){
this.relationship = relationship;
}
public void setRelatedNotes(String relatedNotes) {
this.relatedNotes = relatedNotes;
}
public int getId(){
return id;
}
public String getRelationship(){
return relationship;
}
public String getRelatedNotes() {
return relatedNotes;
}
public static void create(List<RelatedTag> rt){
((Model) rt).save();
}
public static boolean exists(String tagRelated) {
for(Tag tag : Tag.find.all()) {
if(tagRelated.equals(tag.getName()))
return true;
}
return false;
}
public static RelatedTag findByLabel(String tagRelated, String relation, String relatedNotes) {
RelatedTag relatedTag = null;
for(Tag tag : Tag.find.all()) {
if(tagRelated.equals(tag.getName())) {
relatedTag = new RelatedTag(tag.getId(), relation, relatedNotes);
}
}
return relatedTag;
}
public static Tag findTag(int id) {
for(Tag tag : Tag.find.all()) {
if(id == tag.getId())
return tag;
}
return null;
}
}
What have I been doing wrong? Please help me fix this. Thank you very much!