com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) - java

I'm trying implement a rest service. I have created my entitys and daos, and when use this everthyng works fine.
But when I trye expose the information in rest json, the infinite recursion error occur.
I have read many topic about this error, but not is so clear for me.
I'm have tried so many alternatives that is hard talk about each.
When I debug my code, I see that the data from dao is correctly, the problem occur when I trie use json. Whe I use jsf page works fine.
I have tried use Gson and return String in my rest method, but stackoverflow error occur to.
Bellow I post my implememtation (all), because a dont have idea about the problem.
I using wildfly server...
Thanks in advance
Model's
#Entity
#Table(name="usertable")
#NamedQuery(name="UserModel.findAll", query="SELECT u FROM UserModel u")
#XmlRootElement
public class UserModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private String USId;
#Temporal(TemporalType.DATE)
#Column(nullable=false)
private Date userNascimento;
#Column(nullable=false, length=45)
private String USMail;
#Column(nullable=false, length=150)
private String USName;
#Column(nullable=false, length=45)
private String USNick;
#Column(nullable=false, length=45)
private String USPassword;
//bi-directional many-to-one association to UserAddressModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="usertable")
private List<UserAddressModel> listAddressModel;
//bi-directional many-to-one association to UserFoneModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="usertable")
private List<UserFoneModel> listFoneModel;
public UserModel() {
}
public String getUSId() {
return this.USId;
}
public void setUSId(String USId) {
this.USId = USId;
}
public Date getUserNascimento() {
return this.userNascimento;
}
public void setUserNascimento(Date userNascimento) {
this.userNascimento = userNascimento;
}
public String getUSMail() {
return this.USMail;
}
public void setUSMail(String USMail) {
this.USMail = USMail;
}
public String getUSName() {
return this.USName;
}
public void setUSName(String USName) {
this.USName = USName;
}
public String getUSNick() {
return this.USNick;
}
public void setUSNick(String USNick) {
this.USNick = USNick;
}
public String getUSPassword() {
return this.USPassword;
}
public void setUSPassword(String USPassword) {
this.USPassword = USPassword;
}
public List<UserAddressModel> getUseraddresstables() {
return this.listAddressModel;
}
public void setUseraddresstables(List<UserAddressModel> useraddresstables) {
this.listAddressModel = useraddresstables;
}
public UserAddressModel addUseraddresstable(UserAddressModel useraddresstable) {
getUseraddresstables().add(useraddresstable);
useraddresstable.setUsertable(this);
return useraddresstable;
}
public UserAddressModel removeUseraddresstable(UserAddressModel useraddresstable) {
getUseraddresstables().remove(useraddresstable);
useraddresstable.setUsertable(null);
return useraddresstable;
}
public List<UserFoneModel> getUserfonetables() {
return this.listFoneModel;
}
public void setUserfonetables(List<UserFoneModel> userfonetables) {
this.listFoneModel = userfonetables;
}
public UserFoneModel addUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().add(userfonetable);
userfonetable.setUsertable(this);
return userfonetable;
}
public UserFoneModel removeUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().remove(userfonetable);
userfonetable.setUsertable(null);
return userfonetable;
}
}
#Entity
#Table(name="userfonetable")
#NamedQuery(name="UserFoneModel.findAll", query="SELECT u FROM UserFoneModel u")
public class UserFoneModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private String UFId;
#Column(nullable=false)
private short UFDdd;
#Column(nullable=false)
private int UFFone;
//bi-directional many-to-one association to UserModel
#ManyToOne
#JoinColumn(name="UFUserID", nullable=false)
private UserModel usertable;
//bi-directional many-to-one association to OperadorasModel
#ManyToOne
#JoinColumn(name="UFOperadoraID", nullable=false)
private OperadorasModel operadorastable;
//bi-directional many-to-one association to TiposFoneModel
#ManyToOne
#JoinColumn(name="UFTipoTelefone", nullable=false)
private TiposFoneModel tbTipostelefone;
public UserFoneModel() {
}
public String getUFId() {
return this.UFId;
}
public void setUFId(String UFId) {
this.UFId = UFId;
}
public short getUFDdd() {
return this.UFDdd;
}
public void setUFDdd(short UFDdd) {
this.UFDdd = UFDdd;
}
public int getUFFone() {
return this.UFFone;
}
public void setUFFone(int UFFone) {
this.UFFone = UFFone;
}
public UserModel getUsertable() {
return this.usertable;
}
public void setUsertable(UserModel usertable) {
this.usertable = usertable;
}
public OperadorasModel getOperadorastable() {
return this.operadorastable;
}
public void setOperadorastable(OperadorasModel operadorastable) {
this.operadorastable = operadorastable;
}
public TiposFoneModel getTbTipostelefone() {
return this.tbTipostelefone;
}
public void setTbTipostelefone(TiposFoneModel tbTipostelefone) {
this.tbTipostelefone = tbTipostelefone;
}
}
#Entity
#Table(name="useraddresstable")
#NamedQuery(name="UserAddressModel.findAll", query="SELECT u FROM UserAddressModel u")
public class UserAddressModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private String UAId;
#Column(nullable=false, length=100)
private String UABairro;
#Column(nullable=false, length=100)
private String UACidade;
#Column(length=45)
private String UAComplemento;
#Column(nullable=false, length=2)
private String UAEstado;
#Column(nullable=false)
private int UANumero;
#Column(length=100)
private String UARua;
//bi-directional many-to-one association to UserModel
#ManyToOne
#JoinColumn(name="UAUserID", nullable=false)
private UserModel usertable;
public UserAddressModel() {
}
public String getUAId() {
return this.UAId;
}
public void setUAId(String UAId) {
this.UAId = UAId;
}
public String getUABairro() {
return this.UABairro;
}
public void setUABairro(String UABairro) {
this.UABairro = UABairro;
}
public String getUACidade() {
return this.UACidade;
}
public void setUACidade(String UACidade) {
this.UACidade = UACidade;
}
public String getUAComplemento() {
return this.UAComplemento;
}
public void setUAComplemento(String UAComplemento) {
this.UAComplemento = UAComplemento;
}
public String getUAEstado() {
return this.UAEstado;
}
public void setUAEstado(String UAEstado) {
this.UAEstado = UAEstado;
}
public int getUANumero() {
return this.UANumero;
}
public void setUANumero(int UANumero) {
this.UANumero = UANumero;
}
public String getUARua() {
return this.UARua;
}
public void setUARua(String UARua) {
this.UARua = UARua;
}
public UserModel getUsertable() {
return this.usertable;
}
public void setUsertable(UserModel usertable) {
this.usertable = usertable;
}
}
#Entity
#Table(name="tb_tipostelefone")
#NamedQuery(name="TiposFoneModel.findAll", query="SELECT t FROM TiposFoneModel t")
public class TiposFoneModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private short TFId;
#Column(nullable=false, length=45)
private String TFDescricao;
//bi-directional many-to-one association to UserFoneModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="tbTipostelefone")
private List<UserFoneModel> listFoneModel;
public TiposFoneModel() {
}
public short getTFId() {
return this.TFId;
}
public void setTFId(short TFId) {
this.TFId = TFId;
}
public String getTFDescricao() {
return this.TFDescricao;
}
public void setTFDescricao(String TFDescricao) {
this.TFDescricao = TFDescricao;
}
public List<UserFoneModel> getUserfonetables() {
return this.listFoneModel;
}
public void setUserfonetables(List<UserFoneModel> userfonetables) {
this.listFoneModel = userfonetables;
}
public UserFoneModel addUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().add(userfonetable);
userfonetable.setTbTipostelefone(this);
return userfonetable;
}
public UserFoneModel removeUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().remove(userfonetable);
userfonetable.setTbTipostelefone(null);
return userfonetable;
}
}
#Entity
#Table(name="operadorastable")
#NamedQuery(name="OperadorasModel.findAll", query="SELECT o FROM OperadorasModel o")
public class OperadorasModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private short OPCodigo;
#Column(nullable=false, length=100)
private String opNome;
//bi-directional many-to-one association to UserFoneModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="operadorastable")
private List<UserFoneModel> listFoneModel;
public OperadorasModel() {
}
public short getOPCodigo() {
return this.OPCodigo;
}
public void setOPCodigo(short OPCodigo) {
this.OPCodigo = OPCodigo;
}
public String getOpNome() {
return this.opNome;
}
public void setOpNome(String opNome) {
this.opNome = opNome;
}
public List<UserFoneModel> getUserfonetables() {
return this.listFoneModel;
}
public void setUserfonetables(List<UserFoneModel> userfonetables) {
this.listFoneModel = userfonetables;
}
public UserFoneModel addUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().add(userfonetable);
userfonetable.setOperadorastable(this);
return userfonetable;
}
public UserFoneModel removeUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().remove(userfonetable);
userfonetable.setOperadorastable(null);
return userfonetable;
}
}
DAO
#Stateless
#LocalBean
public class UserDao {
/**
* Default constructor.
*/
#PersistenceContext
EntityManager em;
public UserDao() {
// TODO Auto-generated constructor stub
}
public List<UserModel> listAll()
{
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UserModel> cq = cb.createQuery(UserModel.class);
Root<UserModel> rootEntry = cq.from(UserModel.class);
CriteriaQuery<UserModel> all = cq.select(rootEntry);
TypedQuery<UserModel> allQuery = em.createQuery(all);
List<UserModel> listU = allQuery.getResultList();
return listU;
/*
Query query = em.createQuery("SELECT u FROM UserModel u");
return query.getResultList();
*/
}
}
My Rest
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import br.com.avera.dao.UserDao;
import br.com.avera.model.UserAddressModel;
import br.com.avera.model.UserFoneModel;
import br.com.avera.model.UserModel;
#Path("/users")
public class UserRest {
#Inject
UserDao userDao;
#GET
#Produces(MediaType.APPLICATION_JSON)
public UserModel getUser()
{
List<UserModel> userModelList = userDao.listAll();
UserModel userModel = userModelList.get(0);
List<UserFoneModel> lFone = userModel.getUserfonetables();
for (UserFoneModel userFoneModel : lFone) {
System.out.println(userFoneModel.getUFDdd());
System.out.println(userFoneModel.getUFFone());
}
System.out.println("OOOOOO");
List<UserAddressModel> lAddressModels = userModel.getUseraddresstables();
for (UserAddressModel userAddressModel : lAddressModels) {
System.out.println(userAddressModel.getUACidade());
System.out.println(userAddressModel.getUAEstado());
}
return userModel;
}
}

Related

How to use detailed SQL query on Srpingboot using #Query?

I'm having some trouble to find out how to use an specific query on Springboot
SELECT tb_excursao.fk_cliente, tb_cliente.nome, tb_cliente.documento, tb_cliente.org_emissor, tb_cliente.data_nascimento, tb_excursao.fk_viagem, tb_viagens.destino, tb_viagens.data_viagem
FROM ((tb_excursao
INNER JOIN tb_cliente ON fk_cliente = tb_cliente.id_cliente)
INNER JOIN tb_viagens ON fk_viagem = tb_viagens.id_viagem))
This works fine on MySQL, but the examples that I saw it's always something like "SELECT u FROM User u", and as a beginner I can't relate using columns from different tables using #Query.
The models are below:
Cliente.java
#Entity
#Table(name = "tb_cliente")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idCliente;
#NotBlank
#Size(min = 3)
private String nome;
#NotNull
private String documento;
#NotNull
private String orgEmissor;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataNascimento;
#Temporal(TemporalType.TIMESTAMP)
private Date dataCadastro = new java.sql.Date(System.currentTimeMillis());
#OneToMany(mappedBy = "fkCliente")
Set<Excursao> excursao;
public long getIdCliente() {
return idCliente;
}
public void setIdCliente(long idCliente) {
this.idCliente = idCliente;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDocumento() {
return documento;
}
public void setDocumento(String documento) {
this.documento = documento;
}
public String getOrgEmissor() {
return orgEmissor;
}
public void setOrgEmissor(String orgEmissor) {
this.orgEmissor = orgEmissor;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public Date getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}
}
Viagem.java
#Entity
#Table(name = "tb_viagens")
public class Viagem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idViagem;
#NotBlank
private String destino;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataViagem;
#NotBlank
private int quantidadeMaxPessoas;
#OneToMany(mappedBy = "fkViagem")
private Set<Excursao> excursao;
public long getIdViagem() {
return idViagem;
}
public void setIdViagem(long idViagem) {
this.idViagem = idViagem;
}
public String getDestino() {
return destino;
}
public void setDestino(String destino) {
this.destino = destino;
}
public Date getDataViagem() {
return dataViagem;
}
public void setDataViagem(Date dataViagem) {
this.dataViagem = dataViagem;
}
public int getQuantidadeMaxPessoas() {
return quantidadeMaxPessoas;
}
public void setQuantidadeMaxPessoas(int quantidadeMaxPessoas) {
this.quantidadeMaxPessoas = quantidadeMaxPessoas;
}
}
ExcursaoEmbeddable.java
#Embeddable
public class ExcursaoEmb implements Serializable {
#Column(name = "fkCliente")
private Long fkCliente;
#Column(name = "fkViagem")
private Long fkViagem;
public Long getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Long fkCliente) {
this.fkCliente = fkCliente;
}
public Long getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Long fkViagem) {
this.fkViagem = fkViagem;
}
}
Excursao.java This is the table that the query in the beginning of the post goes
#Entity
#Table(name = "tb_excursao")
public class Excursao {
#EmbeddedId
ExcursaoEmb idExcursao;
#ManyToOne
#JoinColumn(name = "id_cliente")
private Cliente fkCliente;
#ManyToOne
#JoinColumn(name = "id_viagem")
private Viagem fkViagem;
#NotNull
private boolean primeiraParcela;
#NotNull
private boolean segundaParcela;
private boolean terceiraParcela;
public ExcursaoEmb getIdExcursao() {
return this.idExcursao;
}
public void setIdExcursao(ExcursaoEmb idExcursao) {
this.idExcursao = idExcursao;
}
public Cliente getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Cliente fkCliente) {
this.fkCliente = fkCliente;
}
public Viagem getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Viagem fkViagem) {
this.fkViagem = fkViagem;
}
public boolean isPrimeiraParcela() {
return this.primeiraParcela;
}
public boolean getPrimeiraParcela() {
return this.primeiraParcela;
}
public void setPrimeiraParcela(boolean primeiraParcela) {
this.primeiraParcela = primeiraParcela;
}
public boolean isSegundaParcela() {
return this.segundaParcela;
}
public boolean getSegundaParcela() {
return this.segundaParcela;
}
public void setSegundaParcela(boolean segundaParcela) {
this.segundaParcela = segundaParcela;
}
public boolean isTerceiraParcela() {
return this.terceiraParcela;
}
public boolean getTerceiraParcela() {
return this.terceiraParcela;
}
public void setTerceiraParcela(boolean terceiraParcela) {
this.terceiraParcela = terceiraParcela;
}
}

spring boot rest for one to many relation

I created spring boot project where I am making rest application. I have used My SQL database and I am using spring data. There is one method which adds orders based on customer id. So I am not able to figure out it will work based on spring data query or custom query and how it will be?
I have attached required codes only,
Customer.java
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "customers")
#NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "cust_ID_PK")
#GeneratedValue(strategy = GenerationType.AUTO)
private int custIDPK;
#Column(name = "billing_city")
private String billingCity;
#Column(name = "billing_country")
private String billingCountry;
#Column(name = "billing_state")
private String billingState;
#Column(name = "billing_street")
private String billingStreet;
#Column(name = "billing_zip")
private String billingZip;
private String company;
#Column(name = "display_name")
private String displayName;
private String email;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "other_details")
private String otherDetails;
#Column(name = "print_on_check_as")
private String printOnCheckAs;
#Column(name = "shipping_city")
private String shippingCity;
#Column(name = "shipping_country")
private String shippingCountry;
#Column(name = "shipping_state")
private String shippingState;
#Column(name = "shipping_street")
private String shippingStreet;
#Column(name = "shipping_zip")
private String shippingZip;
private String suffix;
private String title;
// bi-directional many-to-one association to Order
#OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private List<Order> orders;
public Customer() {
}
public int getCustIDPK() {
return this.custIDPK;
}
public void setCustIDPK(int cust_ID_PK) {
this.custIDPK = cust_ID_PK;
}
public String getBillingCity() {
return this.billingCity;
}
public void setBillingCity(String billingCity) {
this.billingCity = billingCity;
}
public String getBillingCountry() {
return this.billingCountry;
}
public void setBillingCountry(String billingCountry) {
this.billingCountry = billingCountry;
}
public String getBillingState() {
return this.billingState;
}
public void setBillingState(String billingState) {
this.billingState = billingState;
}
public String getBillingStreet() {
return this.billingStreet;
}
public void setBillingStreet(String billingStreet) {
this.billingStreet = billingStreet;
}
public String getBillingZip() {
return this.billingZip;
}
public void setBillingZip(String billingZip) {
this.billingZip = billingZip;
}
public String getCompany() {
return this.company;
}
public void setCompany(String company) {
this.company = company;
}
public String getDisplayName() {
return this.displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getOtherDetails() {
return this.otherDetails;
}
public void setOtherDetails(String otherDetails) {
this.otherDetails = otherDetails;
}
public String getPrintOnCheckAs() {
return this.printOnCheckAs;
}
public void setPrintOnCheckAs(String printOnCheckAs) {
this.printOnCheckAs = printOnCheckAs;
}
public String getShippingCity() {
return this.shippingCity;
}
public void setShippingCity(String shippingCity) {
this.shippingCity = shippingCity;
}
public String getShippingCountry() {
return this.shippingCountry;
}
public void setShippingCountry(String shippingCountry) {
this.shippingCountry = shippingCountry;
}
public String getShippingState() {
return this.shippingState;
}
public void setShippingState(String shippingState) {
this.shippingState = shippingState;
}
public String getShippingStreet() {
return this.shippingStreet;
}
public void setShippingStreet(String shippingStreet) {
this.shippingStreet = shippingStreet;
}
public String getShippingZip() {
return this.shippingZip;
}
public void setShippingZip(String shippingZip) {
this.shippingZip = shippingZip;
}
public String getSuffix() {
return this.suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Order> getOrders() {
return this.orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
public Order addOrder(Order order) {
getOrders().add(order);
order.setCustomer(this);
return order;
}
public Order removeOrder(Order order) {
getOrders().remove(order);
order.setCustomer(null);
return order;
}
}
Order.java
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#Entity
#Table(name = "orders")
#NamedQuery(name = "Order.findAll", query = "SELECT o FROM Order o")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "order_ID_PK")
#GeneratedValue(strategy = GenerationType.AUTO)
private int order_ID_PK;
#Column(name = "custom_message")
private String customMessage;
#Temporal(TemporalType.DATE)
#Column(name = "delivery_due_date")
private Date deliveryDueDate;
#Temporal(TemporalType.DATE)
#Column(name = "invoice_creation_date")
private Date invoiceCreationDate;
#Temporal(TemporalType.DATE)
#Column(name = "payment_due_date")
private Date paymentDueDate;
// bi-directional many-to-one association to Customer
#ManyToOne
#JoinColumn(name = "cust_ID_FK")
private Customer customer;
// bi-directional many-to-many association to Product
#ManyToMany(mappedBy = "orders")
private List<Product> products;
public Order() {
}
public int getOrder_ID_PK() {
return this.order_ID_PK;
}
public void setOrder_ID_PK(int order_ID_PK) {
this.order_ID_PK = order_ID_PK;
}
public String getCustomMessage() {
return this.customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
public Date getDeliveryDueDate() {
return this.deliveryDueDate;
}
public void setDeliveryDueDate(Date deliveryDueDate) {
this.deliveryDueDate = deliveryDueDate;
}
public Date getInvoiceCreationDate() {
return this.invoiceCreationDate;
}
public void setInvoiceCreationDate(Date invoiceCreationDate) {
this.invoiceCreationDate = invoiceCreationDate;
}
public Date getPaymentDueDate() {
return this.paymentDueDate;
}
public void setPaymentDueDate(Date paymentDueDate) {
this.paymentDueDate = paymentDueDate;
}
public Customer getCustomer() {
return this.customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
OrderOperation.java
package com.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.model.Order;
public interface OrderOperation extends JpaRepository<Order, Long> {
#Query("SELECT c.orders FROM Customer c where c.custIDPK = :id")
public List<Order> findOrderbyID(#Param("id") int id);
}
CustomerController.java
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
ICutomerService customerDAO;
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = { "/", "" }, method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<?> getAllCustomer() {
return new ResponseEntity(customerDAO.getAllCustomer(), HttpStatus.ACCEPTED);
}
#RequestMapping(value = "/{CustomerById}", method = RequestMethod.GET, produces = { "application/json" })
public Customer getCustomerbyId(#PathVariable("CustomerById") String cid) {
return customerDAO.findCustomerById(Integer.parseInt(cid));
}
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = "{CustomerById}/order", method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<?> getAllOrder(#PathVariable("CustomerById") String cid) {
return new ResponseEntity(customerDAO.getOrdersbyId(Integer.parseInt(cid)), HttpStatus.ACCEPTED);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#RequestMapping(value = "order/{CustomerById}/product", method = RequestMethod.GET, produces = {
"application/json" })
public ResponseEntity<?> getAllProduct(#PathVariable("CustomerById") String cid) {
return new ResponseEntity(customerDAO.getProductsById(Integer.parseInt(cid)), HttpStatus.ACCEPTED);
}
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<?> addCustomer(#RequestBody Customer c) {
boolean flag = customerDAO.addCustomer(c);
if (flag)
return new ResponseEntity(HttpStatus.CREATED);
else
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/{CustomerById}/orders", method = RequestMethod.POST)
public ResponseEntity<?> addOrders(#PathVariable("CustomerById") String cid, #RequestBody Order c) {
// c.getCustomer().setCustIDPK(Integer.parseInt(cid));
boolean flag = customerDAO.addOrder(c);
if (flag) {
return new ResponseEntity(HttpStatus.CREATED);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
How should I design this addOrders method?
If you are using Spring Data then you will need to create a CrudRepository for each table you which to access. The CrudRepository allows you to easily manipulate data in your table using standard ORM practices. Here is a link with more details.
For more detailed info on how to use Spring Data check out this wonderful guide. This guide has become indispensable when working with Spring Data.
There are many options to this but i have used below approach so hope it helps you. The #Query annotation allows to execute native queries by setting the nativeQuery flag to true.
#Query(value = "select o.* from customer c inner join order o on c.customer_id = o.customer_id where o. = ?1", nativeQuery = true)
Please write sql according to your requirement.

How to find intersection of many to many entities directly by JQL?

These are my model classes:
Film.java
#Entity
public class Film {
private Integer id;
private String title;
private List<FilmActor> filmActors;
#OneToMany(mappedBy = "film")
public List<FilmActor> getFilmActors() {
return filmActors;
}
public void setFilmActors(List<FilmActor> filmActors) {
this.filmActors = filmActors;
}
}
Actor.java
#Entity
public class Actor {
private Integer id;
private String firstname;
private String lastname;
private List<FilmActor> filmActors;
#OneToMany(mappedBy = "actor")
public List<FilmActor> getFilmActors() {
return filmActors;
}
public void setFilmActors(List<FilmActor> filmActors) {
this.filmActors = filmActors;
}
}
And this is the Join Table Entity:
#Entity
#Table(name = "film_actor")
public class FilmActor {
private FilmActorPK id;
private Film film;
private Actor actor;
private Timestamp lastUpdate;
#EmbeddedId
public FilmActorPK getId() {
return id;
}
public void setId(FilmActorPK id) {
this.id = id;
}
#ManyToOne
#MapsId("film")
#JoinColumn(name = "film_id")
public Film getFilm() {
return film;
}
public void setFilm(Film film) {
this.film = film;
}
#ManyToOne
#MapsId("actor")
#JoinColumn(name = "actor_id")
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
#Column(name = "last_update")
public Timestamp getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Timestamp lastUpdate) {
this.lastUpdate = lastUpdate;
}
}
and the Primary Key class:
#Embeddable
public class FilmActorPK implements Serializable {
private int actorId;
private int filmId;
#Column(name = "actor_id")
public int getActorId() {
return actorId;
}
public void setActorId(int actorId) {
this.actorId = actorId;
}
#Column(name = "film_id")
public int getFilmId() {
return filmId;
}
public void setFilmId(int filmId) {
this.filmId = filmId;
}
}
So I want to find films where 2 given actors acts. This is what I have:
#Override
public Collection<Film> filmsActorsTogether(Actor a, Actor b) {
final List<Film> filmsOfActorA = filmsOfActor(a);
final List<Film> filmsOfActorB = filmsOfActor(b);
final Collection<Film> intersection = CollectionUtils.intersection(filmsOfActorA, filmsOfActorB);
return intersection;
}
#Override
public List<Film> filmsOfActor(Actor actor) {
final EntityManager entityManager = persistenceUtil.getEntityManager();
final Actor persistentActor = entityManager.find(Actor.class, actor.getId());
final ArrayList<Film> films = new ArrayList<Film>();
for (FilmActor filmActor : persistentActor.getFilmActors()) {
films.add(filmActor.getFilm());
}
entityManager.close();
return films;
}
Is there any way to achieve this without fetching ALL films of 2 actors, and using filtering in memory? How do I get the Films directly from the DB with JQL?
Maybe there is something more elegant, but the following query should work:
select f from Film f where
(select count(fa.id) from FilmActor fa
where fa.film = f
and (fa.actor = :actor1 or fa.actor = :actor2)) = 2
Side note: your PK class should have a correct equals() and hashCode() methods

How to persist parent and childs in JPA?

I have a table called conclusion and it has a relationship with table comments.
When i am adding conclusion and comments at the same time, Conclusion is being inserted but child getting conclusion id as null by which i'm getting violation of not null constraint.
My transaction roll backs conclusion also not inserted.
So please tell me how to insert parent and child at once.
my entities are
Conclusion Entity
#Entity
#Table(name="olm_anlys_cncln")
public class OlmAnalysisConclusion implements Serializable {
private static final long serialVersionUID = 1L;
private Long conclusionId;
private String concludedBy;
private Timestamp concludedTime;
private String conclusion;
private Timestamp discussionEndTime;
private String discussionActive;
private Timestamp discussionStartTime;
private Integer tntId;
private OlmAnalysis olmAnly;
private OlmAnalysisCategory olmAnlysCatgMstr;
private OlmAnalysisCause olmAnlysCauseMstr;
private List<OlmInvsgDiscussionComment> olmInvsgDiscnCmnts;
public OlmAnalysisConclusion() {
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="olm_anlys_cncln_id")
public Long getConclusionId() {
return this.conclusionId;
}
public void setConclusionId(Long conclusionId) {
this.conclusionId = conclusionId;
}
#Column(name="cncld_by")
public String getConcludedBy() {
return this.concludedBy;
}
public void setConcludedBy(String concludedBy) {
this.concludedBy = concludedBy;
}
#Column(name="cncld_time")
public Timestamp getConcludedTime() {
return this.concludedTime;
}
public void setConcludedTime(Timestamp concludedTime) {
this.concludedTime = concludedTime;
}
#Column(name="cncln")
public String getConclusion() {
return this.conclusion;
}
public void setConclusion(String conclusion) {
this.conclusion = conclusion;
}
#Column(name="discn_end_time")
public Timestamp getDiscussionEndTime() {
return this.discussionEndTime;
}
public void setDiscussionEndTime(Timestamp discussionEndTime) {
this.discussionEndTime = discussionEndTime;
}
#Column(name="discn_flag")
public String getDiscussionActive() {
return this.discussionActive;
}
public void setDiscussionActive(String discussionActive) {
this.discussionActive = discussionActive;
}
#Column(name="discn_strt_time")
public Timestamp getDiscussionStartTime() {
return this.discussionStartTime;
}
public void setDiscussionStartTime(Timestamp discussionStartTime) {
this.discussionStartTime = discussionStartTime;
}
#Column(name="tnt_id")
public Integer getTntId() {
return this.tntId;
}
public void setTntId(Integer tntId) {
this.tntId = tntId;
}
//bi-directional many-to-one association to OlmAnalysis
#ManyToOne
#JoinColumn(name="anlys_id")
public OlmAnalysis getOlmAnly() {
return this.olmAnly;
}
public void setOlmAnly(OlmAnalysis olmAnly) {
this.olmAnly = olmAnly;
}
//bi-directional many-to-one association to OlmAnalysisCategory
#ManyToOne
#JoinColumn(name="catg_id")
public OlmAnalysisCategory getOlmAnlysCatgMstr() {
return this.olmAnlysCatgMstr;
}
public void setOlmAnlysCatgMstr(OlmAnalysisCategory olmAnlysCatgMstr) {
this.olmAnlysCatgMstr = olmAnlysCatgMstr;
}
//bi-directional many-to-one association to OlmAnalysisCause
#ManyToOne
#JoinColumn(name="cause_id")
public OlmAnalysisCause getOlmAnlysCauseMstr() {
return this.olmAnlysCauseMstr;
}
public void setOlmAnlysCauseMstr(OlmAnalysisCause olmAnlysCauseMstr) {
this.olmAnlysCauseMstr = olmAnlysCauseMstr;
}
//bi-directional many-to-one association to OlmInvsgDiscussionComment
#OneToMany(fetch=FetchType.EAGER,mappedBy="olmAnlysCncln",cascade=CascadeType.ALL)
public List<OlmInvsgDiscussionComment> getOlmInvsgDiscnCmnts() {
return this.olmInvsgDiscnCmnts;
}
public void setOlmInvsgDiscnCmnts(List<OlmInvsgDiscussionComment> olmInvsgDiscnCmnts) {
this.olmInvsgDiscnCmnts = olmInvsgDiscnCmnts;
}
public OlmInvsgDiscussionComment addOlmInvsgDiscnCmnt(OlmInvsgDiscussionComment olmInvsgDiscnCmnt) {
getOlmInvsgDiscnCmnts().add(olmInvsgDiscnCmnt);
olmInvsgDiscnCmnt.setOlmAnlysCncln(this);
return olmInvsgDiscnCmnt;
}
public OlmInvsgDiscussionComment removeOlmInvsgDiscnCmnt(OlmInvsgDiscussionComment olmInvsgDiscnCmnt) {
getOlmInvsgDiscnCmnts().remove(olmInvsgDiscnCmnt);
olmInvsgDiscnCmnt.setOlmAnlysCncln(null);
return olmInvsgDiscnCmnt;
}
}
Comment Entity
#Entity
#Table(name="olm_invsg_discn_cmnt")
public class OlmInvsgDiscussionComment implements Serializable {
private static final long serialVersionUID = 1L;
private Long commentId;
private String comment;
private Timestamp commentTime;
private String commentedBy;
private Integer tenentId;
private OlmAnalysisConclusion olmAnlysCncln;
private Set<OlmInvsgCommentAttachment> olmInvsgDiscnCmntAtmnts;
public OlmInvsgDiscussionComment() {
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="olm_invsg_discn_cmnt_id")
public Long getCommentId() {
return this.commentId;
}
public void setCommentId(Long commentId) {
this.commentId = commentId;
}
#Column(name="cmnt")
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
#Column(name="cmnt_time")
public Timestamp getCommentTime() {
return this.commentTime;
}
public void setCommentTime(Timestamp commentTime) {
this.commentTime = commentTime;
}
#Column(name="cmntd_by")
public String getCommentedBy() {
return this.commentedBy;
}
public void setCommentedBy(String commentedBy) {
this.commentedBy = commentedBy;
}
#Column(name="tnt_id")
public Integer getTenentId() {
return this.tenentId;
}
public void setTenentId(Integer tenentId) {
this.tenentId = tenentId;
}
//bi-directional many-to-one association to OlmAnalysisConclusion
#ManyToOne(fetch=FetchType.EAGER, optional=false)
#JoinColumn(name="cncln_id")
public OlmAnalysisConclusion getOlmAnlysCncln() {
return this.olmAnlysCncln;
}
public void setOlmAnlysCncln(OlmAnalysisConclusion olmAnlysCncln) {
this.olmAnlysCncln = olmAnlysCncln;
}
//bi-directional many-to-one association to OlmInvsgCommentAttachment
#OneToMany(fetch=FetchType.EAGER,mappedBy="olmInvsgDiscnCmnt",cascade=CascadeType.ALL)
public Set<OlmInvsgCommentAttachment> getOlmInvsgDiscnCmntAtmnts() {
return this.olmInvsgDiscnCmntAtmnts;
}
public void setOlmInvsgDiscnCmntAtmnts(Set<OlmInvsgCommentAttachment> olmInvsgDiscnCmntAtmnts) {
this.olmInvsgDiscnCmntAtmnts = olmInvsgDiscnCmntAtmnts;
}
public OlmInvsgCommentAttachment addOlmInvsgDiscnCmntAtmnt(OlmInvsgCommentAttachment olmInvsgDiscnCmntAtmnt) {
getOlmInvsgDiscnCmntAtmnts().add(olmInvsgDiscnCmntAtmnt);
olmInvsgDiscnCmntAtmnt.setOlmInvsgDiscnCmnt(this);
return olmInvsgDiscnCmntAtmnt;
}
public OlmInvsgCommentAttachment removeOlmInvsgDiscnCmntAtmnt(OlmInvsgCommentAttachment olmInvsgDiscnCmntAtmnt) {
getOlmInvsgDiscnCmntAtmnts().remove(olmInvsgDiscnCmntAtmnt);
olmInvsgDiscnCmntAtmnt.setOlmInvsgDiscnCmnt(null);
return olmInvsgDiscnCmntAtmnt;
}
}
The most probable reason for the join column being null in your table is that the olmAnlysCncln field is null in the OlmInvsgDiscussionComment entity you're trying to persist. That's the owner side of the bidirectional association. You MUST initialize it if you want Hibernate to set something in the corresponding column. Adding the comment to the conclusion is not sufficient.
Side note: vowels are accepted, and even recommented, in property names. You should be able to pronounce a property name. olmInvsgDiscnCmntAtmnts is unpronouceable and unreadable. Use proper English names.

Hibernate Mapping Exception

I have 2 Entity classes ParameterGroupBean and GroupLevelBean
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
#Entity
#Table(name="tbl_ParameterGroups")
public class ParameterGroupBean {
#Id
#GeneratedValue
private int ParameterGroupId;
private String ParameterGroupName;
private Boolean Status;
#ManyToOne
#JoinColumn(name="LevelId")
private GroupLevelBean level = new GroupLevelBean();
public GroupLevelBean getLevel() {
return level;
}
public void setLevel(GroupLevelBean level) {
this.level = level;
}
#Id
#GeneratedValue
public int getParameterGroupId() {
return ParameterGroupId;
}
public void setParameterGroupId(int parameterGroupId) {
ParameterGroupId = parameterGroupId;
}
#Column(length=120)
public String getParameterGroupName() {
return ParameterGroupName;
}
public void setParameterGroupName(String parameterGroupName) {
ParameterGroupName = parameterGroupName;
}
public Boolean getStatus() {
return Status;
}
public void setStatus(Boolean Status) {
this.Status = Status;
}
}
GroupLevelBean:
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
#Entity
#Table(name="tbl_GroupLevel")
public class GroupLevelBean {
private int LevelId;
private String LevelName;
#OneToMany(mappedBy = "level")
private Collection<ParameterGroupBean> parameterGroups = new ArrayList<ParameterGroupBean>();
public Collection<ParameterGroupBean> getParameterGroups() {
return parameterGroups;
}
public void setParameterGroups(Collection<ParameterGroupBean> parameterGroups) {
this.parameterGroups = parameterGroups;
}
#Id
#GeneratedValue
public int getLevelId() {
return LevelId;
}
public void setLevelId(int levelId) {
LevelId = levelId;
}
#Column(length = 30)
public String getLevelName() {
return LevelName;
}
public void setLevelName(String levelName) {
LevelName = levelName;
}
}
The relationship between GroupLevelBean and ParameterGroupBean is one to many.
I am getting an exception when i try to create a session object.
org.hibernate.MappingException: Could not determine type for: com.vrde.daems.bean.GroupLevelBean, at table: tbl_ParameterGroups, for columns: [org.hibernate.mapping.Column(level)]
Can anyone tell me what is the problem?
Because you are putting #Id and #GeneratedValue java persistence annotations above:
#Id
#GeneratedValue
private int ParameterGroupId;
and in same time above:
#Id
#GeneratedValue
public int getParameterGroupId() {
return ParameterGroupId;
}
Its enough just to put annotations above private int ParameterGroupId;

Categories

Resources