Error on persisting data can not set int field - java

I have to create a Java Spring web app and I have a problem :
java.lang.IllegalArgumentException: Can not set int field Métier.Visiteur.VstId to Métier.Visiteur
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeIntegerFieldAccessorImpl.getInt(UnsafeIntegerFieldAccessorImpl.java:56) ~[na:na]
at java.base/java.lang.reflect.Field.getInt(Field.java:594) ~[na:na]
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:62) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:223) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:5119) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4819) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:294) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
at org.hibernate.event.internal.EntityState.getEntityState(EntityState.java:59) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:95) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:714) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:700) ~[hibernate-core-5.4.11.Final.jar:5.4.11.Final]
Visiteur :
package Métier;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Temporal mapping : https://thorben-janssen.com/hibernate-jpa-date-and-time/
* TODO : Vérifier que les attributs sont nullables
*/
#Entity
public class Visiteur {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(updatable = false, nullable = false)
public int VstId;
private String adresse;
private String code_postal;
private String ville;
#Temporal(TemporalType.DATE)
private Date date_embauche;
#OneToMany
private List<FicheFrais> fichesFrais = new ArrayList<FicheFrais>();
public Visiteur() {
}
public void addFicheFrais(FicheFrais ff) {
fichesFrais.add(ff);
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public int getVstId() {
return VstId;
}
public void setVstId(int id) {
this.VstId = id;
}
public String getCode_postal() {
return code_postal;
}
public void setCode_postal(String code_postal) {
this.code_postal = code_postal;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public Date getDate_embauche() {
return date_embauche;
}
public void setDate_embauche(Date date_embauche) {
this.date_embauche = date_embauche;
}
}
Is it a problem with my auto generated primary key ?
This table is linked to another named "FicheFrais", this table has a composite key (created with Embeddable annotation) in which it's referencing visiteur (with ManyToOne association)
There is no query at all, I'm just trying to persist a Visiteur instance, like this :
EntityManagerFactory emf = Persistence.createEntityManagerFactory("GSBSpring");
EntityManager em = emf.createEntityManager();
Visiteur vst = new Visiteur();
// vst.setId((long) 1);
FicheFraisPK fpk = new FicheFraisPK(vst, Mois.AVRIL);
FicheFrais ff = new FicheFrais();
ff.setEtat(Etat.ENCOURS);
ff.setId(fpk);
vst.addFicheFrais(ff);
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.persist(vst);
em.persist(fpk);
em.persist(ff);
Edit :
here is FicheFrais (linked with visiteur) :
package Métier;
import org.hibernate.annotations.ManyToAny;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* Enum mapping : https://thorben-janssen.com/hibernate-enum-mappings/
* TODO : Faire les méthodes ? total_frais_forfaitaire, total_frais_hors_forfait ?
* TODO : Vérifier si la clé composée est fonctionnelle
*/
#Entity
public class FicheFrais implements Serializable {
#Enumerated(EnumType.STRING)
private Etat etat;
#EmbeddedId
private FicheFraisPK id;
private int nb_justificatifs;
private float montant_valide;
#Temporal(TemporalType.DATE)
private Date date_modif;
public FicheFraisPK getId() {
return id;
}
public void setId(FicheFraisPK ident) {
id = ident;
}
public Etat getEtat() {
return etat;
}
public Visiteur getVisiteur() {
return id.visiteur;
}
public void setVisiteur(Visiteur vst) {
id.visiteur = vst;
}
public void setEtat(Etat etat) {
this.etat = etat;
}
public int getNb_justificatifs() {
return nb_justificatifs;
}
public void setNb_justificatifs(int nb_justificatifs) {
this.nb_justificatifs = nb_justificatifs;
}
public float getMontant_valide() {
return montant_valide;
}
public void setMontant_valide(float montant_valide) {
this.montant_valide = montant_valide;
}
public Date getDate_modif() {
return date_modif;
}
public void setDate_modif(Date date_modif) {
this.date_modif = date_modif;
}
}
and it's EmbeddedId :
package Métier;
import javax.persistence.Embeddable;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import java.io.Serializable;
import java.util.Objects;
#Embeddable
public class FicheFraisPK implements Serializable {
#ManyToOne
Visiteur visiteur;
#Enumerated(EnumType.STRING)
Mois mois;
public FicheFraisPK() {
}
public FicheFraisPK(Visiteur vst, Mois ms) {
this.visiteur = vst;
this.mois = ms;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FicheFraisPK)) return false;
FicheFraisPK that = (FicheFraisPK) o;
return Objects.equals(getVisiteur(), that.getVisiteur()) &&
Objects.equals(getMois(), that.getMois());
}
#Override
public int hashCode() {
return Objects.hash(getVisiteur(), getMois());
}
private Visiteur getVisiteur() {
return visiteur;
}
private void setVisiteur(Visiteur visiteur) {
this.visiteur = visiteur;
}
public Mois getMois() {
return mois;
}
public void setMois(Mois mois) {
this.mois = mois;
}
}

Try a mapping like this:
#Entity
public class Visiteur {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(updatable = false, nullable = false)
public int VstId;
private String adresse;
private String code_postal;
private String ville;
#Temporal(TemporalType.DATE)
private Date date_embauche;
#OneToMany(mappedBy = "visiteur")
private List<FicheFrais> fichesFrais = new ArrayList<FicheFrais>();
}
#Entity
public class FicheFrais implements Serializable {
#Enumerated(EnumType.STRING)
private Etat etat;
#EmbeddedId
private FicheFraisPK id;
#ManyToOne
#JoinColumn(name = "Visiteur_id", insertable = false, updatable = false)
Visiteur visiteur;
private int nb_justificatifs;
private float montant_valide;
#Temporal(TemporalType.DATE)
private Date date_modif;
}
#Embeddable
public class FicheFraisPK implements Serializable {
#Column(name = "Visiteur_id")
int VstId;
#Enumerated(EnumType.STRING)
Mois mois;
}

Related

I'm not able to select particular column from a JPQL?

here is my query where I'm trying to get id and userNotes from Job Class.
#Query("SELECT j.id, j.userNotes FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate")
List<Job> getDriverCalendar(#Param("stDate") Timestamp stDate, #Param("edDate") Timestamp edDate);
Job.java
package com.housecar.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table(name = "hc_job")
public class Job{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "ride_time")
private Timestamp rideTime;
#Column(name = "booking_time")
private Timestamp bookingTime;
#Column(name = "guest_id")
private Long guestId;
#Column(name = "booked_user_id")
private Long bookedUserId;
#Column(name = "car_id")
private Long carId;
#Column(name = "pickup_location")
private String pickupLocation;
#Column(name = "drop_location")
private String dropLocation;
#Column(name = "trip_type")
private Character tripType;
#Column(name = "is_private_job")
private Boolean isPrivateJob;
#Column(name = "estimated_fare")
private BigDecimal estimatedFare;
#Column(name = "actual_fare")
private BigDecimal actualFare;
#Column(name = "tip")
private BigDecimal tip;
#Column(name = "payment_status")
private Character paymentStatus;
#Column(name = "user_notes")
private String userNotes;
#Column(name = "cancellation_notes")
private String cancellationNotes;
#Column(name = "status")
private Character status;
#OneToOne
#JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
private JobDriverRating jobDriverRating;
#OneToOne
#JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
private JobCostSplit jobCostSplit;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getGuestId() {
return guestId;
}
public void setGuestId(Long guestId) {
this.guestId = guestId;
}
public Long getBookedUserId() {
return bookedUserId;
}
public void setBookedUserId(Long bookedUserId) {
this.bookedUserId = bookedUserId;
}
public Long getCarId() {
return carId;
}
public void setCarId(Long carId) {
this.carId = carId;
}
public String getPickupLocation() {
return pickupLocation;
}
public void setPickupLocation(String pickupLocation) {
this.pickupLocation = pickupLocation;
}
public String getDropLocation() {
return dropLocation;
}
public void setDropLocation(String dropLocation) {
this.dropLocation = dropLocation;
}
public Character getTripType() {
return tripType;
}
public void setTripType(Character tripType) {
this.tripType = tripType;
}
public Boolean getIsPrivateJob() {
return isPrivateJob;
}
public void setIsPrivateJob(Boolean isPrivateJob) {
this.isPrivateJob = isPrivateJob;
}
public BigDecimal getEstimatedFare() {
return estimatedFare;
}
public void setEstimatedFare(BigDecimal estimatedFare) {
this.estimatedFare = estimatedFare;
}
public BigDecimal getActualFare() {
return actualFare;
}
public void setActualFare(BigDecimal actualFare) {
this.actualFare = actualFare;
}
public BigDecimal getTip() {
return tip;
}
public void setTip(BigDecimal tip) {
this.tip = tip;
}
public Character getPaymentStatus() {
return paymentStatus;
}
public void setPaymentStatus(Character paymentStatus) {
this.paymentStatus = paymentStatus;
}
public String getUserNotes() {
return userNotes;
}
public void setUserNotes(String userNotes) {
this.userNotes = userNotes;
}
public String getCancellationNotes() {
return cancellationNotes;
}
public void setCancellationNotes(String cancellationNotes) {
this.cancellationNotes = cancellationNotes;
}
public Character getStatus() {
return status;
}
public void setStatus(Character status) {
this.status = status;
}
public JobDriverRating getJobDriverRating() {
return jobDriverRating;
}
public void setJobDriverRating(JobDriverRating jobDriverRating) {
this.jobDriverRating = jobDriverRating;
}
public Timestamp getRideTime() {
return rideTime;
}
public void setRideTime(Timestamp rideTime) {
this.rideTime = rideTime;
}
public Timestamp getBookingTime() {
return bookingTime;
}
public void setBookingTime(Timestamp bookingTime) {
this.bookingTime = bookingTime;
}
public JobCostSplit getJobCostSplit() {
return jobCostSplit;
}
public void setJobCostSplit(JobCostSplit jobCostSplit) {
this.jobCostSplit = jobCostSplit;
}
}
#Query("SELECT j.id, j.userNotes FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate") this query returned [ ].
#Query("SELECT j FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate") this query returned the complete Job object.
Your query doesn't select a Job. It selects two fields. Such a JPQL query returns a List<Object[]>, where each array of the list has two elements.
The return type of the method should thus be changed to List<Object[]>.
In the above query use the alias name for each value fetched
You will get the result as the list of hashmap so change the return type from List<Job> to List<Map> as shown below,
#Query("SELECT j.id as id , j.userNotes as userNotes FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate")
List<Map> getDriverCalendar(#Param("stDate") Timestamp stDate, #Param("edDate") Timestamp edDate);

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

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;
}
}

JPA/Hibernate - Java EE - Unable to find model.Composer with id model.ComposerId#0

I'm trying to persist in my DB a COMMANDE object (sorry it's in french ;)).
My DB :
Here is my mapping :
composer.java:
package model;
import java.io.Serializable;
import javax.persistence.*;
import model.Panier;
import model.Produit;
/**
* Entity implementation class for Entity: Composer
*
*/
#Entity
#Table(name="COMPOSER")
#IdClass(ComposerId.class)
public class Composer implements Serializable {
#Id
private int idPan;
#Id
private int idProd;
#ManyToOne
//#PrimaryKeyJoinColumn(name="idPan", referencedColumnName="id")
#JoinColumn(name="idPan", referencedColumnName="id", insertable = false, updatable = false)
private Panier panier;
#ManyToOne
//#PrimaryKeyJoinColumn(name="idProd", referencedColumnName="id")
#JoinColumn(name="idProd", referencedColumnName="id" , insertable = false, updatable = false)
private Produit produit;
private int nbProdPan;
private static final long serialVersionUID = 1L;
public Composer() {
super();
}
public Panier getPanier() {
return this.panier;
}
public void setPanier(Panier panier) {
this.panier = panier;
}
public Produit getProduit() {
return this.produit;
}
public void setProduit(Produit produit) {
this.produit = produit;
}
public int getNbProdPan() {
return this.nbProdPan;
}
public void setNbProdPan(int nbProdPan) {
this.nbProdPan = nbProdPan;
}
}
Commande.java
package model;
import java.io.Serializable;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Commande
*
*/
#Entity
#Table(name="COMMANDE")
public class Commande implements Serializable {
#Id
#GeneratedValue
private int id;
private int modLivrCom;
private static final long serialVersionUID = 1L;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="idPan")
private Panier panier;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="idUtil")
private Utilisateur utilisateur;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="idAdr")
private Adresse adresse;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="idEtat")
private Etatcmd etatcmd;
public Commande() {
super();
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getModLivrCom() {
return this.modLivrCom;
}
public void setModLivrCom(int modLivrCom) {
this.modLivrCom = modLivrCom;
}
public Panier getPanier() {
return panier;
}
public void setPanier(Panier panier) {
this.panier = panier;
}
public Utilisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utilisateur utilisateur) {
this.utilisateur = utilisateur;
}
public Adresse getAdresse() {
return adresse;
}
public void setAdresse(Adresse adresse) {
this.adresse = adresse;
}
public Etatcmd getEtatcmd() {
return etatcmd;
}
public void setEtatcmd(Etatcmd etatcmd) {
this.etatcmd = etatcmd;
}
}
Panier.java :
package model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Panier
*
*/
#Entity
#Table(name="PANIER")
public class Panier implements Serializable {
#Id
#GeneratedValue
private int id;
private float prixTotPan;
private static final long serialVersionUID = 1L;
#OneToOne(mappedBy="panier")
private Commande commande;
#OneToMany(mappedBy="panier")
private List<Composer> composers;
public Panier() {
super();
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public float getPrixTotPan() {
return this.prixTotPan;
}
public void setPrixTotPan(float prixTotPan) {
this.prixTotPan = prixTotPan;
}
public List<Composer> getComposers() {
return composers;
}
public void setComposers(List<Composer> composers) {
this.composers = composers;
}
}
buy.java
Commande laCommande = new Commande();
if(Integer.parseInt(request.getParameter("idCommande"))==-1){
Utilisateur utilisateur = UtilisateurDao.find(((Utilisateur)request.getSession().getAttribute("user")).getId());
laCommande.setAdresse(utilisateur.getAdresse());
}
else{
Enseigne enseigne = EnseigneDao.find(Integer.parseInt(request.getParameter("idLivraison")));
laCommande.setAdresse(enseigne.getAdresse());
}
model.Panier panier = (model.Panier)request.getSession().getAttribute("Panier");
PanierDao.update(panier);
Etatcmd etatcmd = EtatcmdDao.find(0);
laCommande.setEtatcmd(etatcmd);
laCommande.setModLivrCom(Integer.parseInt(request.getParameter("idCommande")));
laCommande.setPanier(panier);
laCommande.setUtilisateur((Utilisateur)request.getSession().getAttribute("user"));
CommandeDao.create(laCommande);
RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/confirmation.jsp");
dispatcher.forward(request, response);
When I try to execute this code, no object is persisted, and I obtain this error page :
HTTP Status 500 - Unable to find model.Composer with id model.ComposerId#0
type Exception report
message Unable to find model.Composer with id model.ComposerId#0
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.persistence.EntityNotFoundException: Unable to find model.Composer with id model.ComposerId#0
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:183)
org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:275)
org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:151)
org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1070)
org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:989)
org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:716)
org.hibernate.type.EntityType.resolve(EntityType.java:502)
org.hibernate.type.EntityType.replace(EntityType.java:366)
org.hibernate.type.CollectionType.replaceElements(CollectionType.java:549)
org.hibernate.type.CollectionType.replace(CollectionType.java:690)
org.hibernate.type.AbstractType.replace(AbstractType.java:178)
org.hibernate.type.TypeHelper.replaceAssociations(TypeHelper.java:261)
org.hibernate.event.internal.DefaultMergeEventListener.copyValues(DefaultMergeEventListener.java:433)
org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:256)
org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:189)
org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:85)
org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:876)
org.hibernate.internal.SessionImpl.merge(SessionImpl.java:858)
org.hibernate.internal.SessionImpl.merge(SessionImpl.java:863)
org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1196)
dao.PanierDao.update(PanierDao.java:44)
front.Buy.doPost(Buy.java:60)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
What can I do?
Your Composer.class has two fields annotated with #Id. In SQL you can have only one primary key. If both the field should compose your primary key, consider using a composite primary key, see for example the JPA documentation, where it says:
Composite primary keys are denoted using the javax.persistence.EmbeddedId and javax.persistence.IdClass annotations.

SPRING JPA - org.hibernate.PersistentObjectException: detached entity passed to persist:

I've been stuck here for almost a week trying find the answer on the internet but sadly nothing worked. :( Everytime I try to update using this method:
private Tenant updateTenantWithApplicationProperties(List<TenantApplicationProperty> newTenantApplicationProperties, String tenantId) {
String reason = "Update application properties.";
Tenant existingTenant = tenantRepository.findById(tenantId);
List<TenantApplicationProperty> temp = existingTenant.getTenantApplicationProperties();
existingTenant.setTenantApplicationProperties(newTenantApplicationProperties);
setApplicationPropertiesUpdateValues(temp, existingTenant);
if(newTenantApplicationProperties != null && newTenantApplicationProperties.size() != 0) {
Tenant savedTenantWithAppProps = saveTenantWithLog(existingTenant, reason);
return savedTenantWithAppProps;
}
return existingTenant;
}
Im always getting this error:
javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.infor.ecom.tenant.manager.model.entity.ApplicationProperty
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1361)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1295)
at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:876)
But when Im using this method it works fine:
public Tenant updateTenant(Tenant tenant) {
List<Database> databases = tenant.getDatabases();
List<Administrator> administrators = tenant.getAdministrators();
validateUpdateTenant(tenant);
validateDatabases(databases);
validateAdministrators(administrators);
Tenant existingTenant = findByIdWithAllDetails(tenant.getId());
List<Database> listExistingDatabases = existingTenant.getDatabases();
Database existingEcomDb = getDatabaseByType(listExistingDatabases,
TenantManagerConstants.ECOM_DATASOURCE);
setDatabaseUpdateValues(listExistingDatabases, tenant);
setAdministratorsUpdateValues(existingTenant.getAdministrators(),
tenant);
setProductUpdateValue(existingTenant.getProduct(), tenant);
setApplicationPropertiesUpdateValues(existingTenant.getTenantApplicationProperties(), tenant);
setEcomDBParamsDefaultValues(tenant);
setAdministratorDefaultValues(tenant);
Database updateEcomDb = getDatabaseByType(tenant.getDatabases(),
TenantManagerConstants.ECOM_DATASOURCE);
Boolean shouldInstallNewDB = true;
if (existingEcomDb.getName().equalsIgnoreCase(updateEcomDb.getName())
&& existingEcomDb.getHost().equalsIgnoreCase(
updateEcomDb.getHost())
&& existingEcomDb.getPort().equals(updateEcomDb.getPort())) {
shouldInstallNewDB = false;
} else {
testEcomDBConnection(updateEcomDb);
}
int ecomDbTableCount = getEcomDBTableCount(updateEcomDb);
String[][] languages = formatAndValidateLanguages(updateEcomDb
.getEcomDatabaseParameters().getLanguages());
Tenant updatedTenant = saveExistingTenant(tenant);
if (updatedTenant != null) {
if (shouldInstallNewDB || ecomDbTableCount == 0) {
installDatabase(updateEcomDb, languages, updatedTenant);
} else {
updateDatabase(updateEcomDb, languages, updatedTenant);
}
storageService.updateTenantFolderStructure(updatedTenant);
} else {
throw new TenantManagerException(
ApiMessageConstants.M_TENANT_PROVISION_ERROR,
ApiMessageConstants.C_TENANT_PROVISION_ERROR);
}
return updatedTenant;
}
So here is my complete codes:
Tenant.java
package com.infor.ecom.tenant.manager.model.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import com.infor.ecom.tenant.manager.constant.TenantManagerConstants;
import com.infor.ecom.tenant.manager.constant.TenantStatusEnum;
#Entity
#Table(name="tenant")
#XmlRootElement(name = "Tenant",namespace = "http://com.infor.ecom.tenant.manager/Tenant")
public class Tenant extends BaseModel {
private static final long serialVersionUID = -6687293822212120396L;
#Id
private String id;
private String displayName;
private String description;
private String url;
private String apiKey;
private String status;
#OneToMany(mappedBy = "tenant", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Database> databases;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Activity> activites;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Administrator> administrators;
private String message;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<TenantApplicationProperty> tenantApplicationProperties;
#OneToOne(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private Product product;
public Database findEcomDatabase() {
Database database = null;
if(databases != null) {
for(Database db : databases) {
if(db.getDatasource() != null) {
if(TenantManagerConstants.ECOM_DATASOURCE.equals(db.getDatasource().getName())) {
database = db;
break;
}
}
}
}
return database;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getStatus() {
return status;
}
public void setStatus(TenantStatusEnum statusEnum) {
this.status = statusEnum.name();
}
public List<Database> getDatabases() {
return databases;
}
public void setDatabases(List<Database> databases) {
this.databases = databases;
}
public void addDatabase(Database database) {
if (this.databases == null) {
this.databases = new ArrayList<Database>();
}
database.setTenant(this);
this.databases.add(database);
}
public List<Activity> getActivites() {
return activites;
}
public void setActivites(List<Activity> activities) {
this.activites = activities;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setStatus(String status) {
this.status = status;
}
public List<Administrator> getAdministrators() {
return this.administrators;
}
public void setAdministrators(List<Administrator> administrators) {
for (Administrator admin:administrators) {
admin.setTenant(this);
}
this.administrators = administrators;
}
public void addAdministrator(Administrator administrator) {
if (this.administrators == null) {
this.administrators = new ArrayList<Administrator>();
}
administrator.setTenant(this);
this.administrators.add(administrator);
}
public List<TenantApplicationProperty> getTenantApplicationProperties() {
return tenantApplicationProperties;
}
public void setTenantApplicationProperties(
List<TenantApplicationProperty> tenantApplicationProperties) {
this.tenantApplicationProperties = tenantApplicationProperties;
}
public void addTenantApplicationProperty(TenantApplicationProperty tenantApplicationProperty) {
if (this.tenantApplicationProperties == null) {
this.tenantApplicationProperties = new ArrayList<TenantApplicationProperty>();
}
tenantApplicationProperty.setTenant(this);
this.tenantApplicationProperties.add(tenantApplicationProperty);
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
product.setTenant(this);
this.product = product;
}
}
TenantApplicationProperty.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.infor.ecom.tenant.manager.model.entity.pk.TenantApplicationPropertyPK;
#Entity
#Table(name = "tenant_application_property")
#IdClass(TenantApplicationPropertyPK.class)
public class TenantApplicationProperty extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name = "tenant_id")
private Tenant tenant;
#Id
#OneToOne
#JoinColumn(name = "application_property_id")
private ApplicationProperty applicationProperty;
private String value;
public TenantApplicationProperty() {
super();
}
/**
* Added constructor to handle custom query for
* findByTenantIdApplicationPropertyName. No need to retrieve Tenant and
* ApplicationProperty
*
* #param value
*/
public TenantApplicationProperty(String value) {
setTenant(null);
setApplicationProperty(null);
setValue(value);
}
public Tenant getTenant() {
return tenant;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
public ApplicationProperty getApplicationProperty() {
return applicationProperty;
}
public void setApplicationProperty(ApplicationProperty applicationProperty) {
this.applicationProperty = applicationProperty;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((applicationProperty == null) ? 0 : applicationProperty
.hashCode());
return result;
}
#Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
TenantApplicationProperty tenantAppProp = (TenantApplicationProperty) object;
if (applicationProperty == null) {
if (tenantAppProp.applicationProperty != null) {
return false;
}
} else if (!applicationProperty.getApplicationPropertyGroup().getName().equals(tenantAppProp.applicationProperty.getApplicationPropertyGroup().getName())
|| !applicationProperty.getName().equals(tenantAppProp.applicationProperty.getName())) {
return false;
}
return true;
}
}
TenanatApplicationPropertyPK.java
package com.infor.ecom.tenant.manager.model.entity.pk;
public class TenantApplicationPropertyPK implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String tenant;
private Integer applicationProperty;
public String getTenantId() {
return tenant;
}
public void setTenantId(String tenant) {
this.tenant = tenant;
}
public Integer getApplicationPropertyId() {
return applicationProperty;
}
public void setApplicationPropertyId(Integer applicationProperty) {
this.applicationProperty = applicationProperty;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((applicationProperty == null) ? 0 : applicationProperty
.hashCode());
result = prime * result + ((tenant == null) ? 0 : tenant.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TenantApplicationPropertyPK tenantAppPropPK = (TenantApplicationPropertyPK) obj;
if (applicationProperty == null) {
if (tenantAppPropPK.applicationProperty != null) {
return false;
}
} else if (!applicationProperty
.equals(tenantAppPropPK.applicationProperty)) {
return false;
}
if (tenant == null) {
if (tenantAppPropPK.tenant != null) {
return false;
}
} else if (!tenant.equals(tenantAppPropPK.tenant)) {
return false;
}
return true;
}
}
ApplicationProperty.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "application_property")
public class ApplicationProperty extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String defaultValue;
private boolean isVisible;
private boolean clientVisible;
#OneToOne
#JoinColumn(name = "property_group_id")
private ApplicationPropertyGroup applicationPropertyGroup;
#OneToOne
#JoinColumn(name = "property_type_id")
private ApplicationPropertyType applicationPropertyType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public boolean getIsVisible() {
return isVisible;
}
public void setIsVisible(boolean isVisible) {
this.isVisible = isVisible;
}
public boolean getClientVisible() {
return clientVisible;
}
public void setClientVisible(boolean clientVisible) {
this.clientVisible = clientVisible;
}
public ApplicationPropertyGroup getApplicationPropertyGroup() {
return applicationPropertyGroup;
}
public void setApplicationPropertyGroup(ApplicationPropertyGroup applicationPropertyGroup) {
this.applicationPropertyGroup = applicationPropertyGroup;
}
public ApplicationPropertyType getApplicationPropertyType() {
return applicationPropertyType;
}
public void setApplicationPropertyType(ApplicationPropertyType applicationPropertyType) {
this.applicationPropertyType = applicationPropertyType;
}
}
ApplicationPropertyGroup.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "application_property_group")
public class ApplicationPropertyGroup extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ApplicationPropertyType.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "application_property_type")
public class ApplicationPropertyType extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
TenantServiceImpl.java
private Tenant updateTenantWithApplicationProperties(List<TenantApplicationProperty> newTenantApplicationProperties, String tenantId) {
String reason = "Update application properties.";
Tenant existingTenant = tenantRepository.findById(tenantId);
List<TenantApplicationProperty> temp = existingTenant.getTenantApplicationProperties();
existingTenant.setTenantApplicationProperties(newTenantApplicationProperties);
setApplicationPropertiesUpdateValues(temp, existingTenant);
if(newTenantApplicationProperties != null && newTenantApplicationProperties.size() != 0) {
Tenant savedTenantWithAppProps = saveTenantWithLog(existingTenant, reason);
return savedTenantWithAppProps;
}
return existingTenant;
}
private Tenant saveTenantWithLog(Tenant tenant, String reason) {
Tenant updatedTenant = tenantRepository.save(tenant);
TenantLog tenantLog = new TenantLog();
tenantLog.setTenantId(updatedTenant.getId());
tenantLog.setDisplayName(updatedTenant.getDisplayName());
tenantLog.setDescription(updatedTenant.getDescription());
tenantLog.setUrl(updatedTenant.getUrl());
tenantLog.setApiKey(updatedTenant.getApiKey());
tenantLog.setStatus(TenantStatusEnum.valueOf(updatedTenant.getStatus()));
tenantLog.setReason(reason);
tenantLog.setMessage(updatedTenant.getMessage());
tenantLogRepository.save(tenantLog);
return updatedTenant;
}
private void setApplicationPropertiesUpdateValues(List<TenantApplicationProperty> existingTenantAppProps, Tenant tenant) {
List<TenantApplicationProperty> newTenantApplicationProperties = (tenant.getTenantApplicationProperties() != null) ? tenant.getTenantApplicationProperties() : new ArrayList<TenantApplicationProperty>();
if(newTenantApplicationProperties.size() != 0) {
for(TenantApplicationProperty tenantAppProp : newTenantApplicationProperties) {
int index = existingTenantAppProps.indexOf(tenantAppProp);
if (index < 0) {
// throw an error -- tenantAppProp should always exist, right?
} else {
existingTenantAppProps.get(index).setValue(tenantAppProp.getValue());
}
}
tenant.setTenantApplicationProperties(existingTenantAppProps);
}
}
public Tenant updateTenant(Tenant tenant) {
List<Database> databases = tenant.getDatabases();
List<Administrator> administrators = tenant.getAdministrators();
validateUpdateTenant(tenant);
validateDatabases(databases);
validateAdministrators(administrators);
Tenant existingTenant = findByIdWithAllDetails(tenant.getId());
List<Database> listExistingDatabases = existingTenant.getDatabases();
Database existingEcomDb = getDatabaseByType(listExistingDatabases,
TenantManagerConstants.ECOM_DATASOURCE);
setDatabaseUpdateValues(listExistingDatabases, tenant);
setAdministratorsUpdateValues(existingTenant.getAdministrators(),
tenant);
setProductUpdateValue(existingTenant.getProduct(), tenant);
setApplicationPropertiesUpdateValues(existingTenant.getTenantApplicationProperties(), tenant);
setEcomDBParamsDefaultValues(tenant);
setAdministratorDefaultValues(tenant);
Database updateEcomDb = getDatabaseByType(tenant.getDatabases(),
TenantManagerConstants.ECOM_DATASOURCE);
Boolean shouldInstallNewDB = true;
if (existingEcomDb.getName().equalsIgnoreCase(updateEcomDb.getName())
&& existingEcomDb.getHost().equalsIgnoreCase(
updateEcomDb.getHost())
&& existingEcomDb.getPort().equals(updateEcomDb.getPort())) {
shouldInstallNewDB = false;
} else {
testEcomDBConnection(updateEcomDb);
}
int ecomDbTableCount = getEcomDBTableCount(updateEcomDb);
String[][] languages = formatAndValidateLanguages(updateEcomDb
.getEcomDatabaseParameters().getLanguages());
Tenant updatedTenant = saveExistingTenant(tenant);
if (updatedTenant != null) {
if (shouldInstallNewDB || ecomDbTableCount == 0) {
installDatabase(updateEcomDb, languages, updatedTenant);
} else {
updateDatabase(updateEcomDb, languages, updatedTenant);
}
storageService.updateTenantFolderStructure(updatedTenant);
} else {
throw new TenantManagerException(
ApiMessageConstants.M_TENANT_PROVISION_ERROR,
ApiMessageConstants.C_TENANT_PROVISION_ERROR);
}
return updatedTenant;
}
private Tenant saveExistingTenant(Tenant tenant) {
tenant.setStatus(TenantStatusEnum.INPROGRESS);
tenant.setMessage(ApiMessageConstants.M_DATABASE_UPDATE_INPROGRESS);
String reason = ApiMessageConstants.R_UPDATE_TENANT;
return saveTenantWithLog(tenant, reason);
}
In application property, you defined 1-1 relation like:
#OneToOne
#JoinColumn(name = "property_group_id")
private ApplicationPropertyGroup applicationPropertyGroup;
#OneToOne
#JoinColumn(name = "property_type_id")
private ApplicationPropertyType applicationPropertyType;
While you have not defined the same relation (note it should work bidirectionally i.e. say for e.g. if you as a person related to an employee id, then employee id is related to you as a person well) in individual property ApplicationPropertyGroup and ApplicationPropertyType.
You should add the same 1-1 relation in ApplicationPropertyGroup and ApplicationPropertyType with ApplicationProperty.

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