Related
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.
I'm using JHipster and I'm running the following curl command:
POST/api/gang-users
with body:
{
"role": "member",
"gang": "3",
"user": "1"
}
but I get the following error:
JSON parse error: Cannot construct instance of
com.getgreetapp.greetapp.domain.User (although at least one Creator
exists): no String-argument constructor/factory method to deserialize
from String value ('1'); nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
construct instance of com.getgreetapp.greetapp.domain.User (although
at least one Creator exists): no String-argument constructor/factory
method to deserialize from String value ('1')\n at [Source:
(PushbackInputStream); line: 4, column: 10] (through reference chain:
com.getgreetapp.greetapp.domain.GangUser[\"user\"])
GangUserResource createGangUser
#PostMapping("/gang-users")
#Timed
public ResponseEntity<GangUser> createGangUser(#Valid #RequestBody GangUser gangUser) throws URISyntaxException {
log.debug("REST request to save GangUser : {}", gangUser);
if (gangUser.getId() != null) {
throw new BadRequestAlertException("A new gangUser cannot already have an ID", ENTITY_NAME, "idexists");
}
User user = userRepository.findById(gangUser.getUser());
GangUser result = gangUserRepository.save(gangUser);
return ResponseEntity.created(new URI("/api/gang-users/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
GangUser
package com.getgreetapp.greetapp.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A GangUser.
*/
#Entity
#Table(name = "gang_user")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class GangUser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name = "jhi_role", nullable = false)
private String role;
#ManyToOne
private Gang gang;
#ManyToOne
private User user;
public GangUser() {
}
public GangUser(String role, Gang gang, User user)
{
this.role = role;
this.gang = gang;
this.user = user;
}
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRole() {
return role;
}
public GangUser role(String role) {
this.role = role;
return this;
}
public void setRole(String role) {
this.role = role;
}
public Gang getGang() {
return gang;
}
public GangUser gang(Gang gang) {
this.gang = gang;
return this;
}
public void setGang(Gang gang) {
this.gang = gang;
}
public User getUser() {
return user;
}
public GangUser user(User user) {
this.user = user;
return this;
}
public void setUser(User user) {
this.user = user;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GangUser gangUser = (GangUser) o;
if (gangUser.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), gangUser.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "GangUser{" +
"id=" + getId() +
", role='" + getRole() + "'" +
"}";
}
}
User
package com.getgreetapp.greetapp.domain;
import com.getgreetapp.greetapp.config.Constants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.validation.constraints.Email;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.time.Instant;
/**
* A user.
*/
#Entity
#Table(name = "jhi_user")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Pattern(regexp = Constants.LOGIN_REGEX)
#Size(min = 1, max = 50)
#Column(length = 50, unique = true, nullable = false)
private String login;
#JsonIgnore
#NotNull
#Size(min = 60, max = 60)
#Column(name = "password_hash", length = 60, nullable = false)
private String password;
#Size(max = 50)
#Column(name = "first_name", length = 50)
private String firstName;
#Size(max = 50)
#Column(name = "last_name", length = 50)
private String lastName;
#Email
#Size(min = 5, max = 254)
#Column(length = 254, unique = true)
private String email;
#NotNull
#Column(nullable = false)
private boolean activated = false;
#Size(min = 2, max = 6)
#Column(name = "lang_key", length = 6)
private String langKey;
#Size(max = 256)
#Column(name = "image_url", length = 256)
private String imageUrl;
#Size(max = 20)
#Column(name = "activation_key", length = 20)
#JsonIgnore
private String activationKey;
#Size(max = 20)
#Column(name = "reset_key", length = 20)
#JsonIgnore
private String resetKey;
#Column(name = "reset_date")
private Instant resetDate = null;
#JsonIgnore
#ManyToMany
#JoinTable(
name = "jhi_user_authority",
joinColumns = {#JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {#JoinColumn(name = "authority_name", referencedColumnName = "name")})
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
public User() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean getActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return !(user.getId() == null || getId() == null) && Objects.equals(getId(), user.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
Gang
package com.getgreetapp.greetapp.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;
/**
* A Gang.
*/
#Entity
#Table(name = "gang")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Gang implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name = "name", nullable = false)
private String name;
#NotNull
#Column(name = "description", nullable = false)
private String description;
#NotNull
#Column(name = "longitude", precision = 10, scale = 2, nullable = false)
private BigDecimal longitude;
#NotNull
#Column(name = "latitude", precision = 10, scale = 2, nullable = false)
private BigDecimal latitude;
#NotNull
#Column(name = "membership_approval", nullable = false)
private String membershipApproval;
#NotNull
#Column(name = "privacy", nullable = false)
private String privacy;
public Gang() {}
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public Gang name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public Gang description(String description) {
this.description = description;
return this;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getLongitude() {
return longitude;
}
public Gang longitude(BigDecimal longitude) {
this.longitude = longitude;
return this;
}
public void setLongitude(BigDecimal longitude) {
this.longitude = longitude;
}
public BigDecimal getLatitude() {
return latitude;
}
public Gang latitude(BigDecimal latitude) {
this.latitude = latitude;
return this;
}
public void setLatitude(BigDecimal latitude) {
this.latitude = latitude;
}
public String getMembershipApproval() {
return membershipApproval;
}
public Gang membershipApproval(String membershipApproval) {
this.membershipApproval = membershipApproval;
return this;
}
public void setMembershipApproval(String membershipApproval) {
this.membershipApproval = membershipApproval;
}
public String getPrivacy() {
return privacy;
}
public Gang privacy(String privacy) {
this.privacy = privacy;
return this;
}
public void setPrivacy(String privacy) {
this.privacy = privacy;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Gang gang = (Gang) o;
if (gang.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), gang.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "Gang{" +
"id=" + getId() +
", name='" + getName() + "'" +
", description='" + getDescription() + "'" +
", longitude=" + getLongitude() +
", latitude=" + getLatitude() +
", membershipApproval='" + getMembershipApproval() + "'" +
", privacy='" + getPrivacy() + "'" +
"}";
}
}
In my humble opinion, there are a couple of things to check.
First, it isn't recommended to use the same object to store data in your database and response a request. The data object could be GangUser, User and Gang, while the response objects GangUserApi, UserApi, and GangApi. With this approach, you'll be able to amend a layer without modifying another.
Second, your service is expecting a GangUser with a User inside. The same User Object that you use to store it in the database. You're just sending a String ("1") instead of an object there.
A quick solution could be modifying the JSON:
{
"role": "member",
"gang": "3",
"user": {
"id":"1"
}
}
But I would like to know if you understand what was going on. That is more important than just give you a quick solution.
Cheers.
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've been stuck here for almost a week trying find the answer on the internet but sadly nothing worked. :( Everytime I try to update using this method:
private Tenant updateTenantWithApplicationProperties(List<TenantApplicationProperty> newTenantApplicationProperties, String tenantId) {
String reason = "Update application properties.";
Tenant existingTenant = tenantRepository.findById(tenantId);
List<TenantApplicationProperty> temp = existingTenant.getTenantApplicationProperties();
existingTenant.setTenantApplicationProperties(newTenantApplicationProperties);
setApplicationPropertiesUpdateValues(temp, existingTenant);
if(newTenantApplicationProperties != null && newTenantApplicationProperties.size() != 0) {
Tenant savedTenantWithAppProps = saveTenantWithLog(existingTenant, reason);
return savedTenantWithAppProps;
}
return existingTenant;
}
Im always getting this error:
javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.infor.ecom.tenant.manager.model.entity.ApplicationProperty
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1361)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1295)
at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:876)
But when Im using this method it works fine:
public Tenant updateTenant(Tenant tenant) {
List<Database> databases = tenant.getDatabases();
List<Administrator> administrators = tenant.getAdministrators();
validateUpdateTenant(tenant);
validateDatabases(databases);
validateAdministrators(administrators);
Tenant existingTenant = findByIdWithAllDetails(tenant.getId());
List<Database> listExistingDatabases = existingTenant.getDatabases();
Database existingEcomDb = getDatabaseByType(listExistingDatabases,
TenantManagerConstants.ECOM_DATASOURCE);
setDatabaseUpdateValues(listExistingDatabases, tenant);
setAdministratorsUpdateValues(existingTenant.getAdministrators(),
tenant);
setProductUpdateValue(existingTenant.getProduct(), tenant);
setApplicationPropertiesUpdateValues(existingTenant.getTenantApplicationProperties(), tenant);
setEcomDBParamsDefaultValues(tenant);
setAdministratorDefaultValues(tenant);
Database updateEcomDb = getDatabaseByType(tenant.getDatabases(),
TenantManagerConstants.ECOM_DATASOURCE);
Boolean shouldInstallNewDB = true;
if (existingEcomDb.getName().equalsIgnoreCase(updateEcomDb.getName())
&& existingEcomDb.getHost().equalsIgnoreCase(
updateEcomDb.getHost())
&& existingEcomDb.getPort().equals(updateEcomDb.getPort())) {
shouldInstallNewDB = false;
} else {
testEcomDBConnection(updateEcomDb);
}
int ecomDbTableCount = getEcomDBTableCount(updateEcomDb);
String[][] languages = formatAndValidateLanguages(updateEcomDb
.getEcomDatabaseParameters().getLanguages());
Tenant updatedTenant = saveExistingTenant(tenant);
if (updatedTenant != null) {
if (shouldInstallNewDB || ecomDbTableCount == 0) {
installDatabase(updateEcomDb, languages, updatedTenant);
} else {
updateDatabase(updateEcomDb, languages, updatedTenant);
}
storageService.updateTenantFolderStructure(updatedTenant);
} else {
throw new TenantManagerException(
ApiMessageConstants.M_TENANT_PROVISION_ERROR,
ApiMessageConstants.C_TENANT_PROVISION_ERROR);
}
return updatedTenant;
}
So here is my complete codes:
Tenant.java
package com.infor.ecom.tenant.manager.model.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import com.infor.ecom.tenant.manager.constant.TenantManagerConstants;
import com.infor.ecom.tenant.manager.constant.TenantStatusEnum;
#Entity
#Table(name="tenant")
#XmlRootElement(name = "Tenant",namespace = "http://com.infor.ecom.tenant.manager/Tenant")
public class Tenant extends BaseModel {
private static final long serialVersionUID = -6687293822212120396L;
#Id
private String id;
private String displayName;
private String description;
private String url;
private String apiKey;
private String status;
#OneToMany(mappedBy = "tenant", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Database> databases;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Activity> activites;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Administrator> administrators;
private String message;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<TenantApplicationProperty> tenantApplicationProperties;
#OneToOne(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private Product product;
public Database findEcomDatabase() {
Database database = null;
if(databases != null) {
for(Database db : databases) {
if(db.getDatasource() != null) {
if(TenantManagerConstants.ECOM_DATASOURCE.equals(db.getDatasource().getName())) {
database = db;
break;
}
}
}
}
return database;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getStatus() {
return status;
}
public void setStatus(TenantStatusEnum statusEnum) {
this.status = statusEnum.name();
}
public List<Database> getDatabases() {
return databases;
}
public void setDatabases(List<Database> databases) {
this.databases = databases;
}
public void addDatabase(Database database) {
if (this.databases == null) {
this.databases = new ArrayList<Database>();
}
database.setTenant(this);
this.databases.add(database);
}
public List<Activity> getActivites() {
return activites;
}
public void setActivites(List<Activity> activities) {
this.activites = activities;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setStatus(String status) {
this.status = status;
}
public List<Administrator> getAdministrators() {
return this.administrators;
}
public void setAdministrators(List<Administrator> administrators) {
for (Administrator admin:administrators) {
admin.setTenant(this);
}
this.administrators = administrators;
}
public void addAdministrator(Administrator administrator) {
if (this.administrators == null) {
this.administrators = new ArrayList<Administrator>();
}
administrator.setTenant(this);
this.administrators.add(administrator);
}
public List<TenantApplicationProperty> getTenantApplicationProperties() {
return tenantApplicationProperties;
}
public void setTenantApplicationProperties(
List<TenantApplicationProperty> tenantApplicationProperties) {
this.tenantApplicationProperties = tenantApplicationProperties;
}
public void addTenantApplicationProperty(TenantApplicationProperty tenantApplicationProperty) {
if (this.tenantApplicationProperties == null) {
this.tenantApplicationProperties = new ArrayList<TenantApplicationProperty>();
}
tenantApplicationProperty.setTenant(this);
this.tenantApplicationProperties.add(tenantApplicationProperty);
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
product.setTenant(this);
this.product = product;
}
}
TenantApplicationProperty.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.infor.ecom.tenant.manager.model.entity.pk.TenantApplicationPropertyPK;
#Entity
#Table(name = "tenant_application_property")
#IdClass(TenantApplicationPropertyPK.class)
public class TenantApplicationProperty extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name = "tenant_id")
private Tenant tenant;
#Id
#OneToOne
#JoinColumn(name = "application_property_id")
private ApplicationProperty applicationProperty;
private String value;
public TenantApplicationProperty() {
super();
}
/**
* Added constructor to handle custom query for
* findByTenantIdApplicationPropertyName. No need to retrieve Tenant and
* ApplicationProperty
*
* #param value
*/
public TenantApplicationProperty(String value) {
setTenant(null);
setApplicationProperty(null);
setValue(value);
}
public Tenant getTenant() {
return tenant;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
public ApplicationProperty getApplicationProperty() {
return applicationProperty;
}
public void setApplicationProperty(ApplicationProperty applicationProperty) {
this.applicationProperty = applicationProperty;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((applicationProperty == null) ? 0 : applicationProperty
.hashCode());
return result;
}
#Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
TenantApplicationProperty tenantAppProp = (TenantApplicationProperty) object;
if (applicationProperty == null) {
if (tenantAppProp.applicationProperty != null) {
return false;
}
} else if (!applicationProperty.getApplicationPropertyGroup().getName().equals(tenantAppProp.applicationProperty.getApplicationPropertyGroup().getName())
|| !applicationProperty.getName().equals(tenantAppProp.applicationProperty.getName())) {
return false;
}
return true;
}
}
TenanatApplicationPropertyPK.java
package com.infor.ecom.tenant.manager.model.entity.pk;
public class TenantApplicationPropertyPK implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String tenant;
private Integer applicationProperty;
public String getTenantId() {
return tenant;
}
public void setTenantId(String tenant) {
this.tenant = tenant;
}
public Integer getApplicationPropertyId() {
return applicationProperty;
}
public void setApplicationPropertyId(Integer applicationProperty) {
this.applicationProperty = applicationProperty;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((applicationProperty == null) ? 0 : applicationProperty
.hashCode());
result = prime * result + ((tenant == null) ? 0 : tenant.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TenantApplicationPropertyPK tenantAppPropPK = (TenantApplicationPropertyPK) obj;
if (applicationProperty == null) {
if (tenantAppPropPK.applicationProperty != null) {
return false;
}
} else if (!applicationProperty
.equals(tenantAppPropPK.applicationProperty)) {
return false;
}
if (tenant == null) {
if (tenantAppPropPK.tenant != null) {
return false;
}
} else if (!tenant.equals(tenantAppPropPK.tenant)) {
return false;
}
return true;
}
}
ApplicationProperty.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "application_property")
public class ApplicationProperty extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String defaultValue;
private boolean isVisible;
private boolean clientVisible;
#OneToOne
#JoinColumn(name = "property_group_id")
private ApplicationPropertyGroup applicationPropertyGroup;
#OneToOne
#JoinColumn(name = "property_type_id")
private ApplicationPropertyType applicationPropertyType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public boolean getIsVisible() {
return isVisible;
}
public void setIsVisible(boolean isVisible) {
this.isVisible = isVisible;
}
public boolean getClientVisible() {
return clientVisible;
}
public void setClientVisible(boolean clientVisible) {
this.clientVisible = clientVisible;
}
public ApplicationPropertyGroup getApplicationPropertyGroup() {
return applicationPropertyGroup;
}
public void setApplicationPropertyGroup(ApplicationPropertyGroup applicationPropertyGroup) {
this.applicationPropertyGroup = applicationPropertyGroup;
}
public ApplicationPropertyType getApplicationPropertyType() {
return applicationPropertyType;
}
public void setApplicationPropertyType(ApplicationPropertyType applicationPropertyType) {
this.applicationPropertyType = applicationPropertyType;
}
}
ApplicationPropertyGroup.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "application_property_group")
public class ApplicationPropertyGroup extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ApplicationPropertyType.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "application_property_type")
public class ApplicationPropertyType extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
TenantServiceImpl.java
private Tenant updateTenantWithApplicationProperties(List<TenantApplicationProperty> newTenantApplicationProperties, String tenantId) {
String reason = "Update application properties.";
Tenant existingTenant = tenantRepository.findById(tenantId);
List<TenantApplicationProperty> temp = existingTenant.getTenantApplicationProperties();
existingTenant.setTenantApplicationProperties(newTenantApplicationProperties);
setApplicationPropertiesUpdateValues(temp, existingTenant);
if(newTenantApplicationProperties != null && newTenantApplicationProperties.size() != 0) {
Tenant savedTenantWithAppProps = saveTenantWithLog(existingTenant, reason);
return savedTenantWithAppProps;
}
return existingTenant;
}
private Tenant saveTenantWithLog(Tenant tenant, String reason) {
Tenant updatedTenant = tenantRepository.save(tenant);
TenantLog tenantLog = new TenantLog();
tenantLog.setTenantId(updatedTenant.getId());
tenantLog.setDisplayName(updatedTenant.getDisplayName());
tenantLog.setDescription(updatedTenant.getDescription());
tenantLog.setUrl(updatedTenant.getUrl());
tenantLog.setApiKey(updatedTenant.getApiKey());
tenantLog.setStatus(TenantStatusEnum.valueOf(updatedTenant.getStatus()));
tenantLog.setReason(reason);
tenantLog.setMessage(updatedTenant.getMessage());
tenantLogRepository.save(tenantLog);
return updatedTenant;
}
private void setApplicationPropertiesUpdateValues(List<TenantApplicationProperty> existingTenantAppProps, Tenant tenant) {
List<TenantApplicationProperty> newTenantApplicationProperties = (tenant.getTenantApplicationProperties() != null) ? tenant.getTenantApplicationProperties() : new ArrayList<TenantApplicationProperty>();
if(newTenantApplicationProperties.size() != 0) {
for(TenantApplicationProperty tenantAppProp : newTenantApplicationProperties) {
int index = existingTenantAppProps.indexOf(tenantAppProp);
if (index < 0) {
// throw an error -- tenantAppProp should always exist, right?
} else {
existingTenantAppProps.get(index).setValue(tenantAppProp.getValue());
}
}
tenant.setTenantApplicationProperties(existingTenantAppProps);
}
}
public Tenant updateTenant(Tenant tenant) {
List<Database> databases = tenant.getDatabases();
List<Administrator> administrators = tenant.getAdministrators();
validateUpdateTenant(tenant);
validateDatabases(databases);
validateAdministrators(administrators);
Tenant existingTenant = findByIdWithAllDetails(tenant.getId());
List<Database> listExistingDatabases = existingTenant.getDatabases();
Database existingEcomDb = getDatabaseByType(listExistingDatabases,
TenantManagerConstants.ECOM_DATASOURCE);
setDatabaseUpdateValues(listExistingDatabases, tenant);
setAdministratorsUpdateValues(existingTenant.getAdministrators(),
tenant);
setProductUpdateValue(existingTenant.getProduct(), tenant);
setApplicationPropertiesUpdateValues(existingTenant.getTenantApplicationProperties(), tenant);
setEcomDBParamsDefaultValues(tenant);
setAdministratorDefaultValues(tenant);
Database updateEcomDb = getDatabaseByType(tenant.getDatabases(),
TenantManagerConstants.ECOM_DATASOURCE);
Boolean shouldInstallNewDB = true;
if (existingEcomDb.getName().equalsIgnoreCase(updateEcomDb.getName())
&& existingEcomDb.getHost().equalsIgnoreCase(
updateEcomDb.getHost())
&& existingEcomDb.getPort().equals(updateEcomDb.getPort())) {
shouldInstallNewDB = false;
} else {
testEcomDBConnection(updateEcomDb);
}
int ecomDbTableCount = getEcomDBTableCount(updateEcomDb);
String[][] languages = formatAndValidateLanguages(updateEcomDb
.getEcomDatabaseParameters().getLanguages());
Tenant updatedTenant = saveExistingTenant(tenant);
if (updatedTenant != null) {
if (shouldInstallNewDB || ecomDbTableCount == 0) {
installDatabase(updateEcomDb, languages, updatedTenant);
} else {
updateDatabase(updateEcomDb, languages, updatedTenant);
}
storageService.updateTenantFolderStructure(updatedTenant);
} else {
throw new TenantManagerException(
ApiMessageConstants.M_TENANT_PROVISION_ERROR,
ApiMessageConstants.C_TENANT_PROVISION_ERROR);
}
return updatedTenant;
}
private Tenant saveExistingTenant(Tenant tenant) {
tenant.setStatus(TenantStatusEnum.INPROGRESS);
tenant.setMessage(ApiMessageConstants.M_DATABASE_UPDATE_INPROGRESS);
String reason = ApiMessageConstants.R_UPDATE_TENANT;
return saveTenantWithLog(tenant, reason);
}
In application property, you defined 1-1 relation like:
#OneToOne
#JoinColumn(name = "property_group_id")
private ApplicationPropertyGroup applicationPropertyGroup;
#OneToOne
#JoinColumn(name = "property_type_id")
private ApplicationPropertyType applicationPropertyType;
While you have not defined the same relation (note it should work bidirectionally i.e. say for e.g. if you as a person related to an employee id, then employee id is related to you as a person well) in individual property ApplicationPropertyGroup and ApplicationPropertyType.
You should add the same 1-1 relation in ApplicationPropertyGroup and ApplicationPropertyType with ApplicationProperty.
I have a situation where i have an entity OrderedItem which have a many-to-one relationship with another entity Order. When I try to persist the Order entity I receive the following error:
> The bean encountered a non-application exception; nested exception is:
> javax.persistence.PersistenceException: Exception [EclipseLink-4002]
> (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b):
> org.eclipse.persistence.exceptions.DatabaseException Internal
> Exception: com.sap.db.jdbc.exceptions.JDBCDriverException: SAP DBTech
> JDBC: [257]: sql syntax error: incorrect syntax near "ORDER": line 1
> col 13 (at pos 13) Error Code: 257 Call: INSERT INTO ORDER (ID,
> ORDEREDAT, STATUS, TABLE, acceptor_id, waiter_id) VALUES (?, ?, ?, ?,
> ?, ?) bind => [6 parameters bound] Query:
> InsertObjectQuery([Timestamp: 2013-07-16 19:17:56.708 Table: 365
> Status: NEW Waiter: [ID: 1 EGN: 9999999999 Name: Kukata Role: [Role:
> Manager]] Acceptor: [ID: 1 EGN: 9999999999 Name: Kukata Role: [Role:
> Manager]]])
Here is my Order entity
#Entity
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
public static enum Status{
NEW,
PROCESSED
}
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private long id;
#NotNull
#Column(nullable = false)
private Timestamp orderedAt;
#NotNull
#Column(nullable = false)
private Integer table;
#NotNull
#ManyToOne(optional = false)
#JoinColumn(name = "waiter_id", referencedColumnName = "id")
private Employee waiter;
#NotNull
#Enumerated(EnumType.STRING)
private Status status;
#ManyToOne(optional = true)
#JoinColumn(name = "acceptor_id", referencedColumnName = "id")
private Employee acceptor;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Timestamp getOrderedAt() {
return orderedAt;
}
public void setOrderedAt(Timestamp param) {
this.orderedAt = param;
}
public Integer getTable() {
return table;
}
public void setTable(Integer param) {
this.table = param;
}
public Employee getWaiter() {
return waiter;
}
public void setWaiter(Employee param) {
this.waiter = param;
}
public Status getStatus() {
return status;
}
public void setStatus(Status param) {
this.status = param;
}
public Employee getAcceptor() {
return acceptor;
}
public void setAcceptor(Employee param) {
this.acceptor = param;
}
#Override
public String toString() {
return new StringBuilder().append("[Timestamp: ").append(orderedAt)
.append("\tTable: ").append(table).append("\tStatus: ")
.append(status).append("\tWaiter: ").append(waiter)
.append("\tAcceptor: ").append(acceptor).append("]").toString();
}
}
And here is my orderedItem entity
#Entity
#Table(name = "OrderedItem")
public class OrderedItem implements Serializable {
private static final long serialVersionUID = 1L;
public OrderedItem() {
}
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private long id;
#NotNull
#Column(nullable = false)
private Integer quantity;
#NotNull
#Column(nullable = false)
private Double price;
#NotNull
#OneToOne(optional = false)
#JoinColumn(name = "item_id", referencedColumnName = "id")
private Item item;
#NotNull
#ManyToOne(optional = false)
#JoinColumn(name = "order_id", referencedColumnName = "id")
private Order order;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer param) {
this.quantity = param;
}
public Double getPrice() {
return price;
}
public void setPrice(Double param) {
this.price = param;
}
public Item getItem() {
return item;
}
public void setItem(Item param) {
this.item = param;
}
public Order getOrder() {
return order;
}
public void setOrder(Order param) {
this.order = param;
}
#Override
public String toString() {
return new StringBuilder().append("[Order: ").append(order)
.append("Item: ").append(item).append("\tQuantity: ")
.append(quantity).append("\tPrice: ").append(price).append("]")
.toString();
}
}
And my Employee entity
#Entity
#Table(name = "Employee")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
public Employee() {
}
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private long id;
#NotNull
#Column(nullable = false)
private String name;
#NotNull
#Column(nullable = false, unique = true)
private String egn;
#NotNull
#Column(nullable = false)
private byte[] pwd;
#NotNull
#ManyToOne(optional = false)
#JoinColumn(name = "Role_role", referencedColumnName = "role")
private Role role;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String param) {
this.name = param;
}
public String getEGN() {
return egn;
}
public void setEGN(String param) {
this.egn = param;
}
public byte[] getPwd() {
return pwd;
}
public void setPwd(byte[] param) {
this.pwd = param;
}
public Role getRole() {
return role;
}
public void setRole(Role param) {
this.role = param;
}
#Override
public String toString() {
return new StringBuilder().append("[ID: ").append(id).append("\tEGN: ")
.append(egn).append("\tName: ").append(name).append("\tRole: ")
.append(role).append("]").toString();
}
}
Everything works fine, until I try to persist the order entity. Here is a dummy test servlet
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.persistence.dao.CategoryDAO;
import org.persistence.dao.EmployeeDAO;
import org.persistence.dao.ItemDAO;
import org.persistence.dao.OrderDAO;
import org.persistence.dao.OrderedItemDAO;
import org.persistence.dao.RoleDAO;
import sbms.persistence.entities.Category;
import sbms.persistence.entities.Employee;
import sbms.persistence.entities.Item;
import sbms.persistence.entities.Order;
import sbms.persistence.entities.OrderedItem;
import sbms.persistence.entities.Role;
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
private CategoryDAO categoryDAO;
#EJB
private OrderDAO orderDAO;
#EJB
private OrderedItemDAO orderedItemDAO;
#EJB
private ItemDAO itemDAO;
#EJB
private RoleDAO roleDAO;
#EJB
private EmployeeDAO employeeDAO;
public Test() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
response.getWriter().print(
"<p>Checking if the Role 'Manager' exists.</p>");
Role managerRole = null;
List<Role> roles = roleDAO.getAll(
"select X from Role X where X.role = ?1",
Role.ERoles.Manager);
if (roles.size() == 0) {
response.getWriter().print(
"<p>The role 'manager' does not exist. Adding it.</p>");
Role role = new Role();
role.setRole(Role.ERoles.Manager);
roleDAO.add(role);
managerRole = role;
} else {
response.getWriter().print(
"<p>The role 'manager' does exists.</p>");
managerRole = roles.get(0);
}
response.getWriter().print(
"<p>Checking if there are any managers</p>");
List<Employee> employes = employeeDAO.getAll(
"select X from Employee X where X.role = ?1", managerRole);
if (employes.size() == 0) {
response.getWriter().print(
"<p>There are no managers. Adding new one.</p>");
Employee employee = new Employee();
employee.setEGN("9999999999");
employee.setName("Kukata");
employee.setPwd("password".getBytes());
employee.setRole(managerRole);
employeeDAO.add(employee);
}
response.getWriter().print("<p>Checking for category 'Vodka'</p>");
Category category = null;
List<Category> categories = categoryDAO.getAll(
"select X from Category X where X.name = ?1", "Vodka");
if (categories.size() == 0) {
category = new Category();
response.getWriter().print("<p>Adding category Vodka</p>");
category.setName("Vodka");
categoryDAO.add(category);
}else{
category = categories.get(0);
}
response.getWriter().print("<p>Checking for Russian Standard :D</p>");
Item item = null;
List<Item> items = itemDAO.getAll("select X from Item X where X.name = ?1", "RussianStandard");
if(items.size() == 0){
response.getWriter().print(
"<p>Adding item vodka Russian Standard</p>");
item = new Item();
item.setCategory(category);
item.setPrice(35.6);
item.setName("RussianStandard");
itemDAO.add(item);
}else{
item = items.get(0);
}
response.getWriter().print("<p>Making an order</p>");
// Get the employee who accepted the order (in this example -
// Kukata)
List<Employee> acceptor = employeeDAO.getAll(
"select X from Employee X where X.egn = ?1", "9999999999");
if (acceptor.size() == 0) {
response.getWriter().print(
"<p>Error -there is no such employee</p>");
return;
}
Order order = new Order();
order.setStatus(Order.Status.NEW);
order.setOrderedAt(new Timestamp(System.currentTimeMillis()));
order.setTable(365);
// Kuakata accepted and processed the order!
order.setWaiter(acceptor.get(0));
order.setAcceptor(acceptor.get(0));
response.getWriter().print("<p>Persisting the order</p>");
orderDAO.add(order);
response.getWriter().print("<p>Adding the ordered items</p>");
OrderedItem orderedItem = new OrderedItem();
// We set the previously created item(vodka), but we can also get it
// from the db
orderedItem.setItem(item);
orderedItem.setOrder(order);
orderedItem.setPrice(item.getPrice());
orderedItem.setQuantity(5);
orderedItemDAO.add(orderedItem);
response.getWriter().print("<p>Lets see what we have done:</p>");
} catch (Exception e) {
response.getWriter().print(e.getMessage());
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
As Sotirios Delimanolis said in the comments, ORDER is a reserved word in hana. Changing it to something else solves the problem