Postman changes all number values to 0 - java

I've been looking around for a bit and can't seem to figure out why this happens.
I made a post request in postman, it runs it, intelliJ's console doesn't display an error, yet when printing out the object, it shows only the name has been inserted as I wrote it, the rest are 0's.
EDIT: numbers now come in, but foreign key "holdid" only returns as a null value
EDIT 2: Made it work, code changed to show working code
My Controller:
import com.example.tourdebackend.domain.model.Cykelrytter;
import com.example.tourdebackend.domain.service.CykelholdService;
import com.example.tourdebackend.domain.service.CykelrytterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/api/tourdefrance")
public class CykelrytterController {
private final CykelrytterService cykelrytterService;
private final CykelholdService cykelholdService;
#Autowired
public CykelrytterController(CykelrytterService cykelrytterService,
CykelholdService cykelholdService) {
this.cykelrytterService = cykelrytterService;
this.cykelholdService = cykelholdService;
}
#PostMapping()
public ResponseEntity<Cykelrytter> createCykelrytter(
#RequestBody Cykelrytter cykelrytter) {
cykelrytterService.create(cykelrytter);
System.out.println(cykelrytter);
return new ResponseEntity<>(HttpStatus.OK);
}
}
My relevant service:
import com.example.tourdebackend.domain.model.Cykelrytter;
import com.example.tourdebackend.repository.CykelrytterRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
#Service
public class CykelrytterService {
private final CykelrytterRepository cykelrytterRepository;
#Autowired
public CykelrytterService(CykelrytterRepository cykelrytterRepository){
this.cykelrytterRepository = cykelrytterRepository;
}
public void create (Cykelrytter cykelrytter) {
cykelrytterRepository.save(cykelrytter);
}
public List<Cykelrytter> read() {
return cykelrytterRepository.findAll();
}
public Optional<Cykelrytter> readById(int id) { return cykelrytterRepository.findById(id); }
public Cykelrytter update(Cykelrytter cykelrytter){
return cykelrytterRepository.save(cykelrytter);
}
public void delete(int id) { cykelrytterRepository.deleteById(id); }
}
Models:
package com.example.tourdebackend.domain.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Data;
import javax.persistence.*;
#Entity
#Data
#Builder
public class Cykelrytter {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
#Column(name = "bjergpoint")
#JsonProperty("bjergpoint")
private int bjergPoint;
#Column(name = "spurtpoint")
#JsonProperty("spurtpoint")
private int spurtPoint;
#Column(name = "laptime")
#JsonProperty("laptime")
private double lapTime;
#JsonBackReference
#ManyToOne
#JoinColumn(name = "holdid", referencedColumnName = "id")
private Cykelhold cykelhold;
public Cykelrytter() {
}
public Cykelrytter(int id, String name, int bjergPoint, int spurtPoint, double lapTime, Cykelhold cykelhold) {
this.id = id;
this.name = name;
this.bjergPoint = bjergPoint;
this.spurtPoint = spurtPoint;
this.lapTime = lapTime;
this.cykelhold = cykelhold;
}
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 int getBjergPoint() {
return bjergPoint;
}
public void setBjergPoint(int bjergPoint) {
this.bjergPoint = bjergPoint;
}
public int getSpurtPoint() {
return spurtPoint;
}
public void setSpurtPoint(int spurtPoint) {
this.spurtPoint = spurtPoint;
}
public double getLapTime() {
return lapTime;
}
public void setLapTime(double lapTime) {
this.lapTime = lapTime;
}
public Cykelhold getCykelhold() {
return cykelhold;
}
public void setCykelhold(Cykelhold cykelhold) {
this.cykelhold = cykelhold;
}
#Override
public String toString() {
return "Cykelrytter{" +
"id=" + id +
", name='" + name + '\'' +
", bjergPoint=" + bjergPoint +
", spurtPoint=" + spurtPoint +
", lapTime=" + lapTime +
", cykelhold=" + cykelhold +
'}';
}
}
package com.example.tourdebackend.domain.model;
import javax.persistence.*;
import java.util.List;
#Entity
public class Cykelhold {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "holdname")
private String holdName;
#OneToMany
#JoinColumn(name = "id")
//#JsonBackReference
private List<Cykelrytter> cykelrytters;
public Cykelhold() {
}
public Cykelhold(int holdid, String holdName) {
this.id = holdid;
this.holdName = holdName;
}
public Cykelhold(int holdid, String holdName, List<Cykelrytter> cykelrytters) {
this.id = holdid;
this.holdName = holdName;
this.cykelrytters = cykelrytters;
}
public int getId() {
return id;
}
public void setId(int holdid) {
this.id = holdid;
}
public String getHoldName() {
return holdName;
}
public void setHoldName(String holdName) {
this.holdName = holdName;
}
public List<Cykelrytter> getCykelrytters() {
return cykelrytters;
}
public void setCykelrytters(List<Cykelrytter> cykelrytters) {
this.cykelrytters = cykelrytters;
}
#Override
public String toString() {
return "Cykelhold{" +
"id=" + id +
", holdName='" + holdName + '\'' +
", cykelrytters=" + cykelrytters +
'}';
}
}
My postman request:
{
"bjergpoint": 5,
"laptime": 52.02,
"cykelhold":{
"id": 2
},
"name": "kurt",
"spurtpoint": 5
}
Any help is appreciated, thank you!

For JSON deserialization, Jackson is case sensitive to find the Java fields for each of the fields in the JSON body. In your case, the Java field names are not the same as the JSON field names. You either have to rename them in one of the sides, or add the JsonProperty annotation to tell Jackson, what the field is called in the JSON body.
Example:
#Column(name = "bjergpoint")
#JsonProperty("bjergpoint")
private int bjergPoint;

Related

How can I indicate the PathVariable for Spring REST-method?

I want to indicate the pathvariable secondpart. Thats not possible because an errormessage shows: Could not determine type for: veranstaltung.Identificationnumber, at table: teilnehmer, for columns: [org.hibernate.mapping.Column(id)]
What I have to change to use the variable secondpart? How can I access the variable secondpart in the method of the Controller?
package veranstaltung;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Teilnehmer {
static int idnumber=69;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Identificationnumber id;
private String name;
private String vorname;
private String wohnort;
protected Teilnehmer() {}
public Teilnehmer(Identificationnumber id, String name, String vorname,String wohnort)
{
this.id=id;
this.name=name;
this.vorname=vorname;
this.wohnort=wohnort;
}
public static String erzeugeID ()
{
String id= "JAVALAND-";
id=id+idnumber;
idnumber++;
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getWohnort() {
return wohnort;
}
public void setWohnort(String wohnort) {
this.wohnort = wohnort;
}
#Override
public String toString()
{
return id.getfullID()+" "+getName()+" "+getVorname()+" "+getWohnort();
}
}
package veranstaltung;
public class Identificationnumber {
private String firstpart;
private Long secondpart;
public Identificationnumber(String firstpart, Long secondpart)
{
this.firstpart=firstpart;
this.secondpart=secondpart;
}
public String getFirstpart() {
return firstpart;
}
public void setFirstpart(String firstpart) {
this.firstpart = firstpart;
}
public Long getSecondpart() {
return secondpart;
}
public void setSecondpart(Long secondpart) {
this.secondpart = secondpart;
}
public String getfullID()
{
return firstpart+' '+secondpart;
}
}
package veranstaltung;
import veranstaltung.Teilnehmer;
import veranstaltung.Identificationnumber;
import veranstaltung.TeilnehmerRepository;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController
public class TeilnehmerController {
#Autowired
TeilnehmerRepository teilnehmerRepository;
#GetMapping("/teilnehmer")
Iterable<Teilnehmer> teilnehmer(){
return this.teilnehmerRepository.findAll();
}
#GetMapping("/teilnehmer/{id}")
Teilnehmer teilnehmerById(#PathVariable Long secondpart){
Optional<Teilnehmer> teilnehmerOptional = this.teilnehmerRepository.findById(secondpart);
if(teilnehmerOptional.isPresent()) {
return teilnehmerOptional.get();
}
return null;
}
}
Your Identificationnumber is not primitive but custom class. What you are doing is trying to use Long against your Identificationnumber in teilnehmerById method.
I would suggest to either change #Id column of Teilnehmer to Long from Identificationnumber or you can still pass Identificationnumber in teilnehmerById method by doing something like below (This is based on consideration that you have implemented your own findById which will convert Identificationnumber to Long):
#GetMapping("/teilnehmer/{id}")
Teilnehmer teilnehmerById(#PathVariable Long secondpart){
Identificationnumber number = new Identificationnumber();
number.setSecondpart(secondpart);
Optional<Teilnehmer> teilnehmerOptional = this.teilnehmerRepository.findById(number.getfullID());
if(teilnehmerOptional.isPresent()) {
return teilnehmerOptional.get();
}
return null;
Based on hibernate error, it looks like you have to use my first option which is change #Id of Teilnehmer to Long.
Edit : just updated code so that you can use composition of String to Long.

If two entity parent and child saved at same time which mapped with one to many relationship throw id not found exception of parent class

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.

Why is my application failing to create a bean?

I have the following files:
UnitController.java
package com.fidolease.fidolease.controllers;
import com.fidolease.fidolease.exceptions.ResourceNotFoundException;
import com.fidolease.fidolease.models.Unit;
import com.fidolease.fidolease.repository.UnitRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/api/v1")
public class UnitController {
#Autowired
private UnitRepository unitRepository;
#GetMapping("/units")
public List<Unit> getAllUnits(){
return unitRepository.findAll();
}
#GetMapping("/units/{id}")
public ResponseEntity<Unit> getUnitById(#PathVariable(value = "id") Long unitId)
throws ResourceNotFoundException {
Unit unit = unitRepository.findById(unitId)
.orElseThrow(() -> new ResourceNotFoundException("Unit not found for this id :: " + unitId));
return ResponseEntity.ok().body(unit);
}
}
ErrorDetails.java
package com.fidolease.fidolease.exceptions;
import java.util.Date;
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public String getMessage() {
return message;
}
public String getDetails() {
return details;
}
}
GlobalExceptionHandler.java
package com.fidolease.fidolease.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import java.util.Date;
#ControllerAdvice
public class GlobalExceptionHandler {
#ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> resourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
#ExceptionHandler(Exception.class)
public ResponseEntity<?> globalExceptionHandler(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
ResourceNotFoundException.java
package com.fidolease.fidolease.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends Exception{
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message){
super(message);
}
}
Unit.java
package com.fidolease.fidolease.models;
import javax.persistence.*;
#Entity
#Table(name = "units")
public class Unit {
private long id;
private String unit_heading;
private int unit_type_id;
private int number_of_bedroom;
private double number_of_bathroom;
private int number_of_balcony;
private int leasing_info_id;
private String date_of_posting;
private String date_available_from;
private int posted_by;
private boolean is_active;
private String unit_description;
private int carpet_area;
private String unit_number;
private int unit_floor_number;
private int parent_unit_id;
public Unit(){ }
public Unit(String unit_heading, int unit_type_id, int number_of_bedroom, double number_of_bathroom,
int number_of_balcony, int leasing_info_id, String date_of_posting, String date_available_from,
int posted_by, boolean is_active, String unit_description, int carpet_area, String unit_number,
int unit_floor_number, int parent_unit_id) {
this.unit_heading = unit_heading;
this.unit_type_id = unit_type_id;
this.number_of_bedroom = number_of_bedroom;
this.number_of_bathroom = number_of_bathroom;
this.number_of_balcony = number_of_balcony;
this.leasing_info_id = leasing_info_id;
this.date_of_posting = date_of_posting;
this.date_available_from = date_available_from;
this.posted_by = posted_by;
this.is_active = is_active;
this.unit_description = unit_description;
this.carpet_area = carpet_area;
this.unit_number = unit_number;
this.unit_floor_number = unit_floor_number;
this.parent_unit_id = parent_unit_id;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId(){
return this.id;
}
public void setId(long id){
this.id = id;
}
#Column(name = "unit_heading", nullable = false)
public String getUnit_heading(){
return this.unit_heading;
}
public void setUnit_heading(String unit_heading){
this.unit_heading = unit_heading;
}
#Column(name = "unit_type_id", nullable = false)
public int getUnit_type_id(){
return this.unit_type_id;
}
public void setUnit_type_id(int unit_type_id){
this.unit_type_id = unit_type_id;
}
#Column(name = "number_of_bedroom", nullable = false)
public int getNumber_of_bedroom(){
return this.number_of_bedroom;
}
public void setNumber_of_bedroom(int number_of_bedroom){
this.number_of_bedroom = number_of_bedroom;
}
#Column(name = "number_of_bathroom", nullable = false)
public double getNumber_of_bathroom(){
return this.number_of_bathroom;
}
public void setNumber_of_bathroom(double number_of_bathroom){
this.number_of_bathroom = number_of_bathroom;
}
#Column(name = "number_of_balcony", nullable = false)
public int getNumber_of_balcony(){
return this.number_of_balcony;
}
public void setNumber_of_balcony(int number_of_balcony){
this.number_of_balcony = number_of_balcony;
}
#Column(name = "leasing_info_id", nullable = false)
public int getLeasing_info_id(){
return this.leasing_info_id;
}
public void setLeasing_info_id(int leasing_info_id){
this.leasing_info_id = leasing_info_id;
}
#Column(name = "date_of_posting", nullable = false)
public String getDate_of_posting(){
return this.date_of_posting;
}
public void setDate_of_posting(String date_of_posting){
this.date_of_posting = date_of_posting;
}
#Column(name = "date_available_from", nullable = false)
public String getDate_available_from(){
return this.date_available_from;
}
public void setDate_available_from(String date_available_from){
this.date_available_from = date_available_from;
}
#Column(name = "posted_by", nullable = false)
public int getPosted_by(){
return this.posted_by;
}
public void setPosted_by(int posted_by){
this.posted_by = posted_by;
}
#Column(name = "is_active", nullable = false)
public boolean getIs_active(){
return this.is_active;
}
public void setIs_active(boolean is_active){
this.is_active = is_active;
}
#Column(name = "unit_description", nullable = false)
public String getUnit_description(){
return this.unit_description;
}
public void setUnit_description(String unit_description){
this.unit_description = unit_description;
}
#Column(name = "carpet_area", nullable = false)
public int getCarpet_area(){
return this.carpet_area;
}
public void setCarpet_area(int carpet_area){
this.carpet_area = carpet_area;
}
#Column(name = "unit_number", nullable = false)
public String getUnit_number(){
return this.unit_number;
}
public void setUnit_number(){
this.unit_number = unit_number;
}
#Column(name = "unit_floor_number", nullable = false)
public int getUnit_floor_number(){
return this.unit_floor_number;
}
public void setUnit_floor_number(int unit_floor_number){
this.unit_floor_number = unit_floor_number;
}
#Column(name = "parent_unit_id", nullable = false)
public int getParent_unit_id(){
return this.parent_unit_id;
}
public void setParent_unit_id(int parent_unit_id){
this.parent_unit_id = parent_unit_id;
}
#Override
public String toString() {
return "Unit{" +
"id=" + id +
", unit_heading='" + unit_heading + '\'' +
", unit_type_id=" + unit_type_id +
", number_of_bedroom=" + number_of_bedroom +
", number_of_bathroom=" + number_of_bathroom +
", number_of_balcony=" + number_of_balcony +
", leasing_info_id=" + leasing_info_id +
", date_of_posting='" + date_of_posting + '\'' +
", date_available_from='" + date_available_from + '\'' +
", posted_by=" + posted_by +
", is_active=" + is_active +
", unit_description='" + unit_description + '\'' +
", carpet_area=" + carpet_area +
", unit_number='" + unit_number + '\'' +
", unit_floor_number=" + unit_floor_number +
", parent_unit_id=" + parent_unit_id +
'}';
}
}
UnitRepository.java
package com.fidolease.fidolease.repository;
import com.fidolease.fidolease.models.Unit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UnitRepository extends JpaRepository<Unit, Long> {
}
FidoLeaseApplication.java
package com.fidolease.fidolease;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class FidoleaseApplication {
public static void main(String[] args) {
SpringApplication.run(FidoleaseApplication.class, args);
}
}
When I run the application, I get the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'unitRepository' defined in com.fidolease.fidolease.repository.UnitRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
When I searched around, it seemed as if the error might occur if I don't have JPA in my pom file but after searching it, I have the following:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Does anyone have any suggestions as to what I am doing wrong here or maybe a reference to some documentation that may explain my issue? Thank you all for your time and if there is anything I can do to clarify, please let me know.
EDIT: The following is my properties file:
spring.datasource.initialization-mode=always
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://digitaloceanservername:theport/mydbname
spring.datasource.username=myusername
spring.datasource.password=mypassword
Edit 2: Adding the full strack trac -> https://pastebin.com/RskBMJjL
There is a bug in your setter method for unit_number, it is not taking a parameter. It should be:
public void setUnit_number(String unit_number){
this.unit_number = unit_number;
}

I have two Java class and having #ManyToOne and I don't want to #Audit in second java class

I have two Java class Product and ProductNote and I am using #Audit in Product and I don't want to #Audit on ProductNote but getting below error:
Caused by: org.hibernate.MappingException: An audited relation from com.test.test.domain.Product.productNotes to a not audited entity com.test.test.domain.ProductNote!
Code:
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.envers.Audited;
import com.focusrunner.ezpill.Listeners.ProductListeners;
import io.swagger.annotations.ApiModel;
package com.focusrunner.ezpill.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.envers.Audited;
import com.focusrunner.ezpill.Listeners.ProductListeners;
import io.swagger.annotations.ApiModel;
/**
* Stock entry
*
* #author anton
*/
#ApiModel(description = "Stock entry #author anton")
#Entity
#Table(name = "product")
#Audited
#EntityListeners(ProductListeners.class)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(max = 12)
#Column(name = "upc", length = 12, nullable = false)
private String upc;
#Size(min = 10, max = 10)
#Column(name = "ndc", length = 10)
private String ndc;
#Size(max = 255)
#Column(name = "name", length = 255)
private String name;
#Size(max = 255)
#Column(name = "strength", length = 255)
private String strength;
#Size(max = 255)
#Column(name = "form", length = 255)
private String form;
#Size(max = 255)
#Column(name = "jhi_size", length = 255)
private String size;
#Size(max = 255)
#Column(name = "lot", length = 255)
private String lot;
#Column(name = "expires")
private LocalDate expires;
#Column(name = "price", precision = 10, scale = 2)
private BigDecimal price;
#Size(max = 255)
#Column(name = "location", length = 255)
private String location;
#Column(name = "quantity")
private Long quantity;
#Size(max = 15)
#Column(name = "status", length = 15)
private String status;
#OneToMany(mappedBy = "product")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<ProductNote> productNotes = new HashSet<>();
// 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 getUpc() {
return upc;
}
public Product upc(String upc) {
this.upc = upc;
return this;
}
public void setUpc(String upc) {
this.upc = upc;
}
public String getNdc() {
return ndc;
}
public Product ndc(String ndc) {
this.ndc = ndc;
return this;
}
public void setNdc(String ndc) {
this.ndc = ndc;
}
public String getName() {
return name;
}
public Product name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
public String getStrength() {
return strength;
}
public Product strength(String strength) {
this.strength = strength;
return this;
}
public void setStrength(String strength) {
this.strength = strength;
}
public String getForm() {
return form;
}
public Product form(String form) {
this.form = form;
return this;
}
public void setForm(String form) {
this.form = form;
}
public String getSize() {
return size;
}
public Product size(String size) {
this.size = size;
return this;
}
public void setSize(String size) {
this.size = size;
}
public String getLot() {
return lot;
}
public Product lot(String lot) {
this.lot = lot;
return this;
}
public void setLot(String lot) {
this.lot = lot;
}
public LocalDate getExpires() {
return expires;
}
public Product expires(LocalDate expires) {
this.expires = expires;
return this;
}
public void setExpires(LocalDate expires) {
this.expires = expires;
}
public BigDecimal getPrice() {
return price;
}
public Product price(BigDecimal price) {
this.price = price;
return this;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getLocation() {
return location;
}
public Product location(String location) {
this.location = location;
return this;
}
public void setLocation(String location) {
this.location = location;
}
public Long getQuantity() {
return quantity;
}
public Product quantity(Long quantity) {
this.quantity = quantity;
return this;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public String getStatus() {
return status;
}
public Product status(String status) {
this.status = status;
return this;
}
public void setStatus(String status) {
this.status = status;
}
public Set<ProductNote> getProductNotes() {
return productNotes;
}
public Product productNotes(Set<ProductNote> productNotes) {
this.productNotes = productNotes;
return this;
}
public Product addProductNotes(ProductNote productNote) {
this.productNotes.add(productNote);
productNote.setProduct(this);
return this;
}
public Product removeProductNotes(ProductNote productNote) {
this.productNotes.remove(productNote);
productNote.setProduct(null);
return this;
}
public void setProductNotes(Set<ProductNote> productNotes) {
this.productNotes = productNotes;
}
// 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;
}
Product product = (Product) o;
if (product.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), product.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "Product{" +
"id=" + getId() +
", upc='" + getUpc() + "'" +
", ndc='" + getNdc() + "'" +
", name='" + getName() + "'" +
", strength='" + getStrength() + "'" +
", form='" + getForm() + "'" +
", size='" + getSize() + "'" +
", lot='" + getLot() + "'" +
", expires='" + getExpires() + "'" +
", price=" + getPrice() +
", location='" + getLocation() + "'" +
", quantity=" + getQuantity() +
", status='" + getStatus() + "'" +
"}";
}
}
#ApiModel(description = "ProductNotes for add deleted product note #author Sumit")
#Entity
#Table(name = "product_note")
#Audited
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class ProductNote implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Size(max = 255)
#Column(name = "note", length = 255)
private String note;
#Column(name = "jhi_timestamp")
private Instant timestamp;
#ManyToOne
#JsonIgnoreProperties("productNotes")
private Product product;
#ManyToOne
#JsonIgnoreProperties("productNotes")
private 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 getNote() {
return note;
}
public ProductNote note(String note) {
this.note = note;
return this;
}
public void setNote(String note) {
this.note = note;
}
public Instant getTimestamp() {
return timestamp;
}
public ProductNote timestamp(Instant timestamp) {
this.timestamp = timestamp;
return this;
}
public void setTimestamp(Instant timestamp) {
this.timestamp = timestamp;
}
public Product getProduct() {
return product;
}
public ProductNote product(Product product) {
this.product = product;
return this;
}
public void setProduct(Product product) {
this.product = product;
}
public User getUser() {
return user;
}
public ProductNote 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;
}
ProductNote productNote = (ProductNote) o;
if (productNote.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), productNote.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "ProductNote{" +
"id=" + getId() +
", note='" + getNote() + "'" +
", timestamp='" + getTimestamp() + "'" +
"}";
}
I don't want to generate history and audit table for ProductNote.

Hibernate multiple foreign key

I am new to hibernate.
My problem is to resolve multiple Foreign Keys to their Value. I am able to do it with SQL but the Hibernate Annotations makes me crazy.
I got these 2 Tables for example:
Table MoveSets
MoveSet_ID
Punch_1
Punch_2
Graple_1
Graple_2
Graple_3
Graple_4
Table Moves
Move_ID
Name
Damage
MoveType_ID
Counterchance
The Punches and Graples are all foreign keys referencing to Move_ID.
My target is to do a session.createQuery("from MoveSets").list(); and to get a Moveset with the Names of the Moves instead of the IDs.
Is this possible in Hibernate?
package hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "Moves")
public class Moves implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1522367877613954187L;
private int id;
private String name;
private int damage;
private int movetype_id;
private int counterchance;
public Moves() {
}
public Moves(int id, String name, int damage, int movetype_id,
int counterchance) {
this.id = id;
this.name = name;
this.damage = damage;
this.movetype_id = movetype_id;
this.counterchance = counterchance;
}
#Id
#Column(name = "Move_ID")
#GeneratedValue(generator = "increment")
#GenericGenerator(name = "increment", strategy = "increment")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "Damage")
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
#Column(name = "MoveType_ID")
public int getMovetype_id() {
return movetype_id;
}
public void setMovetype_id(int movetype_id) {
this.movetype_id = movetype_id;
}
#Column(name = "Counterchance")
public int getCounterchance() {
return counterchance;
}
public void setCounterchance(int counterchance) {
this.counterchance = counterchance;
}
#Override
public String toString() {
return "Moves - Name: " + name;
}
}
And
package hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "MoveSets")
public class MoveSets implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6488498413048804953L;
private int id;
private int punch_1;
private int punch_2;
private int graple_1;
private int graple_2;
private int graple_3;
private int graple_4;
public MoveSets() {
}
public MoveSets(int id, int punch_1, int punch_2, int graple_1,
int graple_2, int graple_3, int graple_4) {
this.id = id;
this.punch_1 = punch_1;
this.punch_2 = punch_2;
this.graple_1 = graple_1;
this.graple_2 = graple_2;
this.graple_3 = graple_3;
this.graple_4 = graple_4;
}
#ManyToOne
#JoinColumn(name = "Moves_ID")
public Moves moves;
#Id
#Column(name = "MoveSet_ID")
#GeneratedValue(generator = "increment")
#GenericGenerator(name = "increment", strategy = "increment")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "Punch_1")
public int getPunch_1() {
return punch_1;
}
public void setPunch_1(int punch_1) {
this.punch_1 = punch_1;
}
#Column(name = "Punch_2")
public int getPunch_2() {
return punch_2;
}
public void setPunch_2(int punch_2) {
this.punch_2 = punch_2;
}
#Column(name = "Graple_1")
public int getGraple_1() {
return graple_1;
}
public void setGraple_1(int graple_1) {
this.graple_1 = graple_1;
}
#Column(name = "Graple_2")
public int getGraple_2() {
return graple_2;
}
public void setGraple_2(int graple_2) {
this.graple_2 = graple_2;
}
#Column(name = "Graple_3")
public int getGraple_3() {
return graple_3;
}
public void setGraple_3(int graple_3) {
this.graple_3 = graple_3;
}
#Column(name = "Graple_4")
public int getGraple_4() {
return graple_4;
}
public void setGraple_4(int graple_4) {
this.graple_4 = graple_4;
}
#Override
public String toString() {
return "MoveSet - ID: " + id + " Punch 1: " + punch_1;
}
}
Yes it is possible, in fact the whole point of ORM and Hibernate is to get objects (your values) insteed of plain IDs. Your mapping is wrong. You should map your relations (I assume that punches and grapples are moves) via annotations like #OneToOne,#OneToMany and so one along with #JoinColumn, so your fields insteed of this
#Column(name = "Graple_1")
public int getGraple_1() {
return graple_1;
}
should be like
#ManyToOne
#JoinColumn(name="Graple1")
public Move getGraple_1() {
return graple_1;
}
This way you will get relevant Move objects and get any data you want from them, along with the requested name

Categories

Resources