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);
Related
I had write a restful interface in NetbeansIDE8.2 ,and i have debug it with the PostMan App in chorme, and then an exception have experenced I will show the image down here :
the HTTP ERROR 500
and my code is here ,I have return a arryList to browser
#Path("/getStu")
#GET
public List<TfFreshstudent> queryStudentNoDomitory()
{
List<TfFreshstudent> studentList= cq.queryFreshstudentNoDomitory();
if (studentList.isEmpty()) {
return studentList;
}
return null;
}
and I have tried other sub of the automatic create code ,and the error is also happened:
#GET
public List<TfDormitory> getAllTfDormitories() {
log.debug("REST request to get all TfDormitories");
List<TfDormitory> tfDormitories = tfDormitoryFacade.findAll();
return tfDormitories;
}
I have think that it maybe the return type error maybe ArryList can't be show on browser, maybe I must parse it to json type or response
This is the entity which Jeddic was create
package com.freshV3.cart.model;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "tf_dormitory")
public class TfDormitory {
#Column(name = "id", table = "tf_dormitory", nullable = false, length = 22)
#Id
private String id;
#Column(name = "buildName", table = "tf_dormitory", length = 50)
#Basic
private String buildName;
#Column(name = "comment", table = "tf_dormitory")
#Basic
private String comment;
#Column(name = "freshStudentId", table = "tf_dormitory", length = 22)
#Basic
private String freshStudentId;
#Column(name = "isDelete", table = "tf_dormitory")
#Basic
private Integer isDelete;
#Column(name = "operator", table = "tf_dormitory", length = 20)
#Basic
private String operator;
#Column(name = "roomCode", table = "tf_dormitory", length = 32)
#Basic
private String roomCode;
#Column(name = "roomId", table = "tf_dormitory")
#Basic
private String roomId;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getBuildName() {
return this.buildName;
}
public void setBuildName(String buildName) {
this.buildName = buildName;
}
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getFreshStudentId() {
return this.freshStudentId;
}
public void setFreshStudentId(String freshStudentId) {
this.freshStudentId = freshStudentId;
}
public Integer getIsDelete() {
return this.isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public String getOperator() {
return this.operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getRoomCode() {
return this.roomCode;
}
public void setRoomCode(String roomCode) {
this.roomCode = roomCode;
}
public String getRoomId() {
return this.roomId;
}
public void setRoomId(String roomId) {
this.roomId = roomId;
}
}
I'm facing a little issue : I want to select the campaigns where the average of campaignProgression equals 100 using criteria :
here is the query in SQL :
SELECT * FROM campagne as camp, progression_campagne as campProg
where camp.id = campProg.current_campaign and
(SELECT avg(campaign_progression) FROM progression_campagne)=100 group by camp.id;
here is the translation in criteria :
Criteria crit = getSessionFactory().getCurrentSession().createCriteria(Campagne.class);
crit.createAlias("progressionCampagnes", "prog");
crit.setProjection(Projections.projectionList().add(Projections.groupProperty("prog.campagne")).add(Projections.avg("prog.campaignProgression"),"moy"));
crit.add(Restrictions.eq("moy", new Float(100)));
But I'm getting this error :
org.hibernate.QueryException: could not resolve property: moy of:
ma.dataprotect.sensipro.model.Campagne
Edited :
Here are the model classes of Campaign and ProgressionCampaign :
Campagne.java :
package ma.dataprotect.sensipro.model;
// Generated 10 ao�t 2015 14:36:11 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import org.hibernate.Hibernate;
import javax.persistence.CascadeType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Campagne generated by hbm2java
*/
#SuppressWarnings("serial")
#Entity
#Table(name = "campagne")
public class Campagne implements java.io.Serializable {
private Long id;
private String name;
private Organism organism;
private byte[] image;
private Date launchDate;
private Date endDate;
private String description;
private Set<User> users = new HashSet<User>();
private Set<ProgressionCampagne> progressionCampagnes = new HashSet<ProgressionCampagne>();
private Set<ProgressionCours> progressionCourses = new HashSet<ProgressionCours>();
private Long notificationid;
private Boolean isStdr;
private Set<Cours> courses = new HashSet<Cours>();
public Campagne() {
}
public Campagne(String name, Date launchDate) {
this.name = name;
this.launchDate = launchDate;
}
public Campagne(String name, String description) {
this.name = name;
this.description = description;
}
public Campagne(String name, String description, byte[] image, Organism org) {
this.name = name;
this.description = description;
this.image = image;
this.organism = org;
}
public Campagne(String name, Date launchDate, Date endDate,
String description, Set<User> users,
Set<ProgressionCampagne> progressionCampagnes,
Set<ProgressionCours> progressionCourses) {
this.name = name;
this.launchDate = launchDate;
this.endDate = endDate;
this.description = description;
this.users = users;
this.progressionCampagnes = progressionCampagnes;
this.progressionCourses = progressionCourses;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "name", nullable = false, length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Temporal(TemporalType.DATE)
#Column(name = "launchDate", length = 10)
public Date getLaunchDate() {
return this.launchDate;
}
public void setLaunchDate(Date launchDate) {
this.launchDate = launchDate;
}
#Temporal(TemporalType.DATE)
#Column(name = "endDate", length = 10)
public Date getEndDate() {
return this.endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
#Column(name = "description")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "notificationid")
public Long getNotificationid() {
return notificationid;
}
public void setNotificationid(Long notificationid) {
this.notificationid = notificationid;
}
#ManyToMany
#JoinTable(name = "user_campagne", joinColumns = { #JoinColumn(name = "campagneid", nullable = false, updatable = true) }, inverseJoinColumns = { #JoinColumn(name = "userid", nullable = false, updatable = true) })
public Set<User> getUsers() {
// Hibernate.initialize(users);
return this.users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
#OneToMany(mappedBy = "campagne")
public Set<ProgressionCampagne> getProgressionCampagnes() {
return this.progressionCampagnes;
}
public void setProgressionCampagnes(
Set<ProgressionCampagne> progressionCampagnes) {
this.progressionCampagnes = progressionCampagnes;
}
#OneToMany(mappedBy = "campagne")
public Set<ProgressionCours> getProgressionCourses() {
return this.progressionCourses;
}
public void setProgressionCourses(Set<ProgressionCours> progressionCourses) {
this.progressionCourses = progressionCourses;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "organismsid", nullable = false)
public Organism getOrganism() {
return this.organism;
}
public void setOrganism(Organism organism) {
this.organism = organism;
}
#Column(name = "image", length = 5242880)
public byte[] getImage() {
return this.image;
}
public void setImage(byte[] image) {
this.image = image;
}
#Column(name = "isStdr", nullable = false, length = 0, columnDefinition = "bit")
public Boolean getIsStdr() {
return isStdr;
}
public void setIsStdr(Boolean isStdr) {
this.isStdr = isStdr;
}
#ManyToMany(cascade = { CascadeType.MERGE }, fetch = FetchType.LAZY)
#JoinTable(name = "campagne_cours", joinColumns = { #JoinColumn(name = "campagne_id") }, inverseJoinColumns = { #JoinColumn(name = "cours_id") })
public Set<Cours> getCourses() {
return courses;
}
public void setCourses(Set<Cours> courses) {
this.courses = courses;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Campagne other = (Campagne) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
ProgressionCampagne.java
package ma.dataprotect.sensipro.model;
// Generated 10 ao�t 2015 14:36:11 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* ProgressionCampagne generated by hbm2java
*/
#SuppressWarnings("serial")
#Entity
#Table(name = "progression_campagne")
public class ProgressionCampagne implements java.io.Serializable {
private Long id;
private Campagne campagne;
private User user;
private Cours cours;
private float campaignProgression;
private float campaignScore;
private Float campagneCorrectAnswer;
private Long campagneNbrEssai;
private Date dateDebutCamp;
private Date dateFinCamp;
public ProgressionCampagne() {
}
public ProgressionCampagne(Campagne campagne, User user, Cours cours,
float campaignProgression, float campaignScore,
Date dateDebutCamp, Date dateFinCamp) {
super();
this.campagne = campagne;
this.user = user;
this.cours = cours;
this.campaignProgression = campaignProgression;
this.campaignScore = campaignScore;
this.dateDebutCamp = dateDebutCamp;
this.dateFinCamp = dateFinCamp;
}
public ProgressionCampagne(Campagne campagne, User user, Cours cours,
int campaignProgression) {
this.campagne = campagne;
this.user = user;
this.cours = cours;
this.campaignProgression = campaignProgression;
}
public ProgressionCampagne(Campagne campagne, User user, Cours cours,
int campaignProgression,Date dateDebut) {
this.campagne = campagne;
this.user = user;
this.cours = cours;
this.campaignProgression = campaignProgression;
this.dateDebutCamp=dateDebut;
}
public ProgressionCampagne(Campagne campagne, User user,
int campaignProgression,Date dateDebut) {
this.campagne = campagne;
this.user = user;
this.campaignProgression = campaignProgression;
this.dateDebutCamp=dateDebut;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#ManyToOne
#JoinColumn(name = "current_campaign", nullable = false)
public Campagne getCampagne() {
return this.campagne;
}
public void setCampagne(Campagne campagne) {
this.campagne = campagne;
}
#ManyToOne
#JoinColumn(name = "usersid", nullable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
#ManyToOne
#JoinColumn(name = "current_course", nullable = true)
// false
public Cours getCours() {
return this.cours;
}
public void setCours(Cours cours) {
this.cours = cours;
}
#Column(name = "campaign_progression", nullable = false)
public float getCampaignProgression() {
return this.campaignProgression;
}
public void setCampaignProgression(float campaignProgression) {
this.campaignProgression = campaignProgression;
}
#Column(name = "campaign_score", nullable = true)
public float getCampaignScore() {
return campaignScore;
}
public void setCampaignScore(float campaignScore) {
this.campaignScore = campaignScore;
}
#Column(name = "date_debut_camp", nullable = true)
public Date getDateDebutCamp() {
return dateDebutCamp;
}
public void setDateDebutCamp(Date dateDebutCamp) {
this.dateDebutCamp = dateDebutCamp;
}
#Column(name = "date_fin_camp", nullable = true)
public Date getDateFinCamp() {
return dateFinCamp;
}
public void setDateFinCamp(Date dateFinCamp) {
this.dateFinCamp = dateFinCamp;
}
#Column(name = "campagne_correct_answer", nullable = true)
public Float getCampagneCorrectAnswer() {
return campagneCorrectAnswer;
}
public void setCampagneCorrectAnswer(Float campagneCorrectAnswer) {
this.campagneCorrectAnswer = campagneCorrectAnswer;
}
#Column(name = "campagne_nbr_essai", nullable = true)
public Long getCampagneNbrEssai() {
return campagneNbrEssai;
}
public void setCampagneNbrEssai(Long campagneNbrEssai) {
this.campagneNbrEssai = campagneNbrEssai;
}
}
Ok, in your criteria you have to use a subquery in order to achieve the HAVING feature. This is the code:
DetachedCriteria innerCrit = DetachedCriteria.forClass(Campagne.class);
innerCrit.createAlias("progressionCampagnes", "prog");
innerCrit.setProjection(Projections.avg("prog.campaignProgression");
innerCrit.add(Restrictions.eqProperty("id", "campOuter.id"));
DetachedCriteriaouterCrit = DetachedCriteria.forClass(Campagne.class, "campOuter");
outerCrit.add(Subqueries.eq(100, innerCrit));
This should get you the original sql result.
i'm trying to develop a function that count number of rows with specific arguments: for example i want to count the number of dossier which the client is 'client a' i want to get it in a table the first case contain the name of client and the second contanint the number of dossier
for example
client a |5
client b |12
....
right now i just wrote a function that returns the number of all rows
public Object countrow(){
Query query=em.createQuery("SELECT COUNT(d) FROM Dossier d");
Object resultat= query.getSingleResult();
System.out.println(resultat);
return resultat;
}
here's my entity named dossier :
package model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#NamedQueries({ #NamedQuery(name = "Dossier.findAll", query = "select o from Dossier o") })
public class Dossier implements Serializable {
#Column(name = "CAT_PROB", length = 4000)
private String catProb;
#Column(length = 4000)
private String client;
#Column(length = 4000)
private String contact;
#Temporal(TemporalType.DATE)
#Column(name = "DATE_APPEL")
private Date dateAppel;
#Temporal(TemporalType.DATE)
#Column(name = "DATE_CREATION")
private Date dateCreation;
#Temporal(TemporalType.DATE)
#Column(name = "DATE_FERMERTURE")
private Date dateFermerture;
#Column(name = "DEP_ID", length = 4000)
private String depId;
#Column(name = "DESCRI_PROB", length = 4000)
private String descriProb;
#Column(name = "DUREE_TRAITEMENT")
private Long dureeTraitement;
#Column(length = 4000)
private String etat;
#Column(name = "FINAL", length = 4000)
private String final_;
#Column(name = "HEURE_APPEL", length = 20)
private String heureAppel;
#Column(name = "HEURE_FERMETURE", length = 20)
private String heureFermeture;
#Id
#Column(name = "ID_DOSSIER", nullable = false, length = 4000)
private String idDossier;
#Column(name = "ING_AFF", length = 4000)
private String ingAff;
#Column(length = 4000)
private String motiftemp;
#Column(name = "OUVERT_PAR", length = 4000)
private String ouvertPar;
#Column(name = "TEL_CONTACT")
private BigDecimal telContact;
#Column(name = "TYPE_DOSSIER", length = 4000)
private String typeDossier;
public Dossier() {
}
public Dossier(String catProb, String client, String contact, Date dateAppel, Date dateCreation,
Date dateFermerture, String depId, String descriProb, Long dureeTraitement, String etat,
String final_, String heureAppel, String heureFermeture, String idDossier, String ingAff,
String motiftemp, String ouvertPar, BigDecimal telContact, String typeDossier) {
this.catProb = catProb;
this.client = client;
this.contact = contact;
this.dateAppel = dateAppel;
this.dateCreation = dateCreation;
this.dateFermerture = dateFermerture;
this.depId = depId;
this.descriProb = descriProb;
this.dureeTraitement = dureeTraitement;
this.etat = etat;
this.final_ = final_;
this.heureAppel = heureAppel;
this.heureFermeture = heureFermeture;
this.idDossier = idDossier;
this.ingAff = ingAff;
this.motiftemp = motiftemp;
this.ouvertPar = ouvertPar;
this.telContact = telContact;
this.typeDossier = typeDossier;
}
public String getCatProb() {
return catProb;
}
public void setCatProb(String catProb) {
this.catProb = catProb;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public Date getDateAppel() {
return dateAppel;
}
public void setDateAppel(Date dateAppel) {
this.dateAppel = dateAppel;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Date getDateFermerture() {
return dateFermerture;
}
public void setDateFermerture(Date dateFermerture) {
this.dateFermerture = dateFermerture;
}
public String getDepId() {
return depId;
}
public void setDepId(String depId) {
this.depId = depId;
}
public String getDescriProb() {
return descriProb;
}
public void setDescriProb(String descriProb) {
this.descriProb = descriProb;
}
public Long getDureeTraitement() {
return dureeTraitement;
}
public void setDureeTraitement(Long dureeTraitement) {
this.dureeTraitement = dureeTraitement;
}
public String getEtat() {
return etat;
}
public void setEtat(String etat) {
this.etat = etat;
}
public String getFinal_() {
return final_;
}
public void setFinal_(String final_) {
this.final_ = final_;
}
public String getHeureAppel() {
return heureAppel;
}
public void setHeureAppel(String heureAppel) {
this.heureAppel = heureAppel;
}
public String getHeureFermeture() {
return heureFermeture;
}
public void setHeureFermeture(String heureFermeture) {
this.heureFermeture = heureFermeture;
}
public String getIdDossier() {
return idDossier;
}
public void setIdDossier(String idDossier) {
this.idDossier = idDossier;
}
public String getIngAff() {
return ingAff;
}
public void setIngAff(String ingAff) {
this.ingAff = ingAff;
}
public String getMotiftemp() {
return motiftemp;
}
public void setMotiftemp(String motiftemp) {
this.motiftemp = motiftemp;
}
public String getOuvertPar() {
return ouvertPar;
}
public void setOuvertPar(String ouvertPar) {
this.ouvertPar = ouvertPar;
}
public BigDecimal getTelContact() {
return telContact;
}
public void setTelContact(BigDecimal telContact) {
this.telContact = telContact;
}
public String getTypeDossier() {
return typeDossier;
}
public void setTypeDossier(String typeDossier) {
this.typeDossier = typeDossier;
}
}
I have used many to one bidirectional relationship here I can't delete the files once i have been had into database if I am trying to delete I am getting exception has Cannot delete or update a parent row: a foreign key constraint fails.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.treamis.entity;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
/**
*
* #author
* admin
*/
#Entity
#Table(name = "LibraryBookListTable")
public class LibraryBookListEntity implements Serializable {
#Id
#GeneratedValue
#Column(name = "BookListId")
private int booklistid;
#Column(name = "ISBN", nullable = false)
private String isbn;
#Column(name = "edition", nullable = false)
private String edition;
#Column(name = "publisher", nullable = false)
private String publisher;
#Column(name = "place", nullable = false)
private String place;
#Column(name = "page", nullable = false)
private String page;
#Column(name = "source", nullable = false)
private String source;
#Column(name = "billno", nullable = false)
private String billno;
#Column(name = "callno", nullable = false)
private String callno;
#Column(name = "BookTitle", nullable = false)
private String booktitle;
#Column(name = "BookAuthor", nullable = false)
private String author;
#Column(name = "BookPrice", nullable = false)
private float price;
#Column(name = "RackNumber", nullable = false)
private String rack;
#Column(name = "PublishedYear", nullable = false)
private String publishedyear;
#Column(name = "NoofCopies", nullable = false)
private int tcopies;
#Column(name = "DateAdded", nullable = false)
private java.sql.Date dateAdded;
#Column(name = "billdate", nullable = false)
private java.sql.Date billdate;
#ManyToOne(fetch = FetchType.LAZY, targetEntity = CategoryEntity.class, cascade = CascadeType.ALL)
#JoinColumn(name = "category_Id", referencedColumnName = "category_Id", nullable = true)
private CategoryEntity categoryid;
#OneToOne
private UserEntity addedBy;
#OneToOne
private UserEntity modifiedBy;
#OneToMany(fetch = FetchType.LAZY, targetEntity = LibraryBarCodeEntity.class, cascade = CascadeType.ALL, mappedBy = "S_no")
#JoinColumn(name = "BookListId", referencedColumnName = "BookListId")
private Set< LibraryBarCodeEntity> chield;
public Set<LibraryBarCodeEntity> getChield() {
return chield;
}
public void setChield(Set<LibraryBarCodeEntity> chield) {
this.chield = chield;
}
//#Column(name = "AddedDate", nullable = false)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private java.util.Date addedate;
// #Column(name = "ModifiedDate", nullable = false)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private java.util.Date modifiedDate;
public int getBooklistid() {
return booklistid;
}
public void setBooklistid(int booklistid) {
this.booklistid = booklistid;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getBooktitle() {
return booktitle;
}
public void setBooktitle(String booktitle) {
this.booktitle = booktitle;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getRack() {
return rack;
}
public void setRack(String rack) {
this.rack = rack;
}
public int getTcopies() {
return tcopies;
}
public void setTcopies(int tcopies) {
this.tcopies = tcopies;
}
public java.sql.Date getDateAdded() {
return dateAdded;
}
public void setDateAdded(java.sql.Date dateAdded) {
this.dateAdded = dateAdded;
}
public CategoryEntity getCategoryid() {
return categoryid;
}
public void setCategoryid(CategoryEntity categoryid) {
this.categoryid = categoryid;
}
public UserEntity getAddedBy() {
return addedBy;
}
public void setAddedBy(UserEntity addedBy) {
this.addedBy = addedBy;
}
public UserEntity getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(UserEntity modifiedBy) {
this.modifiedBy = modifiedBy;
}
public java.util.Date getAddedate() {
return addedate;
}
public void setAddedate(java.util.Date addedate) {
this.addedate = addedate;
}
public java.util.Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(java.util.Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
// public String getAccessionnumber() {
// return accessionnumber;
// }
//
// public void setAccessionnumber(String accessionnumber) {
// this.accessionnumber = accessionnumber;
// }
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getBillno() {
return billno;
}
public void setBillno(String billno) {
this.billno = billno;
}
public String getCallno() {
return callno;
}
public void setCallno(String callno) {
this.callno = callno;
}
public java.sql.Date getBilldate() {
return billdate;
}
public void setBilldate(java.sql.Date billdate) {
this.billdate = billdate;
}
public String getPublishedyear() {
return publishedyear;
}
public void setPublishedyear(String publishedyear) {
this.publishedyear = publishedyear;
}
// public Set< LibraryBarCodeEntity> getChield() {
// return chield;
// }
//
// public void setChield(Set< LibraryBarCodeEntity> chield) {
// this.chield = chield;
// }
}
This is my another entity class..
package com.treamis.entity;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* #author
* admin
*/
#Entity
#Table(name = "LibraryBarCodeTable")
public class LibraryBarCodeEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "S_no", nullable = false)
private int S_no;
#Column(name = "BookBarCode", nullable = false)
private String barCode;
private String accessno;
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = LibraryBookListEntity.class)
#JoinColumn(name = "BookListId", referencedColumnName = "BookListId")
private LibraryBookListEntity parent;
public LibraryBookListEntity getParent() {
return parent;
}
public void setParent(LibraryBookListEntity parent) {
this.parent = parent;
}
public int getS_no() {
return S_no;
}
public void setS_no(int S_no) {
this.S_no = S_no;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public String getAccessno() {
return accessno;
}
public void setAccessno(String accessno) {
this.accessno = accessno;
}
}
Hi this is my complete stack trace
2014-01-09 15:44:26 ERROR JDBCExceptionReporter:78 - Cannot delete or update a parent row: a foreign key constraint fails (`treamisdemo`.`librarybooklisttable`, CONSTRAINT `FK33BC700C2F4991AA` FOREIGN KEY (`category_Id`) REFERENCES `categoryentity` (`category_Id`))
2014-01-09 15:44:26 ERROR AbstractFlushingEventListener:301 - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:146)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.treamis.library.BookList.LibraryBookListDelete.execute(LibraryBookListDelete.java:90)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
I don't know of this will help, but if you haven't already done so, you can edit your hibernate.cfg.xml file and set hibernate.show_sql from false to true in order to see what sql statements are generated when the exception occurs. Examining them may provide you a clue on what is going on. You may also consider putting print statements (System.out.println) in your set*() functions to see what primary and foreign key values are so you can examine the data in the database (now that you know the primary key value, you can see what record is being processed).
Example: System.out.println("in MyDaoClass: calling customer table: setId()="+customer.getID());
I have this entity named product. Is there a way to add a series of multiple keys? Like A key for Serial Number, a key for Serial Number and Model, a key for Model etc. How can you do this? Thank you very much.
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.entity;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Version;
/**
*
* #author god-gavedmework
*/
#Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long product_Id;
#Column(name = "SERIAL_NUMBER", nullable = false,length = 30)
private String serial_Number;
#Column(name = "DATE_ASSEMBLED", nullable = false,length = 10)
private String date_Assembled;
#Column(name = "TIME_ASSEMBLED", nullable = false,length = 20)
private String time_Assembled;
#Column(name = "MODEL", nullable = false,length = 20)
private String model;
#Column(name = "BATCH_ID", nullable = false,length = 6)
private int batch_Id;
#Column(name = "PROCESS_CODE", nullable = false,length = 3)
private int process_Code;
#Column(name = "DC_POWER_PCB_SERIAL", nullable = false,length = 20)
private String dc_Power_PCB_Serial;
#Column(name = "CONTROL_PWER_PCB_SERIAL", nullable = false,length = 20)
private String control_Power_PCB_Serial;
#Column(name = "MAINS_POWER_PCB_SERIAL", nullable = false,length = 20)
private String mains_Power_PCB_Serial;
#Column(name = "BLOWER_SERIAL", nullable = false,length = 20)
private String blower_Serial;
#Column(name = "HEATERPLATE_SERIAL", nullable = false,length = 20)
private String heaterPlate_Serial;
#Column(name = "LAST_PROCESS", nullable = false,length = 3)
private String last_Process;
#Column(name = "LAST_DATE", nullable = false,length = 20)
private String last_Date;
#Version
#Column(name = "LAST_UPDATED_TIME")
private java.sql.Timestamp updatedTime;
public Timestamp getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Timestamp updatedTime) {
this.updatedTime = updatedTime;
}
public Long getProduct_Id() {
return product_Id;
}
public void setProduct_Id(Long product_Id) {
this.product_Id = product_Id;
}
public String getSerial_Number() {
return serial_Number;
}
public void setSerial_Number(String serial_Number) {
this.serial_Number = serial_Number;
}
public String getDate_Assembled() {
return date_Assembled;
}
public void setDate_Assembled(String date_Assembled) {
this.date_Assembled = date_Assembled;
}
public String getTime_Assembled() {
return time_Assembled;
}
public void setTime_Assembled(String time_Assembled) {
this.time_Assembled = time_Assembled;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getBatch_Id() {
return batch_Id;
}
public void setBatch_Id(int batch_Id) {
this.batch_Id = batch_Id;
}
public int getProcess_Code() {
return process_Code;
}
public void setProcess_Code(int process_Code) {
this.process_Code = process_Code;
}
public String getDc_Power_PCB_Serial() {
return dc_Power_PCB_Serial;
}
public void setDc_Power_PCB_Serial(String dc_Power_PCB_Serial) {
this.dc_Power_PCB_Serial = dc_Power_PCB_Serial;
}
public String getControl_Power_PCB_Serial() {
return control_Power_PCB_Serial;
}
public void setControl_Power_PCB_Serial(String control_Power_PCB_Serial) {
this.control_Power_PCB_Serial = control_Power_PCB_Serial;
}
public String getMains_Power_PCB_Serial() {
return mains_Power_PCB_Serial;
}
public void setMains_Power_PCB_Serial(String mains_Power_PCB_Serial) {
this.mains_Power_PCB_Serial = mains_Power_PCB_Serial;
}
public String getBlower_Serial() {
return blower_Serial;
}
public void setBlower_Serial(String blower_Serial) {
this.blower_Serial = blower_Serial;
}
public String getHeaterPlate_Serial() {
return heaterPlate_Serial;
}
public void setHeaterPlate_Serial(String heaterPlate_Serial) {
this.heaterPlate_Serial = heaterPlate_Serial;
}
public String getLast_Process() {
return last_Process;
}
public void setLast_Process(String last_Process) {
this.last_Process = last_Process;
}
public String getLast_Date() {
return last_Date;
}
public void setLast_Date(String last_Date) {
this.last_Date = last_Date;
}
}
I believe what you are looking for is fundamentally incorrect. A Key should be a unique identifier for an instance of entity. In your example, you want to have a key for "Model", it simply doesn't sounds right.
If you mean something else for "Key", please clarify and we may further discuss on it.