Hibernate Mapping Exception - java

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;

Related

Error on persisting data can not set int field

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

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

Hibernate multiple foreign key

I am new to hibernate.
My problem is to resolve multiple Foreign Keys to their Value. I am able to do it with SQL but the Hibernate Annotations makes me crazy.
I got these 2 Tables for example:
Table MoveSets
MoveSet_ID
Punch_1
Punch_2
Graple_1
Graple_2
Graple_3
Graple_4
Table Moves
Move_ID
Name
Damage
MoveType_ID
Counterchance
The Punches and Graples are all foreign keys referencing to Move_ID.
My target is to do a session.createQuery("from MoveSets").list(); and to get a Moveset with the Names of the Moves instead of the IDs.
Is this possible in Hibernate?
package hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "Moves")
public class Moves implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1522367877613954187L;
private int id;
private String name;
private int damage;
private int movetype_id;
private int counterchance;
public Moves() {
}
public Moves(int id, String name, int damage, int movetype_id,
int counterchance) {
this.id = id;
this.name = name;
this.damage = damage;
this.movetype_id = movetype_id;
this.counterchance = counterchance;
}
#Id
#Column(name = "Move_ID")
#GeneratedValue(generator = "increment")
#GenericGenerator(name = "increment", strategy = "increment")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "Damage")
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
#Column(name = "MoveType_ID")
public int getMovetype_id() {
return movetype_id;
}
public void setMovetype_id(int movetype_id) {
this.movetype_id = movetype_id;
}
#Column(name = "Counterchance")
public int getCounterchance() {
return counterchance;
}
public void setCounterchance(int counterchance) {
this.counterchance = counterchance;
}
#Override
public String toString() {
return "Moves - Name: " + name;
}
}
And
package hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "MoveSets")
public class MoveSets implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6488498413048804953L;
private int id;
private int punch_1;
private int punch_2;
private int graple_1;
private int graple_2;
private int graple_3;
private int graple_4;
public MoveSets() {
}
public MoveSets(int id, int punch_1, int punch_2, int graple_1,
int graple_2, int graple_3, int graple_4) {
this.id = id;
this.punch_1 = punch_1;
this.punch_2 = punch_2;
this.graple_1 = graple_1;
this.graple_2 = graple_2;
this.graple_3 = graple_3;
this.graple_4 = graple_4;
}
#ManyToOne
#JoinColumn(name = "Moves_ID")
public Moves moves;
#Id
#Column(name = "MoveSet_ID")
#GeneratedValue(generator = "increment")
#GenericGenerator(name = "increment", strategy = "increment")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "Punch_1")
public int getPunch_1() {
return punch_1;
}
public void setPunch_1(int punch_1) {
this.punch_1 = punch_1;
}
#Column(name = "Punch_2")
public int getPunch_2() {
return punch_2;
}
public void setPunch_2(int punch_2) {
this.punch_2 = punch_2;
}
#Column(name = "Graple_1")
public int getGraple_1() {
return graple_1;
}
public void setGraple_1(int graple_1) {
this.graple_1 = graple_1;
}
#Column(name = "Graple_2")
public int getGraple_2() {
return graple_2;
}
public void setGraple_2(int graple_2) {
this.graple_2 = graple_2;
}
#Column(name = "Graple_3")
public int getGraple_3() {
return graple_3;
}
public void setGraple_3(int graple_3) {
this.graple_3 = graple_3;
}
#Column(name = "Graple_4")
public int getGraple_4() {
return graple_4;
}
public void setGraple_4(int graple_4) {
this.graple_4 = graple_4;
}
#Override
public String toString() {
return "MoveSet - ID: " + id + " Punch 1: " + punch_1;
}
}
Yes it is possible, in fact the whole point of ORM and Hibernate is to get objects (your values) insteed of plain IDs. Your mapping is wrong. You should map your relations (I assume that punches and grapples are moves) via annotations like #OneToOne,#OneToMany and so one along with #JoinColumn, so your fields insteed of this
#Column(name = "Graple_1")
public int getGraple_1() {
return graple_1;
}
should be like
#ManyToOne
#JoinColumn(name="Graple1")
public Move getGraple_1() {
return graple_1;
}
This way you will get relevant Move objects and get any data you want from them, along with the requested name

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.

Categories

Resources