Error when trying to map foreing key in SpringBoot - java

I'm trying to create an API for saving a Person and its Address, like in this model:
And i'm getting this error when trying to save an address with a foreing key:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error:
Cannot construct instance of `com.apitest.api.model.Pessoa` (although at least one Creator exists):
no int/Int-argument constructor/factory method to deserialize from Number value (1)]
I know it seems like a parser error, but it just happens when i do a request that contains the fk field, so:
This is a valid request:
{
"logradouro": "test",
"cep": "354",
"numero": "test",
"cidade": "test"
}
This one i get a 400 bad request:
{
"logradouro": "null",
"cep": "354",
"numero": "null",
"cidade": "null",
"pessoa": 1
}
Just by adding the fk field, like i said.
Models:
Person
package com.apitest.api.model;
import java.util.Date;
import java.util.List;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
#Entity
#Table(name = "pessoa")
public class Pessoa {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "nome")
private String nome;
#Column(name = "dataNascimento")
private Date dataNascimento;
public Pessoa(Integer id, String nome, Date dataNascimento) {
this.id = id;
this.nome = nome;
this.dataNascimento = dataNascimento;
}
public Pessoa(){
};
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
}
Address
package com.apitest.api.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
#Entity
#Table(name = "endereco")
public class Endereco {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id_endereco;
#Column(name = "logradouro")
private String logradouro;
#Column(name = "cep")
private String cep;
#Column(name = "numero")
private String numero;
#Column(name = "cidade")
private String cidade;
#ManyToOne
#JoinColumn(name = "id")
private Pessoa pessoa;
public Endereco(Integer id_endereco, String logradouro, String cep, String numero, String cidade, Pessoa pessoa) {
this.id_endereco = id_endereco;
this.logradouro = logradouro;
this.cep = cep;
this.numero = numero;
this.cidade = cidade;
this.pessoa = pessoa;
}
public Endereco(){
};
public String getLogradouro() {
return logradouro;
}
public void setLogradouro(String logradouro) {
this.logradouro = logradouro;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
public Integer getId_endereco() {
return id_endereco;
}
public void setId_endereco(Integer id_endereco) {
this.id_endereco = id_endereco;
}
}
Controllers:
Person
package com.apitest.api.controller;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import com.apitest.api.model.Pessoa;
import com.apitest.api.service.PessoaService;
#RestController
public class PessoaController {
#Autowired
private PessoaService pessoaService;
#PostMapping("/pessoas")
public ResponseEntity<Pessoa> createPessoa(#RequestBody Pessoa pessoa){
return ResponseEntity.ok().body(this.pessoaService.createPessoa(pessoa));
}
}
Address
package com.apitest.api.controller;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import com.apitest.api.model.Endereco;
import com.apitest.api.service.EnderecoService;
#RestController
public class EnderecoController {
#Autowired
private EnderecoService enderecoService;
#PostMapping("/endereco")
public ResponseEntity<Endereco> createEndereco(#RequestBody Endereco endereco){
return ResponseEntity.ok().body(this.enderecoService.createEndereco(endereco));
}
}
Service:
Person
package com.apitest.api.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.apitest.api.model.Pessoa;
import com.apitest.api.repository.PessoaRepository;
#Service
#Transactional
public class PessoaServiceImpl implements PessoaService {
#Autowired
private PessoaRepository pessoaRepository;
#Override
public Pessoa createPessoa(Pessoa pessoa) {
return pessoaRepository.save(pessoa);
}
#Override
public Pessoa updatePessoa(Pessoa pessoa) {
Optional<Pessoa> pessoaDb = this.pessoaRepository.findById(pessoa.getId());
Pessoa pessoaUpdate = pessoaDb.get();
pessoaUpdate.setId(pessoa.getId());
pessoaUpdate.setNome(pessoa.getNome());
return pessoaUpdate;
}
#Override
public Pessoa getPessoaById(Pessoa pessoa) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<Pessoa> getAllPessoa() {
// TODO Auto-generated method stub
return null;
}
#Override
public void deletePessoa(long pessoaId) {
// TODO Auto-generated method stub
}
}
Address
package com.apitest.api.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apitest.api.model.Endereco;
import com.apitest.api.repository.EnderecoRepository;
import com.apitest.api.repository.PessoaRepository;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class EnderecoServiceImpl implements EnderecoService {
#Autowired
private EnderecoRepository enderecoRepository;
#Override
public Endereco createEndereco(Endereco endereco) {
return enderecoRepository.save(endereco);
}
}
I have already tried to use JsonCreator and JsonProperty annotations but did not worked for me...
Any help would be appreciated.

You're getting this error because you're sending the value of "1" for the object Pessoa. You need to pass the fields in the object, something like this should work.
{ "logradouro": "null", "cep": "354", "numero": "null", "cidade": "null", "pessoa": {"id": 1} }
Also, I'm not sure what "null" means here, but if you want those fields to be null, don't send them. The way this is written, you're going to end up with the word null everywhere.

Related

spring boot crud api receive 404 error from post request: postman

I am working on the CRUD rest API and application is turning on but when I'm trying to make a post request there is a: "status": 404, "error": "Not Found". On the postman, I also add header content-type: application/JSON and requesting at URL: http://localhost:8080/tickets.
Do you know guys how to fix this?
Here is the code.
model:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table
public class Tickets {
#Id
#Column
private int ticketid;
#Column
private String title;
#Column
private String description;
#Column
private String creationDate;
#Column
private String severity;
#Column
private String status;
public int getTicketid() {
return ticketid;
}
public void setTicketid(int ticketid) {
this.ticketid = ticketid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
controller:
import com.cisco.interview.model.Tickets;
import com.cisco.interview.service.TicketsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class TicketsController {
#Autowired
TicketsService ticketsService;
#GetMapping("/ticket")
private List<Tickets> getAllTickets() {
return ticketsService.getAllTickets();
}
#GetMapping("/ticket/{ticketid}")
private Tickets getTicket(#PathVariable("ticketid")int ticketid) {
return ticketsService.getTicketsById(ticketid);
}
#DeleteMapping("/ticket/{ticketid}")
private void deleteTicket(#PathVariable("ticketid")int ticketid) {
ticketsService.deleteTicket(ticketid);
}
#PostMapping(value = "/tickets")
private int saveTicket(#RequestBody Tickets tickets) {
ticketsService.saveUpdateTicket(tickets);
return tickets.getTicketid();
}
#PutMapping("/tickets")
private Tickets updateTicket(#RequestBody Tickets tickets) {
ticketsService.saveUpdateTicket(tickets);
return tickets;
}
}
service:
import com.cisco.interview.model.Tickets;
import com.cisco.interview.repository.TicketsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
#Service
public class TicketsService {
#Autowired
TicketsRepository ticketsRepository;
public List<Tickets> getAllTickets() {
List<Tickets> tickets = new ArrayList<Tickets>();
ticketsRepository.findAll().forEach(tickets1 -> tickets.add(tickets1));
return tickets;
}
public Tickets getTicketsById(int id) {
return ticketsRepository.findById(id).get();
}
public void saveUpdateTicket(Tickets tickets) {
ticketsRepository.save(tickets);
}
public void deleteTicket(int id) {
ticketsRepository.deleteById(id);
}
public void update(Tickets tickets, int ticketid) {
ticketsRepository.save(tickets);
}
}
repository:
import com.cisco.interview.model.Tickets;
import org.springframework.data.repository.CrudRepository;
public interface TicketsRepository extends CrudRepository<Tickets, Integer> {
}
im trying to make a post request at postman and getting 404 error
Have you specify the POST method in Postman ?
And the body of your request ?
Postam sample

Getting null value in db when using #embbeded in Spring boot Rest api? new to java help me out guys

Getting null values in database for the embedded Address entity. Using MySql database. The user entity is storing values fine but embedded Address entity is returning null value, can't figure out why it's not working. help me out guys.I am a beginner tried searching everywhere but no luck. Just a novice Api but it won't work the way i want it's really annoying.
Model class
package com.example.demo;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class User {
#Id
private int id;
private String name;
#Embedded
private Address address;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return "user [id=" + id + ", name=" + name + ",Address="+address+" ]";
}
public User(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
---------------------------------------------------------------------------------------------------------
**Model class**
package com.example.demo;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String cityname;
private String streetname;
private String Housename;
public Address() {
}
public Address(String cityname, String streetname, String housename) {
super();
this.cityname = cityname;
this.streetname = streetname;
Housename = housename;
}
public String getStreetname() {
return streetname;
}
public void setStreetname(String streetname) {
this.streetname = streetname;
}
public String getHousename() {
return Housename;
}
public void setHousename(String housename) {
Housename = housename;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
}
---------------------------------------------------------------------------------------------------------
**controller class**
package com.example.demo;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Croller {
#Autowired
TestRepo repo;
#PostMapping("/add")
public String save(#RequestBody User mode) {
repo.save(mode);
return "details saved";
}
#GetMapping("/get")
public List<User> retrive(){
return repo.findAll();
}
#GetMapping("/search")
public List<User> searchname(#RequestParam("name")String name){
return repo.name(name);
}
#GetMapping("/byid/{id}")
public Optional <User> getone (#PathVariable int id){
return repo.findById(id);
}
#PutMapping("/update")
public String updateid(#RequestBody User mode ) {
repo.save(mode);
return " user updated sucessfully";
}
#DeleteMapping("/remove/{id}")
public String delete(#PathVariable int id) {
repo.deleteById(id);
return "deleted with the given id:"+ id;
}
}
---------------------------------------------------------------------------------------------------------
Repository
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository <User, Integer> {
List <User> name(String name);
}
**Application.java**
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Demoapi2Application {
public static void main(String[] args) {
SpringApplication.run(Demoapi2Application.class, args);
}
}
Your request has to match the #RequestBody object for spring to map the keys appropriately
Try this request -
{
"id":19,
"name":"Alex",
"address":{
"cityname":"california",
"streetname":"ring road",
"Housename":"Housename"
}
}
Please make sure you give input as per your Model.

JPA with Spring MVC doesn't insert into database using persist

I am using spring 4 and hibernate 4 to create some web services and when I try to retrieve data from the database. It work fine but the problem is when I try to insert data.
When I lunch the project as a java application every thing work fine. The problem is only when I lunch it on the server and I am using tomcat.
This is my entity:
package com.pfe.ecole.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import com.fasterxml.jackson.annotation.JsonIgnore;
#SuppressWarnings("serial")
#Entity
public class Specialite implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String specialite;
#ManyToMany(mappedBy="specialites")
#JsonIgnore
private List<Professeur> professeurs;
public List<Professeur> getProfesseurs() {
return professeurs;
}
public void setProfesseurs(List<Professeur> professeurs) {
this.professeurs = professeurs;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSpecialite() {
return specialite;
}
public void setSpecialite(String specialite) {
this.specialite = specialite;
}
public Specialite() {
// TODO Auto-generated constructor stub
}
public Specialite(int id, String specialite) {
super();
this.id = id;
this.specialite = specialite;
}
public Specialite(String specialite) {
super();
this.specialite = specialite;
}
}
package com.pfe.ecole.entity;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#SuppressWarnings("serial")
#Entity
public class Professeur implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#Column(unique=true, nullable=false)
private String cin;
#Column(unique=true, nullable=false)
private int tel;
#ManyToMany(targetEntity=Specialite.class, cascade = CascadeType.PERSIST)
private Set<Specialite> specialites;
private String nom;
private String prenom;
#Column(unique=true, nullable=false)
private String email;
private String adresse;
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public Set<Specialite> getSpecialites() {
return specialites;
}
public void setSpecialite(Set<Specialite> specialites) {
this.specialites = specialites;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCin() {
return cin;
}
public void setCin(String cin) {
this.cin = cin;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
public Professeur() {
// TODO Auto-generated constructor stub
}
public Professeur(String cin, int tel, Set<Specialite> specialites, String nom, String prenom, String email,
String adresse) {
super();
this.cin = cin;
this.tel = tel;
this.specialites = specialites;
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.adresse = adresse;
}
public Professeur(long id, String cin, int tel, Set<Specialite> specialites, String nom, String prenom,
String email, String adresse) {
super();
this.id = id;
this.cin = cin;
this.tel = tel;
this.specialites = specialites;
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.adresse = adresse;
}
}
and this is my services
package com.pfe.ecole.services;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pfe.ecole.entity.Agent;
import com.pfe.ecole.entity.Specialite;
#Service("specialiteImpl")
#Transactional
public class SpecialiteImpl implements ISpecialite{
#PersistenceContext
private EntityManager em;
#Override
public Specialite add(Specialite specialite) {
em.persist(new Agent());
return specialite;
}
#Override
public Specialite update(Specialite specialite) {
em.persist(specialite);
return specialite;
}
#SuppressWarnings("unchecked")
#Override
public List<Specialite> listAllSpecialite() {
return em.createQuery("select s from Specialite s").getResultList();
}
}
package com.pfe.ecole.services;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pfe.ecole.entity.Professeur;
import com.pfe.ecole.entity.Specialite;
#Service("professeurImpl")
#Transactional
public class ProfesseurImpl implements IProfesseur{
#PersistenceContext
private EntityManager em;
#SuppressWarnings("unchecked")
#Override
public List<Professeur> listAll(int page, int items) {
List<Professeur> profList;
profList=em.createQuery("select p from Professeur p order by p.prenom").setFirstResult(page-1).setMaxResults(items).getResultList();
return profList;
}
#Override
public Professeur findByCin(int cin) {
Query req=em.createQuery("select p from Professeur p where p.cin=:cin").setParameter("cin", cin);
try{
return (Professeur) req.getSingleResult();
}
catch(NoResultException nrEx) {
return null;
}
}
#SuppressWarnings("unchecked")
#Override
public List<Professeur> findByNom(String nom) {
Query req = em.createQuery("select p from Professeur p where p.nom=:nom ").setParameter("nom", nom);
return req.getResultList();
}
#Override
public List<Professeur> listProfBySpec(Specialite spec) {
List<Professeur> profs = new ArrayList<Professeur>();
profs.addAll(spec.getProfesseurs());
return profs;
}
#Override
public Professeur add(Professeur professeur) {
em.persist(professeur);
return professeur;
}
#Override
public Professeur update(Professeur professeur) {
em.persist(professeur);
return professeur;
}
#Override
public int count() {
// TODO Auto-generated method stub
return (int) em.createQuery("select COUNT(p) from Professeur p").getFirstResult();
}
}
and this is the controller
package com.pfe.ecole.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.pfe.ecole.entity.Specialite;
import com.pfe.ecole.services.ISpecialite;
#Controller
#RestController
#EnableWebMvc
#CrossOrigin
public class SpecialiteCtrl {
#Autowired
ISpecialite metier;
#RequestMapping(value="/specialites",method=RequestMethod.GET)
#ResponseBody Map<String, List<Specialite>> get(){metier.add(new Specialite("ddd"));
Map<String, List<Specialite>> result = new HashMap<String,List<Specialite>>();
result.put("content", metier.listAllSpecialite());
return result;
}
}
package com.pfe.ecole.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.pfe.ecole.entity.Professeur;
import com.pfe.ecole.services.IProfesseur;
import com.pfe.ecole.services.Page;
#Controller
#RestController
#EnableWebMvc
#CrossOrigin
public class ProfCtrl {
#Autowired
IProfesseur metier;
#RequestMapping(value="/teacher",method=RequestMethod.POST)
#ResponseBody Professeur add(#RequestBody Professeur professeur) {
return metier.add(professeur);
}
#RequestMapping(value="/teachers/{page}/{items}",method=RequestMethod.GET)
#ResponseBody Page getByParm(#PathVariable("page") int page, #PathVariable("items") int items){
return getAll(page, items);
}
#RequestMapping(value="/teachers/{page}",method=RequestMethod.GET)
#ResponseBody Page getByParm(#PathVariable("page") int page){
return getAll(page, 10);
}
#RequestMapping(value="/teachers",method=RequestMethod.GET)
#ResponseBody Page getByParm(){
return getAll(1, 10);
}
private Page getAll(int page, int items){
return new Page(page,metier.count(),metier.listAll(page, items));
}
}
this is the test that works as java application
public static void main(String[] args) {
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("root-context.xml");
ISpecialite m = (ISpecialite) context.getBean("specialiteImpl");
Specialite s= new Specialite("Web Dev");
m.add(s);
}
This is the error I am getting
javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
adding this annotation to service solved the problem #EnableTransactionManagement

jackson List of subclasses deserialisation

I am working on a webservice where i am supposed to provide xml as response, I am using jackson for that. I am stuck at an issue, I have an abstract class:
package com.spinner.jackson;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText;
public class ClientObject {
#JacksonXmlElementWrapper(useWrapping = false)
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
private List<MyItem> accounts;
public ClientObject(List<MyItem> pl) {
this.accounts = pl;
}
public ClientObject() {
this.accounts = new ArrayList<MyItem>();
}
#JsonDeserialize(using = CustomDeserial.class)
public void setL(List<MyItem> l) {
this.accounts = l;
}
public List<MyItem> getAccounts() {
// TODO Auto-generated method stub
return this.accounts;
}
}
and then I have sub classes as follow:
package com.spinner.jackson;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#JacksonXmlRootElement(localName="itemA")
public class MySubItemA extends MyItem {
public MySubItemA() {
super();
// TODO Auto-generated constructor stub
}
public MySubItemA(int id, String name) {
super(id, name);
// TODO Auto-generated constructor stub
}
private String itemAProperty1;
private String itemAProperty2;
public String getItemAProperty1() {
return this.itemAProperty1;
}
public void setItemAProperty1(String itemAProperty1) {
this.itemAProperty1 = itemAProperty1;
}
public String getItemAProperty2() {
return this.itemAProperty2;
}
public void setItemAProperty2(String itemAProperty2) {
this.itemAProperty2 = itemAProperty2;
}
#JsonCreator
public MySubItemA(#JsonProperty("id")int id, #JsonProperty("name")String name, #JsonProperty("itemAProperty1")String p1, #JsonProperty("itemAProperty2")String p2) {
super(id, name);
this.itemAProperty1 = p1;
this.itemAProperty2 = p2;
}
}
another sub class
package com.spinner.jackson;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
#JacksonXmlRootElement(localName="itemB")
public class MySubItemB extends MyItem {
private int itemBProperty1;
private String itemBProperty2;
public int getItemBProperty1() {
return this.itemBProperty1;
}
public void setItemBProperty1(int itemBProperty1) {
this.itemBProperty1 = itemBProperty1;
}
public String getItemBProperty2() {
return this.itemBProperty2;
}
public void setItemBProperty2(String itemBProperty2) {
this.itemBProperty2 = itemBProperty2;
}
public MySubItemB(#JsonProperty("id")int id, #JsonProperty("name")String name, #JsonProperty("itemBProperty1")int p1, #JsonProperty("itemBProperty2")String p2) {
super(id, name);
this.itemBProperty1 = p1;
this.itemBProperty2 = p2;
}
}
and a client class as followed:
package com.spinner.jackson;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText;
public class ClientObject {
#JacksonXmlElementWrapper(useWrapping = false)
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
private List<MyItem> accounts;
public ClientObject(List<MyItem> pl) {
this.accounts = pl;
}
public ClientObject() {
this.accounts = new ArrayList<MyItem>();
}
#JsonDeserialize(using = CustomDeserial.class)
public void setL(List<MyItem> l) {
this.accounts = l;
}
#JsonDeserialize(using = CustomDeserial.class)
public List<MyItem> getAccounts() {
// TODO Auto-generated method stub
return this.accounts;
}
}
MyItem Class:
package com.spinner.jackson;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
#XmlRootElement
public abstract class MyItem {
public MyItem() {
super();
// TODO Auto-generated constructor stub
}
private int id;
private String name;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public MyItem(int id, String name) {
this.id = id;
this.name = name;
}
}
above generate output xml as followed
<ClientObject>
<accounts>
<MySubItemA>
....
</MySubItemA>
</accounts>
<accounts>
<MySubItemB>
....
</MySubItemB>
</accounts>
</ClientObject>
is there a way to remove <accounts> wrapper even though I am using #JacksonXmlElementWrapper(useWrapping = false), also if I remove this annotation it does something as followed
<ClientObject>
<accounts>
<accounts>
<MySubItemA>
....
</MySubItemA>
</accounts>
<accounts>
<MySubItemB>
.....
</MySubItemB>
</accounts>
</accounts>
</ClientObject>
so final output should be
<ClientObject>
<MySubItemA>
....
</MySubItemA>
<MySubItemB>
....
</MySubItemB>
</ClientObject>
thanks for your help.
Best regards
Sajid
I was able to figure it out so I think it may help someone else:
I created Serializer
package com.spinner.jackson;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class MySerial extends JsonSerializer<ClientObject>
{
public void serialize(ClientObject value, JsonGenerator jgen,
SerializerProvider provider)
throws IOException, JsonProcessingException
{
jgen.writeObjectFieldStart(value.getClass().getSimpleName());
jgen.writeObjectField(value.getAccounts().get(0).getClass().getSimpleName(), value.getAccounts().get(0));
jgen.writeObjectField(value.getAccounts().get(1).getClass().getSimpleName(), value.getAccounts().get(1));
jgen.writeObjectField(value.getAccounts().get(2).getClass().getSimpleName(), value.getAccounts().get(2));
jgen.writeObjectField(value.getAccounts().get(3).getClass().getSimpleName(), value.getAccounts().get(3));
}
}
and next I did following in ClientObject.java:
package com.spinner.jackson;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
#JsonSerialize(using = CustomDeserial.class)
public class ClientObject {
#JacksonXmlElementWrapper(useWrapping = false)
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
private List<MyItem> accounts;
public ClientObject(List<MyItem> pl) {
this.accounts = pl;
}
public ClientObject() {
this.accounts = new ArrayList<MyItem>();
}
public void setL(List<MyItem> l) {
this.accounts = l;
}
public List<MyItem> getAccounts() {
return this.accounts;
}
}
and voila it worked, hope this helps some one.

How Filter data When key attribute is in child Table +spring mvc and hibernate

There are 2 table, Parent is MeetingTypes Child is Meetings they have1 : m mapping
Meeting has releaseID atribute so i want to filter its by releaseID .but problem is, its in Child Table...
If it is Parent Table we can do it simply and it is working
Query query = session.getCurrentSession().createQuery("from MeetingTypes where releaseID= :releaseID");
query.setParameter("releaseID", releaseID);
List list = query.list();
if(list!=null && list.size()>0){
return list;
}else{
return null;
}
I tried it this way
Query query = session.getCurrentSession().createSQLQuery(
"from MeetingTypes mt join mt.Meetings m " +
"where m.releaseID = :releaseID");
query.setParameter("releaseID", releaseID);
return query.list();
But give bellow Erro
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from MeetingTypes mt join mt.Meetings m where m.releaseID = 192' at
line 1
relevant tabales
package pearson.dashboard.model;
import java.util.List;
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;
#Entity
public class MeetingTypes {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int meetingTypeID;
#Column
private String typeName;
#OneToMany(mappedBy = "meetingTypes",fetch = FetchType.EAGER)
private List<Meetings> meetings;
public List<Meetings> getMeetings() {
return meetings;
}
public void setMeetings(List<Meetings> meetings) {
this.meetings = meetings;
}
public MeetingTypes() {
// TODO Auto-generated constructor stub
}
public MeetingTypes(int meetingTypeID, String typeName
) {
super();
this.meetingTypeID = meetingTypeID;
this.typeName = typeName;
}
public int getMeetingTypeID() {
return meetingTypeID;
}
public void setMeetingTypeID(int meetingTypeID) {
this.meetingTypeID = meetingTypeID;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
package pearson.dashboard.model;
import java.util.Date;
import java.util.List;
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 org.springframework.context.annotation.Lazy;
#Entity
public class Meetings {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int meetingID;
#Column
private Date sheduleTime;
#Column
private String meetingHeading;
#Column
private String comment;
#Column
private String roomName;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "meetingTypeID")
private MeetingTypes meetingTypes;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "releaseID")
private Releases releases;
public Releases getReleases() {
return releases;
}
public void setReleases(Releases releases) {
this.releases = releases;
}
public MeetingTypes getMeetingTypes() {
return meetingTypes;
}
public void setMeetingTypes(MeetingTypes meetingTypes) {
this.meetingTypes = meetingTypes;
}
public Meetings() {
// TODO Auto-generated constructor stub
}
public Meetings(int meetingID, Date sheduleTime, String meetingHeading,
String comment, String roomName) {
super();
this.meetingID = meetingID;
this.sheduleTime = sheduleTime;
this.meetingHeading = meetingHeading;
this.comment = comment;
this.roomName = roomName;
}
public int getMeetingID() {
return meetingID;
}
public void setMeetingID(int meetingID) {
this.meetingID = meetingID;
}
public Date getSheduleTime() {
return sheduleTime;
}
public void setSheduleTime(Date sheduleTime) {
this.sheduleTime = sheduleTime;
}
public String getMeetingHeading() {
return meetingHeading;
}
public void setMeetingHeading(String meetingHeading) {
this.meetingHeading = meetingHeading;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getRoomName() {
return roomName;
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
}
package pearson.dashboard.model;
import java.util.Date;
import java.util.List;
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 org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
#Entity
public class Releases {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int releaseID;
#Column
private String orcleCode;
#Column
private String status;
#Column
private Date staging;
#Column
private Date cabCall;
#Column
private Date rrr;
#Column
private String remarks;
#Column
private String releaseName;
#Column
private Date prodDate;
#ManyToOne( fetch = FetchType.EAGER)
#JoinColumn(name = "teamID")
private Teams teams;
public Teams getTeams() {
return teams;
}
public void setTeams(Teams teams) {
this.teams = teams;
}
#OneToMany(mappedBy = "releases",fetch = FetchType.EAGER)
#Fetch(value = FetchMode.SUBSELECT)
private List<Meetings> meetings;
public List<Meetings> getMeetings() {
return meetings;
}
public void setMeetings(List<Meetings> meetings) {
this.meetings = meetings;
}
public Releases() {}
public Releases(int releasID, String orcleCode, String status,
Date staging, Date cabCall, Date rrr, String remarks,
String releaseName,Date prodDate) {
super();
this.releaseID = releasID;
this.orcleCode = orcleCode;
this.status = status;
this.staging = staging;
this.cabCall = cabCall;
this.rrr = rrr;
this.remarks = remarks;
this.releaseName = releaseName;
this.prodDate = prodDate;
}
public int getReleaseID() {
return releaseID;
}
public void setReleaseID(int releaseID) {
this.releaseID = releaseID;
}
public String getOrcleCode() {
return orcleCode;
}
public void setOrcleCode(String orcleCode) {
this.orcleCode = orcleCode;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getStaging() {
return staging;
}
public void setStaging(Date staging) {
this.staging = staging;
}
public Date getCabCall() {
return cabCall;
}
public void setCabCall(Date cabCall) {
this.cabCall = cabCall;
}
public Date getRrr() {
return rrr;
}
public void setRrr(Date rrr) {
this.rrr = rrr;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getReleaseName() {
return releaseName;
}
public void setReleaseName(String releaseName) {
this.releaseName = releaseName;
}
public Date getProdDate() {
return prodDate;
}
public void setProdDate(Date prodDate) {
this.prodDate = prodDate;
}
}
part of Controller******
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pearson.dashboard.dto.NewMeeting;
import pearson.dashboard.service.MeetingService;
import pearson.dashboard.service.MeetingTypeService;
import pearson.dashboard.service.MemberService;
import pearson.dashboard.service.SwarmingScheduleService;
#Controller
public class MeetingTypesController {
#Autowired
private MeetingTypeService meetingTypeService;
//#Autowired
//private MeetingService meetingService;
#Autowired
private SwarmingScheduleService swarmingScheduleService;
#Autowired
private MemberService memberService;
#RequestMapping(value="/detailsPage",method=RequestMethod.POST)
public String getAllmeeting(#ModelAttribute NewMeeting newMeeting,BindingResult result,Map<String, Object> map){
int releaseID = newMeeting.getReleaseID();
map.put("meetingList", meetingTypeService.getAllMeetingTypes(releaseID));
map.put("swarmingScheduleList",swarmingScheduleService.gettAllSwarming() );
map.put("memberList",memberService.gettAllMembers() );
return "details";
}
}
You are using HQL not sql so in hql no keyword like join alternatively you can implement join using objecta.objectb and so on so you have to create your query like below
Query query = session.getCurrentSession().createQuery("FROM MeetingTypes mt WHERE mt.meetings.releases.id = :releaseID");
for more details see the below link
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-joins-forms
Your HQL query should be like this
Query query = session.getCurrentSession().createQuery("FROM MeetingTypes AS mt WHERE mt.meetings.releases.id = :releaseID");
query.setParameter("releaseID", releaseID);
return query.list();
hope this will solve your problem.
hopefully your Releases Entity something like
#Entity
#Table(name="meetings")
public class Meetings {
#Id
#Column(name="meetings_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
//setter & getters
}
also you have not mentioned your name parameter in #Table() annotation is your table name is same as class name ?
#Entity
The #Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.
#Column
The #Column annotation is used to specify the details of the column to which a field or property will be mapped. If the #Column annotation is not specified by default the property name will be used as the column name.
#Table
The #Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If #Table annotation is not specified then Hibernate will by default use the class name as the table name.
createQuery() VS createSQLQuery()
createQuery()
Create a new instance of Query for the given HQL query string.
createSQLQuery()
Create a new instance of SQLQuery for the given SQL query string.

Categories

Resources