Jackson failed to deserialization OneToMany objects - java

I have faced with the problem that converter can't handle JSON object.
I have two objects in data base. Relationship OneToMany.
I have a AutoService with many services.
And wnen i am trying to send JSON object using postman to my server - I am getting an error:
WARN org.springframework.http.converter.json.MappingJackson2HttpMessageConverter - Failed to evaluate Jackson deserialization for type [[simple type, class com.webserverconfig.user.entity.AutoService]]: java.lang.IllegalArgumentException: Can not handle managed/back reference 'defaultReference': no back reference property found from type [collection type; class java.util.List, contains [simple type, class com.webserverconfig.user.entity.Service]]
Next two classes represents my model:
Class AutoService:
#Entity
#Table(name = "AutoRate")
public class AutoService {
public AutoService() {
}
#Id
#GeneratedValue(generator = "increment")
#GenericGenerator(name = "increment", strategy = "increment")
private long id;
#Column(name = "serviceName", nullable = false)
private String serviceName;
#Column(name = "imageURL", nullable = false)
private String imageURL;
#Column(name = "mapCoordinate", nullable = false)
private String mapCoordinate;
#Column(name = "websiteURL", nullable = false)
private String websiteURL;
#Column(name = "phoneNumber", nullable = false)
private String phoneNumber;
#JsonManagedReference
#OneToMany(fetch = FetchType.EAGER)
#JoinColumn(name = "autoServiceId")
private List<Service> services;
public long getId() {
return id;
}
public String getServiceName() {
return serviceName;
}
public String getImageURL() {
return imageURL;
}
public String getMapCoordinate() {
return mapCoordinate;
}
public String getWebsiteURL() {
return websiteURL;
}
public String getPhoneNumber() {
return phoneNumber;
}
public List<Service> getServices() {
return services;
}
}
Class service:
#Entity
#Table(name = "Service")
public class Service {
public Service() {
}
#Id
#GeneratedValue(generator = "increment")
#GenericGenerator(name = "increment", strategy = "increment")
#Column(name = "serviceId", unique = true, nullable = false)
private long serviceId;
#Column(name = "serviceName", nullable = false)
private String serviceName;
#Column(name = "category", nullable = false)
private String category;
#Column(name = "price", nullable = false)
private int price;
#Column(name = "autoServiceId", nullable = false)
private long autoServiceId;
public long getId() {
return serviceId;
}
public String getCategory() {
return category;
}
public int getPrice() {
return price;
}
public String getServiceName() {
return serviceName;
}
public long getAutoServiceId() {
return autoServiceId;
}
}
Asking for help. Am i missing some annotation ?
Also Controller class:
#RestController
#RequestMapping("/directory")
public class ServiceController {
#Autowired
private AutoRateService dataBaseService;
#RequestMapping(value = "/get", method = RequestMethod.GET)
#ResponseBody
public AutoService getData(){
AutoService dataList = dataBaseService.getById(1);
return dataList;
}
#RequestMapping(value = "/saveService", method = RequestMethod.POST)
#ResponseBody public AutoService saveAutoService(#RequestBody AutoService autoService){
return dataBaseService.save(autoService);
}
}

You could add #JsonBackReference to the other site of the relation. Which by the way is missing or not correct implemented. Add:
#JsonBackReference
#ManyToOne
#JoinColumn(name = "autoServiceId", nullable = false)
private AutoService autoService;
instead of private long autoServiceId;.
Also the AutoService needs to be adjusted with:
#JsonManagedReference
#OneToMany(mappedBy = "autoService", fetch=FetchType.EAGER)
private List<Service> services = new ArrayList<>();

Solution #1 :
- add #JsonIgnore where you have attributes with #OneToMany
Example:
class User {
#OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JsonManagedReference
#JsonIgnore
private List<Comment> comments;
}
class Comment {
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "user_id")
#JsonBackReference
private User user;
}
Solution #2:
- use on your class #JsonIgnoreProperties({"name-of-your-attribute"}), for example "comments"

Related

Spring, Jpa : One To Many Error when the list contains values

I want to return a Profile Object in JSON containing a list of login details associated with a social network.
Everything works correctly when the "reseaux_sociaux" table is empty. For my status table I get my statuses in JSON format in my Profile object. However, when "reseaux_sociaux" contains values then I get the error below and my Profile object in JSON format is not returned...
(Logs)
https://cloudvyzor.com/logpad/?query&database=sandbox-7fb06b2c06f198a7c0e4ff7c74d659e0
Profil Class
#Entity
#Table(name = "Profil")
public class Profil {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "IdComptes", nullable = false)
private Comptes IdComptes;
private String Avatar;
private String Banniere;
private String Pseudo;
private String MailPro;
private String Bio;
#ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinTable(name = "Statut_Profil", joinColumns = #JoinColumn(referencedColumnName = "Id"),inverseJoinColumns = #JoinColumn(referencedColumnName ="Id"))
private List<Statut> Statut;
#OneToMany( mappedBy = "IdProfil")
#JsonManagedReference("id_profil")
private List<ReseauxSociaux> Reseaux;
public Profil(){}
public Profil(Long id, Comptes idComptes, String avatar, String banniere, String pseudo, String mailPro, String bio) {
Id = id;
IdComptes = idComptes;
Avatar = avatar;
Banniere = banniere;
Pseudo = pseudo;
MailPro = mailPro;
Bio = bio;
}
}
ReseauxSociaux Class
#Entity
#IdClass(ReseauxId.class)
public class ReseauxSociaux {
#Id
private int Id;
#Id
private Long IdProfil;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "IdProfil", insertable = false, updatable = false)
#JsonBackReference("id_profil")
private Profil Profil;
#ManyToOne
#JoinColumn(name = "Id", insertable = false, updatable = false)
#JsonBackReference("id")
private Reseau Reseau;
private String Identifiant;
private ReseauxSociaux()
{}
public ReseauxSociaux(int id, Long idProfil, String identifiant) {
Id = id;
IdProfil = idProfil;
Identifiant = identifiant;
}
}
Reseau class
#Entity
public class Reseau {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int Id;
private String Nom;
private String Couleur;
//I tried it with and without and it made no difference
#OneToMany( mappedBy = "Id")
#JsonManagedReference("id")
private List<ReseauxSociaux> Reseaux;
public Reseau(){}
public Reseau(int id, String nom, String couleur) {
Id = id;
Nom = nom;
Couleur = couleur;
}
//Get Set
}
Profil Controller
#RestController
#RequestMapping("/profil")
public class ProfilController {
private final ProfilRepository profilRepository;
public ProfilController(ProfilRepository profilRepository) {
this.profilRepository = profilRepository;
}
#PostMapping("/getprofil/{idCompte}")
Profil GetProfil(#PathVariable("idCompte") Long idCompte)
{
Profil profil= profilRepository.findProfilById(idCompte);
return profil;
}
}
I finally succeeded... The cause of the problem remains unclear but I have two hypotheses: the first is the use of capital letters on variable names; the second is the use of a list with the onetomany with the same name in two entities.
Profil class
#Entity
#Table(name = "Profil")
public class Profil {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "idComptes", nullable = false)
#JsonBackReference("id_comptes")
private Comptes idComptes;
private String avatar;
private String banniere;
private String pseudo;
private String mailPro;
private String bio;
#ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinTable(name = "statut_profil", joinColumns = #JoinColumn(referencedColumnName = "id"),inverseJoinColumns = #JoinColumn(referencedColumnName ="id"))
private List<Statut> statut;
#OneToMany( mappedBy = "idProfil")
#JsonManagedReference("id_profil")
private List<ReseauxSociaux> lstprofil;
public Profil(){}
public Profil(Long id, Comptes idComptes, String avatar, String banniere, String pseudo, String mailPro, String bio) {
this.id = id;
this.idComptes = idComptes;
this.avatar = avatar;
this.banniere = banniere;
this.pseudo = pseudo;
this.mailPro = mailPro;
this.bio = bio;
}
//get set
}
ReseauxSociaux class
#Entity
#IdClass(ReseauxId.class)
public class ReseauxSociaux {
#Id
private int id;
#ManyToOne
#JoinColumn(name = "id", insertable = false, updatable = false)
#JsonBackReference("id_reseau")
private Reseau reseau;
#Id
private Long idProfil;
#ManyToOne
#JoinColumn(name = "idProfil", insertable = false, updatable = false)
#JsonBackReference("id_profil")
private Profil profil;
private String identifiant;
private ReseauxSociaux()
{}
public ReseauxSociaux(int id, Reseau reseau, Long idProfil, String identifiant) {
this.id = id;
this.reseau = reseau;
this.idProfil = idProfil;
this.identifiant = identifiant;
}
}
Reseau class
#Entity
public class Reseau {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String nom;
private String couleur;
#OneToMany( mappedBy = "id")
#JsonManagedReference("id_reseau")
private List<ReseauxSociaux> lstreseau;
public Reseau(){}
public Reseau(int id, String nom, String couleur) {
this.id = id;
this.nom = nom;
this.couleur = couleur;
}
}

jackson.databind.ser.BeanSerializer.serialize Error

I am in a loop. My classes are dependent on each other, maybe I should have designed it differently, but it was working until recently, until I added #JsonBackReference and #JsonManagedReference to solve an error I got. But now I am getting this error:
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.13.3.jar:2.13.3]
I have tried the solutions like adding value to #JsonManagedReference and #JsonBackReference. I added to #JsonIgnore to variables but these did not work.
These are my classes :
#Data
#Entity
public class Auction {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(nullable = false)
private String explanation;
#Column(nullable = false)
private String title;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable = false)
private Date startDate;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable = false)
private Date endDate;
private int sellNowPrice;
#Column(nullable = false)
private int startPrice;
//------------------------
#OneToOne(mappedBy = "auction",
cascade = CascadeType.REMOVE)
private FileAttachment fileAttachment;
#OneToOne
private Category category;
#OneToMany(mappedBy = "auction", cascade = CascadeType.MERGE)
#JsonManagedReference(value="selling-item")
private List<Bid> bids;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name = "creator_id")
#JsonBackReference(value="sell")
private User creator;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name = "buyer_id")
#JsonBackReference(value="buyer")
private User buyer;
public Auction(AuctionVM auctionVM) {
this.explanation=auctionVM.getExplanation();
this.title=auctionVM.getTitle();
this.startDate=auctionVM.getStartDate();
this.endDate=auctionVM.getEndDate();
this.sellNowPrice=auctionVM.getSellNowPrice();
this.startPrice=auctionVM.getStartPrice();
}
public Auction() {}
}
.
#Data
#Entity
public class User implements UserDetails{
/**
*
*/
private static final long serialVersionUID = -2725432351214985546L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull(message="Name can not be null")
#Size(min = 2, max=50, message = "Name must be more than 2 letters ")
#Column(nullable = false)
private String name;
#NotNull(message="Username can not be null")
#UniqueUsername
#Size(min=5,max=100 )
#Column(nullable = false)
private String username;
#NotNull(message="Email can not be null")
#Column(nullable = false)
private String email;
#NotNull(message="Password can not be null")
#Size(min = 4, max=16 , message = "Password must be a minimum of 4 characters and a maximum of 16 characters. ")
#Column(nullable = false)
#JsonIgnore
private String password;
#OneToMany(mappedBy = "buyer")
#JsonManagedReference(value="bidder")
private List<Bid> bids;
#OneToMany(mappedBy = "creator")
#JsonManagedReference(value="sell")
private List<Auction> productsOnSale;
#OneToMany(mappedBy = "buyer")
#JsonManagedReference(value="buyer")
private List<Auction> biddedProducts;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "users_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Collection<Role> roles;
private String image;
private boolean isApproved;
//------------------------------
public User() {
}
public User(UserWithoutRole user) {
this.name = user.getName();
this.email = user.getEmail();
this.username=user.getUsername();
this.image=user.getImage();
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<Role> roles = getRoles();
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
#Override
#JsonIgnore
public boolean isAccountNonExpired() {
return true;
}
#Override
#JsonIgnore
public boolean isAccountNonLocked() {
return true;
}
#Override
#JsonIgnore
public boolean isCredentialsNonExpired() {
return true;
}
#Override
#JsonIgnore
public boolean isEnabled() {
return true;
}
}
.
#Data
#Entity
public class Bid {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name = "buyer_id")
#JsonBackReference(value="bidder")
private User buyer;
#ManyToOne(cascade=CascadeType.MERGE)
#JoinColumn(name = "auction_id")
#JsonBackReference(value="selling-item")
private Auction auction;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable = false)
private Date bidTime;
#NotNull
#Column(nullable = false)
private int price;
}
Where is my mistake idk. If I have to use #JsonIgnore for getters should i delete #Data and where should i use #JsonIgnore. I tried like this but didn't work.
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name = "creator_id")
#JsonBackReference(value="sell")
#JsonIgnore
private User creator;

#JsonIgnoreProperties JPA - Not ignoring properties

I am having a faq entity as below. Here createdBy field is having a manyToOne relationship with the user entity. Below joinColumns shows the association.
In the User entity, i have OneToMany relationship with UserRoles and UsersUnit which is EAGER load for User and not for faq. So i added #JsonIgnoreProperties
for UsersUnit and UsersRole and the corresponding User entity is shown below.
#Entity
#Table(name = "FAQ", catalog="abc")
public class Faq implements Serializable {
public Faq() {
super();
}
#Column(name = "CREATE_DATE")
private Timestamp createDate;
#Where(clause = "DELETE_DATE is null")
#Column(name = "DELETE_DATE")
private Timestamp deleteDate;
#Column(name = "DELETED_BY")
private BigDecimal deletedBy;
#Column(name = "DOC_BLOB", nullable = false)
#JsonIgnore
private byte[] docBlob;
#Column(name = "DOC_NAME", nullable = false, length = 100)
private String docName;
#Id
private BigDecimal id;
#Column(name = "ORDER_BY")
private BigDecimal orderBy;
#Column(name = "UPDATE_DATE")
private Timestamp updateDate;
#Column(name = "UPDATED_BY")
private BigDecimal updatedBy;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumns({
#JoinColumn(name="created_by", referencedColumnName="id")
})
private User faqCreatedBy;
}
User entity:
#Entity
#Table(name = "USERS", catalog="abc")
#JsonInclude(Include.NON_NULL)
public class User extends EntityLog{
private BigDecimal id;
private BigDecimal edipi;
private String firstname;
private String lastname;
private String email;
..///
private Set<UsersRoles> userRoles;
private Set<UsersUnit> usersUnit;
#Id
#Column(name="id")
public BigDecimal getId() {
return id;
}
...///
#Column
#JsonIgnoreProperties({ "faqCreatedBy" })
#OneToMany(fetch = FetchType.EAGER,mappedBy = "user",cascade = {CascadeType.ALL})
#JsonManagedReference
public Set<UsersRoles> getUserRoles() {
return userRoles;
}
...///
#Column
#JsonIgnoreProperties({ "faqCreatedBy" })
#OneToMany(fetch = FetchType.EAGER,mappedBy = "user",cascade = {CascadeType.ALL})
#JsonManagedReference
public Set<UsersUnit> getUsersUnit() {
return usersUnit;
}
////...
}
With this change I am expecting the faq to load with User entity but I am not execting UsersRoles and UsersUnit to load.
But that is not what i see. When faq loads it loads User and UsersRoles and UsersUnit. I am using Spring JPA fyi. Any leads what is wrong ? Appreciate any inputs.

Reciving more data than expected

(This question has a spanish version: Pregunta español StackOverflow)
Hello,
im creating a API-REST with springboot, hibernate ...
In one controller, im returning one entity, the point is, when i do this:
Empresa company= empresaManager.findById(2L);
return company;
returns exactly what i expect, (the object company has a list of students, and has only 2 vinculated).
But when instead of use a number, what i do is get the students, and afterwards, return the company of the students, the company that its returning me comes with 12 students (6 times repeated each student)
String token = request.getHeader("Authorization");
token = token.replace("Bearer ", "");
Usuario usuario = tokenManager.getUsuarioFromToken(token);
Long id = usuario.getEmpresa().getIdempresa();
Empresa empresaOriginal = empresaManager.findById(id);
return empresaOriginal;
Any chance you know why is happenning this ?
This is how should return the object company:
And this is how im actually getting it:
From here, to down, is what is asked in comments
This is my user entity :
#Entity
#Table(name = "usuario")
public class Usuario {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idusuario")
private Long idusuario;
#Column(name = "nombre", length = 30, nullable = false)
private String nombre;
#Column(name = "email", length = 80, nullable = false)
private String email;
#JsonIgnore
#Column(name = "contraseña", length = 300, nullable = false)
private String contraseña;
#JsonIgnore
#ManyToOne
#JoinColumn(foreignKey = #ForeignKey(name = "empresa_idempresa"), name = "empresa_idempresa")
private Empresa empresa;
#OneToMany(mappedBy = "usuario", orphanRemoval = true, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Fichaje> fichajes;
public Usuario() {
}
public Empresa getEmpresa() {
return empresa;
}
public void setEmpresa(Empresa empresa) {
this.empresa = empresa;
}
}
This is my Company entity:
#Entity
#Table(name = "empresa")
public class Empresa {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idempresa")
private Long idempresa;
#Column(name = "nombre", length = 100, nullable = false)
private String nombre;
#Column(name = "contacto", length = 300, nullable = false)
private String contacto;
#Column(name = "fecha_inicio_practicas", columnDefinition = "DATE")
private LocalDate inicioPracticas;
#Column(name = "direccion", length = 100)
private String direccion;
#Column(name = "foto_empresa")
private String fotoEmpresa;
#OneToMany(mappedBy = "empresa", orphanRemoval = true, cascade = CascadeType.ALL)
private List<EmpresaTieneDia> empresaTieneDias;
#OneToMany(mappedBy = "empresa", orphanRemoval = false, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Usuario> estudiantes;
public Empresa() {
}
public Long getIdempresa() {
return idempresa;
}
public void setIdempresa(Long idempresa) {
this.idempresa = idempresa;
}
public List<Usuario> getEstudiantes() {
return estudiantes;
}
public void setEstudiantes(List<Usuario> estudiantes) {
this.estudiantes = estudiantes;
}
}
This is the findById:
(Service or Manager)
public Empresa findById(Long id) {
return this.empresaRepository.findByIdempresa(id);
}
(Repository or DAO)
public interface EmpresaRepository extends CrudRepository<Empresa, Long> {
Empresa findByIdempresa(Long id);
}
SOLVED
I had to change my listo of users from a List<Usuario> to a Set<Usuario>.
Anyways, I understand why it fixes it using a Set (cause doesn't let duplicated values in it).
Anyways, if someone could try to explain my why in the first moment I'm having 6 times duplicated every item in the list i would apreciate it.
Thanks !! :D

Create a product in a category hibernate - Transcient issue

I use two class as models to build a JSON :
The productCreateRequestModel:
#Getter #Setter
public class ProductCreateRequestModel {
private Long id;
private String name;
private double price;
private int qty;
private String imgPath;
private CategoryRequestCreateProductModel category;
}
My CategoryRequestCreateProductModel
#Getter #Setter
public class CategoryRequestCreateProductModel {
private Long id;
private String name;
private String categoryKeyId;
}
I created 2 entities to manage categories and products.
#Entity
#Table(name="products")
#Getter #Setter
public class ProductEntity {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
#Column(nullable = false)
private String productKeyId;
// many to one relationship with category
#ManyToOne
#JoinColumn(name = "category_id")
private CategoryEntity category;
#Column(nullable = false)
private String name;
#Column(nullable = false)
private double price;
#Column(nullable = false)
private int qty;
private String imgPath;
}
And :
#Entity
#Table(name="categories")
#Getter #Setter
public class CategoryEntity {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
#Column(length = 30, nullable = false)
private String categoryKeyId;
#Column(nullable = false)
private String name;
#ManyToOne(optional = true, fetch = FetchType.LAZY)
#JoinColumn(name="parent_id", nullable=true)
private CategoryEntity parentCategory;
// allow to delete also subcategories
#OneToMany(mappedBy="parentCategory", cascade = CascadeType.ALL)
private List<CategoryEntity> subCategories;
//Here mappedBy indicates that the owner is in the other side
#OneToMany(fetch = FetchType.EAGER, mappedBy = "category", cascade = CascadeType.REMOVE)
private List<ProductEntity> products;
}
This generated this table in the database.
In my controller:
public ProductRestResponseModel createProduct(#RequestBody ProductCreateRequestModel productCreateRequestModel) throws Exception {
ProductRestResponseModel returnValue = new ProductRestResponseModel();
if(productCreateRequestModel.getName().isEmpty() || productCreateRequestModel.getPrice() <= 0)
throw new ApplicationServiceException(ErrorMessages.MISSING_REQUIRED_FIELDS.getErrorMessage());
ModelMapper modelMapper = new ModelMapper();
ProductDto productDto = modelMapper.map(productCreateRequestModel, ProductDto.class);
ProductDto createdProduct = productService.createProduct(productDto);
returnValue = modelMapper.map(createdProduct, ProductRestResponseModel.class);
return returnValue;
}
In my Service I use the DTO:
#Override
public ProductDto createProduct(ProductDto productDto) {
ProductDto returnValue = new ProductDto();
if (productRepository.findByName(productDto.getName()) != null)
throw new ApplicationServiceException("Record already in Database");
ModelMapper modelMapper = new ModelMapper();
ProductEntity productEntity = modelMapper.map(productDto, ProductEntity.class);
String productKeyId = utils.generateProductKeyId(30);
productEntity.setProductKeyId(productKeyId);
ProductEntity storedProduct = productRepository.save(productEntity);
returnValue = modelMapper.map(storedProduct, ProductDto.class);
return returnValue;
}
My issue is when I send a post request with this object :
{
"name": "Pizza",
"price": 344.0,
"qty": 15,
"imgPath": "new/pathImage",
"category": {
"categoryKeyId": "23ume70Fu6yqyGUWfQkW110P4ko3gZ",
"name": "CatName"
}
}
When i send this request I obtain an error message : org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.app.ws.io.entity.ProductEntity.category -> com.app.ws.io.entity.CategoryEntity
My problem is that the Category already exists in the database and that i just need to set the foreign key in the product table

Categories

Resources