cant send a postman data with ManyToOne - spring

hi i'm working with spring boot and rest in my project and i estableshed a relation ManyToOne between two enteties but i'm unable to send the postman request to add a mission along with its category i'm not even sure that the two enteties are correctly related
he are the two entities and the contoller
the mission etity
#Entity
#Table(name="missions")
public class Mission {
public Mission() {
}
public Mission(int id, String state, String adresse, int etatMission, String image, List<Categorie> categories,
String ville, int duree, String description, String domaine) {
this.id = id;
this.state = state;
this.adresse = adresse;
this.etatMission = etatMission;
this.image = image;
this.categories = categories;
this.ville = ville;
this.duree = duree;
this.description = description;
this.domaine = domaine;
}
public List<Categorie> getCategories() {
return categories;
}
public void setCategories(List<Categorie> categories) {
this.categories = categories;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public Mission(Map<String,Object> userMap) {
if (userMap.get("id") != null)
this.id = (int )userMap.get("id");
this.state = (String) userMap.get("state");
this.duree = (int) userMap.get("duree");
this.domaine = (String) userMap.get("domaine");
this.description = (String) userMap.get("description");
this.ville=(String) userMap.get("ville");
this.adresse=(String) userMap.get("adresse");
this.etatMission=(int) userMap.get("etatMission");
this.image=(String) userMap.get("image");
this.categories=(List<Categorie>) userMap.get("categories");
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String state;
private String adresse;
private int etatMission;
private String image;
#OneToMany(mappedBy="mission",cascade=CascadeType.ALL)
private List<Categorie> categories;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
private String ville;
public int getEtatMission() {
return etatMission;
}
public void setEtatMission(int etatMission) {
this.etatMission = etatMission;
}
private int duree;
private String description;
private String domaine;
public String getDomaine() {
return domaine;
}
public void setDomaine(String domaine) {
this.domaine = domaine;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
#Override
public String toString() {
return "Mission [id=" + id + ", state=" + state + ", duree=" + duree + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getDuree() {
return duree;
}
public void setDuree(int duree) {
this.duree = duree;
}
public void add(Categorie cat) {
if (categories == null) {
categories = new ArrayList<>();
}
categories.add(cat);
cat.setMission(this);
}
}
the category entety
#Entity
#Table(name="categorie")
public class Categorie {
public Categorie() {
}
public Categorie(Map<String, Object> catMap) {
this.id=(int) catMap.get("id");
this.nom = (String) catMap.get("nom");
this.mission =(Mission) catMap.get("mission_id") ;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id ;
private String nom;
#ManyToOne
#JoinColumn(name="mission_id",referencedColumnName="id")
private Mission mission;
public Categorie(int id, String nom, Mission mission) {
this.id = id;
this.nom = nom;
this.mission = mission;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
#Override
public String toString() {
return "Categorie [nom=" + nom + "]";
}
public Mission getMission() {
return mission;
}
public void setMission(Mission mission) {
this.mission = mission;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
here's the controller for mission
package ma.ac.emi.MinuteBrico.Controllers;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;
import ma.ac.emi.MinuteBrico.Services.MissionServices;
import ma.ac.emi.MinuteBrico.Models.Mission;
#RestController
public class MissionController {
#Autowired
private MissionServices missionService;
#CrossOrigin
#GetMapping("/missions")
public List<Mission> index(){
return missionService.findAll();
}
#CrossOrigin
#GetMapping("/missions/{id}")
public Optional<Mission> indexById(#PathVariable String id){
int missionId = Integer.parseInt(id);
return missionService.findById(missionId);
}
#CrossOrigin()
#PostMapping("/missions")
public String create(#RequestBody Map<String, Object> missionMap) {
System.out.println(missionMap);
Mission mission = new Mission(missionMap);
missionService.savemission(mission);
return "Mission ajouté";
}
}
package ma.ac.emi.MinuteBrico.Repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import ma.ac.emi.MinuteBrico.Models.Mission;
public interface MissionRepository extends JpaRepository<Mission,Integer> {
}
the postman request
{
"state": "Urgent",
"adresse": "Av ben drisse",
"etatMission": 0,
"image": "assets/Brand.jpeg",
"ville": "Chefchaouen",
"duree": 480000,
"description": "je veux quelqu\\'un pour me faire une cuisne",
"domaine": "Plomberie",
"categories":[
{
"id":15,
"nom":"Menuiserie",
"mission":{
"field":"value"
}
}
]
}

try to add #ManyToOne(cascade = CascadeType.ALL)

Related

How to send a Request body in postman for Embedded entity class in spring data jpa?

Can anyone please help me on how to send a nested json requestbody in postman for the below entity class.
ProcessRequestInfo.java
import java.sql.Date;
import java.time.ZonedDateTime;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="PROCESS_REQUEST_INFO")
public class ProcessRequestInfo {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
private String userName;
private String contactNumber;
#Embedded
private DefectiveComponentInfo defectiveComponentInfo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public DefectiveComponentInfo getDefectiveComponentInfo() {
return defectiveComponentInfo;
}
public void setDefectiveComponentInfo(DefectiveComponentInfo defectiveComponentInfo) {
this.defectiveComponentInfo = defectiveComponentInfo;
}
#Override
public String toString() {
return "ProcessRequestInfo [id=" + id + ", userName=" + userName + ", contactNumber=" + contactNumber
+ ", defectiveComponentInfo=" + defectiveComponentInfo + "]";
}
public ProcessRequestInfo(int id, String userName, String contactNumber,
DefectiveComponentInfo defectiveComponentInfo, ZonedDateTime date) {
super();
this.id = id;
this.userName = userName;
this.contactNumber = contactNumber;
this.defectiveComponentInfo = defectiveComponentInfo;
}
public ProcessRequestInfo() {
super();
// TODO Auto-generated constructor stub
}
}
DefectiveComponentInfo.java
import javax.persistence.Embeddable;
#Embeddable
public class DefectiveComponentInfo {
private String componentType;
private String componentName;
private Long quantity;
private String description;
public String getComponentType() {
return componentType;
}
public void setComponentType(String componentType) {
this.componentType = componentType;
}
public String getComponentName() {
return componentName;
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "DefectiveComponentDetail [componentType=" + componentType + ", componentName=" + componentName
+ ", quantity=" + quantity + ", description=" + description + "]";
}
public DefectiveComponentInfo(String componentType, String componentName, Long quantity, String description) {
super();
this.componentType = componentType;
this.componentName = componentName;
this.quantity = quantity;
this.description = description;
}
public DefectiveComponentInfo() {
super();
// TODO Auto-generated constructor stub
}
}
I have tried few nested json requestbody in postman but the inner class data is getting null.
Below is my json request body which I have tried.
{
"userName" : "sam",
"contactNumber" : "96014587555",
"DefectiveComponentInfo":
[ {
"componentType":"Integral",
"componentName":"Bummper",
"quantity":5,
"description": "Repair product"
}]
}
Thanks in advance!!!
You are almost there. few things to be corrected
{
"userName" : "sam",
"contactNumber" : "96014587555",
"defectiveComponentInfo": {
"componentType":"Integral",
"componentName":"Bummper",
"quantity":5,
"description": "Repair product"
}
}
What i have corrected here
As per #Ausgefuchster already mentioned about the incorrect usage of [] array syntax. Removed it.
Your property name is defectiveComponentInfo not capital D.
Try this:
"DefectiveComponentInfo":
{
"componentType": "Integral",
"componentName": "Bummper",
"quantity": 5,
"description": "Repair product"
}
Because you're using [] but these indicate a list.

springdatarepository ElasticSearch works on save but fails on update with java.lang.StackOverflowError: null

I am getting java.lang.StackOverflowError: null when updating my data through springdataelasticsearch. The application was generated using Jhipster 7.0.1. Spring Boot version is 2.4.4.. It works fine when creating a new object but an update results in error. Here is the relevant portion of CountryAdminUnitTypeService.java.
* Save a countryAdminUnitType.
*
* #param countryAdminUnitType the entity to save.
* #return the persisted entity.
*/
public CountryAdminUnitType save(CountryAdminUnitType countryAdminUnitType) {
log.debug("Request to save CountryAdminUnitType : {}", countryAdminUnitType);
CountryAdminUnitType result = countryAdminUnitTypeRepository.save(countryAdminUnitType);
countryAdminUnitTypeSearchRepository.save(result);
return result;
}
When creating, here's how the object looks on call to countryAdminUntiTypeSearchRepository.save(result);.
result = {CountryAdminUnitType#23268} "CountryAdminUnitType{id=200102, name='Province'}"
id = {Long#23292} 200102
name = "Province"
parent = null
country = {Country#23275} "Country{id=183778, name='Turkey', isoCode='TR'}"
id = {Long#23281} 183778
name = "Turkey"
isoCode = "TR"
countryAdminUnitTypes = null
And here's how it looks on updating.
result = {CountryAdminUnitType#24746} "CountryAdminUnitType{id=200102, name='Province'}"
id = {Long#24752} 200102
name = "Province"
parent = null
country = {Country#24754} "Country{id=183778, name='Turkey', isoCode='TR'}"
id = {Long#24756} 183778
name = "Turkey"
isoCode = "TR"
countryAdminUnitTypes = {PersistentSet#24761} size = 1
0 = {CountryAdminUnitType#24746} "CountryAdminUnitType{id=200102, name='Province'}"
id = {Long#24752} 200102
name = "Province"
parent = null
country = {Country#24754} "Country{id=183778, name='Turkey', isoCode='TR'}"
The only difference I see is that countryAdminUnitTypes is not null in second case. However this should be taken care of by JsonIgnoreProperties given in Country.java below.
Here's the beginning of a very long log file.
ERROR 91444 --- [ XNIO-5 task-1] c.s.c.s.CountryAdminUnitTypeService : Exception in save() with cause = 'NULL' and exception = 'null'
java.lang.StackOverflowError: null
at org.springframework.data.util.Streamable.stream(Streamable.java:87)
at org.springframework.data.util.Streamable.lambda$map$1(Streamable.java:101)
at org.springframework.data.util.LazyStreamable.stream(LazyStreamable.java:55)
at org.springframework.data.util.LazyStreamable.iterator(LazyStreamable.java:46)
at java.base/java.lang.Iterable.forEach(Iterable.java:74)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeCollectionValue(MappingElasticsearchConverter.java:710)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.getWriteComplexValue(MappingElasticsearchConverter.java:620)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeProperty(MappingElasticsearchConverter.java:601)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeProperties(MappingElasticsearchConverter.java:553)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeEntity(MappingElasticsearchConverter.java:511)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeEntity(MappingElasticsearchConverter.java:636)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.getWriteComplexValue(MappingElasticsearchConverter.java:627)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeProperty(MappingElasticsearchConverter.java:601)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeProperties(MappingElasticsearchConverter.java:553)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeEntity(MappingElasticsearchConverter.java:511)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeEntity(MappingElasticsearchConverter.java:636)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.getWriteComplexValue(MappingElasticsearchConverter.java:627)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.lambda$writeCollectionValue$7(MappingElasticsearchConverter.java:709)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.Spliterators$IteratorSpliterator.tryAdvance(Spliterators.java:1812)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.lambda$initPartialTraversalState$0(StreamSpliterators.java:294)
at java.base/java.util.stream.StreamSpliterators$AbstractWrappingSpliterator.fillBuffer(StreamSpliterators.java:206)
at java.base/java.util.stream.StreamSpliterators$AbstractWrappingSpliterator.doAdvance(StreamSpliterators.java:161)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.tryAdvance(StreamSpliterators.java:300)
at java.base/java.util.Spliterators$1Adapter.hasNext(Spliterators.java:681)
at java.base/java.lang.Iterable.forEach(Iterable.java:74)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeCollectionValue(MappingElasticsearchConverter.java:710)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.getWriteComplexValue(MappingElasticsearchConverter.java:620)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeProperty(MappingElasticsearchConverter.java:601)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeProperties(MappingElasticsearchConverter.java:553)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeEntity(MappingElasticsearchConverter.java:511)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeEntity(MappingElasticsearchConverter.java:636)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.getWriteComplexValue(MappingElasticsearchConverter.java:627)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeProperty(MappingElasticsearchConverter.java:601)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeProperties(MappingElasticsearchConverter.java:553)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeEntity(MappingElasticsearchConverter.java:511)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.writeEntity(MappingElasticsearchConverter.java:636)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.getWriteComplexValue(MappingElasticsearchConverter.java:627)
at org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter.lambda$writeCollectionValue$7(MappingElasticsearchConverter.java:709)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.Spliterators$IteratorSpliterator.tryAdvance(Spliterators.java:1812)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.lambda$initPartialTraversalState$0(StreamSpliterators.java:294)
at java.base/java.util.stream.StreamSpliterators$AbstractWrappingSpliterator.fillBuffer(StreamSpliterators.java:206)
at java.base/java.util.stream.StreamSpliterators$AbstractWrappingSpliterator.doAdvance(StreamSpliterators.java:161)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.tryAdvance(StreamSpliterators.java:300)
at java.base/java.util.Spliterators$1Adapter.hasNext(Spliterators.java:681)
at java.base/java.lang.Iterable.forEach(Iterable.java:74)
Here are the model classes.
CountryAdminUnitType.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* A CountryAdminUnitType.
*/
#Entity
#Table(name = "country_admin_unit_type")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
#org.springframework.data.elasticsearch.annotations.Document(indexName = "countryadminunittype")
public class CountryAdminUnitType implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "name")
private String name;
#ManyToOne
#JsonIgnoreProperties(value = { "parent", "country" }, allowSetters = true)
private CountryAdminUnitType parent;
#ManyToOne
#JsonIgnoreProperties(
value = { "defaultResidenceMeasurementUnit", "countryAdminUnitTypes", "preferences", "personNationalities" },
allowSetters = true
)
private Country country;
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public CountryAdminUnitType id(Long id) {
this.id = id;
return this;
}
public String getName() {
return this.name;
}
public CountryAdminUnitType name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
public CountryAdminUnitType getParent() {
return this.parent;
}
public CountryAdminUnitType parent(CountryAdminUnitType countryAdminUnitType) {
this.setParent(countryAdminUnitType);
return this;
}
public void setParent(CountryAdminUnitType countryAdminUnitType) {
this.parent = countryAdminUnitType;
}
public Country getCountry() {
return this.country;
}
public CountryAdminUnitType country(Country country) {
this.setCountry(country);
return this;
}
public void setCountry(Country country) {
this.country = country;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CountryAdminUnitType)) {
return false;
}
return id != null && id.equals(((CountryAdminUnitType) o).id);
}
#Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
#Override
public String toString() {
return "CountryAdminUnitType{" +
"id=" + getId() +
", name='" + getName() + "'" +
"}";
}
}
Country.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* A Country.
*/
#Entity
#Table(name = "country")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
#org.springframework.data.elasticsearch.annotations.Document(indexName = "country")
public class Country implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "iso_code")
private String isoCode;
#OneToMany(mappedBy = "country")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
#JsonIgnoreProperties(value = { "parent", "country" })
private Set<CountryAdminUnitType> countryAdminUnitTypes = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Country id(Long id) {
this.id = id;
return this;
}
public String getName() {
return this.name;
}
public Country name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
public String getIsoCode() {
return this.isoCode;
}
public Country isoCode(String isoCode) {
this.isoCode = isoCode;
return this;
}
public void setIsoCode(String isoCode) {
this.isoCode = isoCode;
}
public Set<CountryAdminUnitType> getCountryAdminUnitTypes() {
return this.countryAdminUnitTypes;
}
public Country countryAdminUnitTypes(Set<CountryAdminUnitType> countryAdminUnitTypes) {
this.setCountryAdminUnitTypes(countryAdminUnitTypes);
return this;
}
public Country addCountryAdminUnitType(CountryAdminUnitType countryAdminUnitType) {
this.countryAdminUnitTypes.add(countryAdminUnitType);
countryAdminUnitType.setCountry(this);
return this;
}
public Country removeCountryAdminUnitType(CountryAdminUnitType countryAdminUnitType) {
this.countryAdminUnitTypes.remove(countryAdminUnitType);
countryAdminUnitType.setCountry(null);
return this;
}
public void setCountryAdminUnitTypes(Set<CountryAdminUnitType> countryAdminUnitTypes) {
if (this.countryAdminUnitTypes != null) {
this.countryAdminUnitTypes.forEach(i -> i.setCountry(null));
}
if (countryAdminUnitTypes != null) {
countryAdminUnitTypes.forEach(i -> i.setCountry(this));
}
this.countryAdminUnitTypes = countryAdminUnitTypes;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Country)) {
return false;
}
return id != null && id.equals(((Country) o).id);
}
#Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
#Override
public String toString() {
return "Country{" +
"id=" + getId() +
", name='" + getName() + "'" +
", isoCode='" + getIsoCode() + "'" +
"}";
}
}
This is because of how JHipster sets up save. It was only happening on updating objects with bi-directional relationships.
* Save a countryAdminUnitType.
*
* #param countryAdminUnitType the entity to save.
* #return the persisted entity.
*/
public CountryAdminUnitType save(CountryAdminUnitType countryAdminUnitType) {
log.debug("Request to save CountryAdminUnitType : {}", countryAdminUnitType);
CountryAdminUnitType result = countryAdminUnitTypeRepository.save(countryAdminUnitType);
countryAdminUnitTypeSearchRepository.save(result);
return result;
}
The object to be updated is set correctly when being passed to jpa repository countryAdminUnitTypeRepository.save(countryAdminUnitType);. However, the returned result object has circular dependencies and is directly forwarded to elasticsearch repository countryAdminUnitTypeSearchRepository.save(result); for update. I resolved it by only using the id of the object.
Line
CountryAdminUnitType result = countryAdminUnitTypeRepository.save(countryAdminUnitType);
countryAdminUnitTypeSearchRepository.save(result);
has been changed to
CountryAdminUnitType result = countryAdminUnitTypeRepository.save(countryAdminUnitType);
countryAdminUnitType.setId(result.getId());
countryAdminUnitTypeSearchRepository.save(countryAdminUnitType);
return result;
Thank you for the discussion. This did not work for me on entity , using Jhipster 7.8.1.
FYI, I just commented out the SearchRepository.save(result); as a quick fix to unblock development.
Issue: https://github.com/jhipster/generator-jhipster/issues/16136#issuecomment-1012404392

#OneToOne(cascade = {CascadeType.ALL}) problem

I have a problem with my code. I do a little CarRent webservice and when i try to assign Errand to the car, errand which i want to assign is add to list of errands...
this is controller of errand
package com.RentCar.Rent_A_car.domain.Controllers;
import com.RentCar.Rent_A_car.domain.Car;
import com.RentCar.Rent_A_car.domain.Errand;
import com.RentCar.Rent_A_car.domain.Services.CarService;
import com.RentCar.Rent_A_car.domain.Services.ErrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
#Controller
public class ErrandController {
#Autowired
CarService carService;
#Autowired
ErrandService errandService;
#RequestMapping("/assignErrand")
public String assignQuest(#RequestParam("plate") String plate, Model model){
Car car = carService.getCar(plate);
List<Errand> errandList = errandService.getAllCurrentErrands();
model.addAttribute("car",car);
model.addAttribute("errands",errandList);;
return "assignErrand";
}
#RequestMapping(value = "/assignErrand", method = RequestMethod.POST)
public String assignQuest(Car car){
carService.updateCar(car);
System.out.println("assignquest");
return "redirect:/cars";
}
These are my repositories
#Repository
public class CarsRepository {
// class to do CRUD operation on cars and errands
Map<String, Car> CarList = new HashMap<>();
#PersistenceContext
private EntityManager em;
#Transactional
public void AddCar (String mark, String plate, int mileage){
Car newCar = new Car(mark, plate, mileage);
em.persist(newCar);
}
//pobiera aktualne id i dodaje do mapy
#Transactional
public void AddCar(Car car) {
em.persist(car);
}
// dla każdego "powyzej" usuniętego trzeba zmniejszyć id o 1 ; pętla o dlugosci pozostałych aut id--; KONIECZNE FINALNIE, do budowy nie
#Transactional
public void DellateCar(String plate){
Car c = em.find(Car.class, plate);
em.remove(c);
}
public Car getCar(String plate){
Car car = em.createQuery("from Car c where c.plate=:plate", Car.class)
.setParameter("plate", plate).getSingleResult();
return car;
}
public Collection<Car> getAllCars() {
return em.createQuery("from Car",Car.class).getResultList();
}
#Transactional
public void updateCar(Car car) {
em.merge(car);
}
// public String getPlate() {
// if (CarList.isEmpty()) {
// return "Car list is empty";
// } else {
// return (String)CarList.keySet();
// }
// }
// #PostConstruct
// public void build() {
// AddCar("BMW","DW",100000);
// AddCar("Opel","DTR",100043);
// AddCar("Toyota","WB",1012300);
// AddCar("Audi","DST",102340);
//
// }
#Override
public String toString() {
return "CarsRepository{" +
"CarList=" +
'}' + "\n";
}
}
Nr
#Repository
public class ErrandRepository {
#PersistenceContext
private EntityManager ee;
List<Errand> ErrandList = new ArrayList<>();
#Transactional
public void createErrand(String description) {
Errand newErrand = new Errand(description);
ee.persist(newErrand);
System.out.println(newErrand);
}
public void createErrand(Errand errand){ErrandList.add(errand);}
public List<Errand> getAll () {
return ee.createQuery("from Errand", Errand.class).getResultList();
}
public void delateErrand(Errand errand) {
ee.remove(errand);
}
#Transactional
public void delateErrand(int x) {
ErrandList.remove(x);
}
public Errand getErrandId(Integer x){
return ee.find(Errand.class, x );
}
#PostConstruct
#Transactional
public void init(){
Errand e1 = new Errand("zlecenie na wrocław");
Errand e2 = new Errand("zlecenie na wasdw");
Errand e3 = new Errand("zlecenie na wfgasfdław");
}
#Override
public String toString() {
return "ErrandRepository{" +
"ErrandList=" + ErrandList +
'}';
}
}
this is a part of CarService
public void updateCar(Car car) {
carsRepository.updateCar(car);
System.out.println("tu sie wywołuje updatecar");
}
i don't know what is a problem... can you help me ?
edit, i add car and errand class
package com.RentCar.Rent_A_car.domain;
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
public class Car {
// #Id
// #GeneratedValue(strategy = GenerationType.AUTO)
// public int id;
String mark;
#Id
String plate;
int mileage;
#OneToOne(cascade = CascadeType.ALL)
public Errand errand;
public Car() { }
public Car(String mark, String plate, int mileage) {
this.mark = mark;
this.plate = plate;
this.mileage = mileage;
}
public void setErrand(Errand errand) {
this.errand = errand;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public Errand getErrand() {
return errand;
}enter code here
And errand class
package com.RentCar.Rent_A_car.domain;
import net.bytebuddy.dynamic.loading.InjectionClassLoader;
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
public class Errand {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int Id;
public String description;
public Errand() {
}
public Errand(String description) {
this.description = description;
}
#Override
public String toString() {
return description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I'm not quite sure about what is the actual problem. But anyway, I can make you some recommendations:
use plural nouns for REST uris, like:
#GetMapping("cars")
#GetMapping("errands")
and so on. Not verbs, like: assignErrand
If you split Repositories and Services, do not put login in repos, like
#Transactional
public void createErrand(String description) {
Errand newErrand = new Errand(description);
ee.persist(newErrand);
System.out.println(newErrand);
}
In the repos you should do just the persistence job. Leave the logic to the service
To add errands, I would go with something like this:
#PostMapping("/cars/{carId}/errands")
public Car addErranr(#PathVariable int carId, #RequestBody Errand errand){
Car car = this.carService.findById(carId);
car.getErrands().add(errand);
return this.carService.save(car);
}

How to retrieve data from DB and print in jsp using spring and hibernate?

I have already written the code for inserting my data into my DB but I'm a bit confused on how to retrieve that data in json format and print in my jsp view using a jQuery data table. I have written some code on retrieving but I'm still stuck. Please help.
Here are my code snippets:
entity class:
package model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
#Entity
public class Products {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int productId;
#Size(min=1)
private String productName;
#Min(value=1, message = "Value cannot be zero or negative")
private double unitPrice;
#Size(min=1)
private String productDescription;
#Size(min=1)
private String category;
#Min(value = 1, message = " Quantity should be greater than zero and positive")
#Max(value= 99, message = " Quantity limit exceeded, value should be less than 100")
private int productQty;
public Products() {}
public Products(int productId, String productName, double unitPrice, String productDescription, String category, int productQty) {
super();
this.productQty = productQty;
this.productId = productId;
this.productName = productName;
this.unitPrice = unitPrice;
this.productDescription = productDescription;
this.category = category;
}
public int getProductQty() {
return productQty;
}
public void setProductQty(int productQty) {
this.productQty = productQty;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
DAOImplementation class:
package model.daoimpl;
import java.util.List;
import org.hibernate.Session;
import model.config.HibernateUtil;
import model.dao.IProductsDAO;
import model.entity.Products;
public class ProductsDAOImpl implements IProductsDAO {
private Session sess;
public ProductsDAOImpl() {
sess = HibernateUtil.getSessionFactory().openSession();
}
public boolean insertProduct(Products p) {
boolean b = true;
try
{
sess.beginTransaction();
sess.save(p);
sess.getTransaction().commit();
}catch(Exception ex)
{
b = false;
sess.getTransaction().rollback();
ex.printStackTrace();
}
return b;
}
public List<Products> getProducts()
{
List<Products> lp = null;
try
{
sess.beginTransaction();
lp = sess.createQuery("from Product",Products.class).getResultList();
}catch(Exception ex)
{
ex.printStackTrace();
}
return lp;
}
}
controller class:
#Controller
public class ProductController {
#RequestMapping(value="/manageproducts", method= RequestMethod.GET)
public String manageProductPage() {
return "manageproducts";
}
#RequestMapping(value="/insertproducts",method = RequestMethod.POST)
public String addInserProductsPage(#ModelAttribute("Products")Products p) {
IProductsDAO ip = new ProductsDAOImpl();
boolean b = ip.insertProduct(p);
if(b)
return "success";
else
return "manageproducts";
}
#RequestMapping(value="/listproducts", method = RequestMethod.GET)
public List<Products> listAllProducts(){
IProductsDAO ip = new ProductsDAOImpl();
return ip.getProducts();
}
}
So as you can see I have created the getproducts function but I haven't created the view for displaying products for which I want to use the jQuery datatable, Also I'm a bit confused on how to map the view with my controller. So please help.
You can use Model to send your list to the view page
#RequestMapping(value="/listproducts", method = RequestMethod.GET)
public String listAllProducts(Model model){
IProductsDAO ip = new ProductsDAOImpl();
List<Products> products = ip.getProducts();
model.addAttribute ("products",products);
Return "your view name without .jsp";
}

ManyToMany select query is correct and the query is viewed in console. But I cant put values into jsp

I added many to many relationship to importers and agents table..data save successfully and middle table created...but i cannot retrieve data to my jsp ...How can i retrieve agents table data to my jsp.
My model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "importers")
public class Importer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "importer_id")
private long importerId;
#NotEmpty
#Column(unique = true, nullable = false)
private String importerBrc;
private String importerVatNumber;
private String importerName;
private String importerAddress1;
private String importerAddress2;
private String importerAddress3;
private String importerCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
#Email
private String optemail1;
#Email
private String optemail2;
public String getOptemail1() {
return optemail1;
}
public void setOptemail1(String optemail1) {
this.optemail1 = optemail1;
}
public String getOptemail2() {
return optemail2;
}
public void setOptemail2(String optemail2) {
this.optemail2 = optemail2;
}
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "importer_agents",
joinColumns = {#JoinColumn(name = "importerId")},
inverseJoinColumns = {#JoinColumn(name = "agentId")})
private List<Agent> agentList;
public String getImporterBrc() {
return importerBrc;
}
public void setImporterBrc(String importerBrc) {
this.importerBrc = importerBrc;
}
public String getImporterVatNumber() {
return importerVatNumber;
}
public void setImporterVatNumber(String importerVatNumber) {
this.importerVatNumber = importerVatNumber;
}
public String getImporterName() {
return importerName;
}
public void setImporterName(String importerName) {
this.importerName = importerName;
}
public String getImporterAddress1() {
return importerAddress1;
}
public void setImporterAddress1(String importerAddress1) {
this.importerAddress1 = importerAddress1;
}
public String getImporterAddress2() {
return importerAddress2;
}
public void setImporterAddress2(String importerAddress2) {
this.importerAddress2 = importerAddress2;
}
public String getImporterAddress3() {
return importerAddress3;
}
public void setImporterAddress3(String importerAddress3) {
this.importerAddress3 = importerAddress3;
}
public String getImporterCityName() {
return importerCityName;
}
public void setImporterCityName(String importerCityName) {
this.importerCityName = importerCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getImporterId() {
return importerId;
}
public void setImporterId(long importerId) {
this.importerId = importerId;
}
public List<Agent> getAgentList() {
return agentList;
}
public void setAgentList(List<Agent> agentList) {
this.agentList = agentList;
}
}
my agent table model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
#Entity
#Table(name = "agents")
public class Agent {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "agent_id")
private long agentId;
#NotEmpty
#Column(unique = true, nullable = false)
private String nic;
private String vatNumber;
private String name;
private String agentAddress1;
private String agentAddress2;
private String agentAddress3;
private String agentCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
public long getAgentId() {
return agentId;
}
public void setAgentId(long agentId) {
this.agentId = agentId;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public String getVatNumber() {
return vatNumber;
}
public void setVatNumber(String vatNumber) {
this.vatNumber = vatNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAgentAddress1() {
return agentAddress1;
}
public void setAgentAddress1(String agentAddress1) {
this.agentAddress1 = agentAddress1;
}
public String getAgentAddress2() {
return agentAddress2;
}
public void setAgentAddress2(String agentAddress2) {
this.agentAddress2 = agentAddress2;
}
public String getAgentAddress3() {
return agentAddress3;
}
public void setAgentAddress3(String agentAddress3) {
this.agentAddress3 = agentAddress3;
}
public String getAgentCityName() {
return agentCityName;
}
public void setAgentCityName(String agentCityName) {
this.agentCityName = agentCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
my repository is
package lk.slsi.repository;
import java.util.List;
import lk.slsi.domain.Importer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
/**
* Created by ignotus on 2/8/2017.
*/
public interface ImporterRepository extends CrudRepository<Importer,Long> {
#Override
Importer save(Importer importer);
#Override
Importer findOne(Long importerId);
#Override
List<Importer> findAll();
#Override
void delete(Long aLong);
#Override
void delete(Importer importer);
#Override
void delete(Iterable<? extends Importer> iterable);
#Query("select u from Importer u where u.importerVatNumber = :importerVatNumber")
Importer getImporterByimporterVatNumber(#Param("importerVatNumber") String importerVatNumber);
#Query("select u from Importer u inner join u.agentList where u.importerId = :importerId")
List<Importer> findAgents(#Param("importerId") long importerId);
#Query("select u from Importer u where u.importerId = :importerId")
Importer getImporterByimporterID(#Param("importerId") long importerId);
}
my services is
public List<Importer> getAllIAgents(long importerId) {
return importerRepository.findAgents(importerId);
}
My controller is
#RequestMapping(path = "/viewImporter", method = RequestMethod.POST)
public String updateImporterAll(#RequestParam("importerId") long importerId, Model model) {
slsiLogger.info("Updating user with Id [{}]", importerId);
System.out.println("Importer id is " + importerId);
model.addAttribute("importerDetails", importerServices.getImporterByimporterID(importerId));
model.addAttribute("Agentsdetail", importerServices.getAllIAgents(importerId));
return "importerEdit";
}
Jsp is
<th width="15%">Registered Agents</th>
<c:forEach items="${Agentsdetail}" var="Agent">
<tr>
<td>${Agent.agentList.vatNumber}</td>
</tr>
/c:forEach>
</thead>
The query shows in netbeans console like this
Hibernate: select importer0_.importer_id as importer1_2_, importer0_.email as email2_2_, importer0_.importer_address1 as importer3_2_, importer0_.importer_address2 as importer4_2_, importer0_.importer_address3 as importer5_2_, importer0_.importer_brc as importer6_2_, importer0_.importer_city_name as importer7_2_, importer0_.importer_name as importer8_2_, importer0_.importer_vat_number as importer9_2_, importer0_.mobile_phone_number as mobile_10_2_, importer0_.office_phone_number as office_11_2_, importer0_.optemail1 as optemai12_2_, importer0_.optemail2 as optemai13_2_ from importers importer0_ inner join importer_agents agentlist1_ on importer0_.importer_id=agentlist1_.importer_id inner join agents agent2_ on agentlist1_.agent_id=agent2_.agent_id where importer0_.importer_id=?
How can i insert agent table values to my jsp.Please help me

Resources