Hibernate criteria issue : could not resolve property: - java

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.

Related

performance using spring JPA hibernate

I have 2 tables that are bind in a "One to many" connection when I set the relation to EAGER , then the records are fetched from table A and then for each record the data is fetched from table B if let’s say I have 100 record in table B then 100 select query are done which is really bad for the performance. what do I need to do to the set it correct so all the data will be fetched in 1 query?
here is all the code: for table A (survey)
package hibernateDataFiles;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
/**
* Surveys generated by hbm2java
*/
#Entity
#Table(name = "surveys", schema = "edi_ms")
public class Survey implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long surveyId;
private String umn;
private String firstName;
private String middleName;
private String lastName;
private String phoneNumber;
private Date creationDate;
private Long shortFeedbackGrade;
private String shortFeedbackComment;
private List<MemberAnswer> memberAnswers = new ArrayList<MemberAnswer>(0);
private List<CategoryAnswer> categoriesAnswers = new ArrayList<CategoryAnswer>(0);
public Survey() {
}
public Survey(long surveyId, String firstName, String lastName, String phoneNumber, Date creationDate) {
this.surveyId = surveyId;
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.creationDate = creationDate;
}
public Survey(long surveyId, String umn, String firstName, String middleName, String lastName, String phoneNumber,
Date creationDate, Long shortFeedbackGrade, String shortFeedbackComment,
List<MemberAnswer> memberAnswers, List<CategoryAnswer> categoriesAnswer) {
this.surveyId = surveyId;
this.umn = umn;
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.creationDate = creationDate;
this.shortFeedbackGrade = shortFeedbackGrade;
this.shortFeedbackComment = shortFeedbackComment;
this.memberAnswers = memberAnswers;
this.categoriesAnswers = categoriesAnswer;
}
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "survey_id_seq")
#SequenceGenerator(allocationSize = 1, name = "survey_id_seq", sequenceName = "EDI_MS.survey_id_seq")
#Id
#Column(name = "survey_id", unique = true, nullable = false)
public long getSurveyId() {
return this.surveyId;
}
public void setSurveyId(long surveyId) {
this.surveyId = surveyId;
}
#Column(name = "umn", length = 15)
public String getUmn() {
return this.umn;
}
public void setUmn(String umn) {
this.umn = umn;
}
#Column(name = "first_name", nullable = false, length = 20)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "middle_name", length = 20)
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
#Column(name = "last_name", nullable = false, length = 20)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "phone_number", nullable = false, length = 15)
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "creation_date", nullable = false, length = 29)
public Date getCreationDate() {
return this.creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
#Column(name = "short_feedback_grade")
public Long getShortFeedbackGrade() {
return this.shortFeedbackGrade;
}
public void setShortFeedbackGrade(Long shortFeedbackGrade) {
this.shortFeedbackGrade = shortFeedbackGrade;
}
#Column(name = "short_feedback_comment", length = 500)
public String getShortFeedbackComment() {
return this.shortFeedbackComment;
}
public void setShortFeedbackComment(String shortFeedbackComment) {
this.shortFeedbackComment = shortFeedbackComment;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "survey")
#NotFound(action = NotFoundAction.IGNORE)
public List<MemberAnswer> getMemberAnswers() {
return this.memberAnswers;
}
public void setMemberAnswers(List<MemberAnswer> membersAnswers) {
this.memberAnswers = membersAnswers;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "survey")
#NotFound(action = NotFoundAction.IGNORE)
public List<CategoryAnswer> getCategoriesAnswers() {
return this.categoriesAnswers;
}
public void setCategoriesAnswers(List<CategoryAnswer> categoriesAnswers) {
this.categoriesAnswers = categoriesAnswers;
}
}
here is the JPA
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import hibernateDataFiles.Survey;
public interface SurveyRepository extends JpaRepository<Survey, Long> {
#Query("from Survey where ?1 <= creation_date and creation_date < ?2 ")
List<Survey> getSurveysByDates(Date fromDate , Date toDate );
}
here is table B (category_answers)
package hibernateDataFiles;
// Generated Jul 5, 2018 8:37:29 AM by Hibernate Tools 5.2.10.Final
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* CategoriesAnswers generated by hbm2java
*/
#Entity
#Table(name = "categories_answers", schema = "edi_ms")
public class CategoryAnswer implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private CategoryAnswerId id;
private Category category;
private Survey survey;
private long grade;
private String comment;
public CategoryAnswer() {
}
public CategoryAnswer(CategoryAnswerId id, Category category, Survey survey, long grade) {
this.id = id;
this.category = category;
this.survey = survey;
this.grade = grade;
}
public CategoryAnswer(CategoryAnswerId id, Category category, Survey survey, long grade, String comment) {
this.id = id;
this.category = category;
this.survey = survey;
this.grade = grade;
this.comment = comment;
}
#EmbeddedId
#AttributeOverrides({ #AttributeOverride(name = "surveyId", column = #Column(name = "survey_id", nullable = false)),
#AttributeOverride(name = "categoryId", column = #Column(name = "category_id", nullable = false)) })
public CategoryAnswerId getId() {
return this.id;
}
public void setId(CategoryAnswerId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "category_id", nullable = false, insertable = false, updatable = false)
public Category getCategory() {
return this.category;
}
public void setCategory(Category category) {
this.category = category;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "survey_id", nullable = false, insertable = false, updatable = false)
#JsonIgnore
public Survey getSurvey() {
return this.survey;
}
public void setSurvey(Survey survey) {
this.survey = survey;
}
#Column(name = "grade", nullable = false)
public long getGrade() {
return this.grade;
}
public void setGrade(long grade) {
this.grade = grade;
}
#Column(name = "comment", length = 500)
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
and categoryAnswerId (pk of the table )
package hibernateDataFiles;
// Generated Jul 5, 2018 8:37:29 AM by Hibernate Tools 5.2.10.Final
import javax.persistence.Column;
import javax.persistence.Embeddable;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
/**
* CategoriesAnswersId generated by hbm2java
*/
#Embeddable
public class CategoryAnswerId implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long surveyId;
private long categoryId;
public CategoryAnswerId() {
}
public CategoryAnswerId(long surveyId, long categoryId) {
this.surveyId = surveyId;
this.categoryId = categoryId;
}
#Column(name = "survey_id", nullable = false)
public long getSurveyId() {
return this.surveyId;
}
public void setSurveyId(long surveyId) {
this.surveyId = surveyId;
}
#Column(name = "category_id", nullable = false)
public long getCategoryId() {
return this.categoryId;
}
public void setCategoryId(long categoryId) {
this.categoryId = categoryId;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof CategoryAnswerId))
return false;
CategoryAnswerId castOther = (CategoryAnswerId) other;
return (this.getSurveyId() == castOther.getSurveyId()) && (this.getCategoryId() == castOther.getCategoryId());
}
public int hashCode() {
int result = 17;
result = 37 * result + (int) this.getSurveyId();
result = 37 * result + (int) this.getCategoryId();
return result;
}
}
and the JPA:
package repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import hibernateDataFiles.Category;
public interface CategoryRepository extends JpaRepository<Category, Long>{
#Transactional
#Modifying
#Query("update Category set expiration_date = current_date() where category_id = ?1 ")
void expireCategory(Long id );
#Query("from Category where function ('coalesce' ,effectiveDate ,current_date() ) <= current_date() "
+ "and function('coalesce' ,expirationDate , to_date('50001231','yyyymmdd')) > current_date() ")
List<Category> getEffective( );
}
You have the so called 1+n problem.
One solution is to tweak the fetch settings of the collection.
Can't find a JPA way on the short hand. But since your using Hibernate, this should work:
#org.hibernate.annotations.Fetch(FetchMode.JOIN) or better FetchMode.SUBSELECT
If you're executing a query, you have to adjust the query by adding join fetch.

hibernate: Use of #OneToMany or #ManyToMany targeting an unmapped class

I'm using hibernate-core in a maven project and I want to create the entities for the following database: db_schema
I'm just starting to learn hibernate, so please bear with me on this one. I know that it might be a stupid mistake but I just can't figure it out.
I'm getting the following exception when I try to test the code:
org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: entity.User.groups[entity.IsIn]
I will list the code for my entities below
User
package entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "userId")
private int userId;
#OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<IsIn> groups = new ArrayList<>();
#Column(name = "customerName", nullable = false)
private String customerName;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "is_active", nullable = false)
private boolean is_active;
#Column(name = "notificationType", nullable = false)
private String notificationType;
#Column(name = "create_date", nullable = false)
private String create_date;
public User() { }
public User(String customerName, String password, String email, boolean is_active, String notificationType, String create_date) {
this.customerName = customerName;
this.password = password;
this.email = email;
this.is_active = is_active;
this.notificationType = notificationType;
this.create_date = create_date;
}
public void addGroup(Group group) {
IsIn isIn = new IsIn(this, group);
groups.add(isIn);
}
public void removeGroup(Group group) {
for (Iterator<IsIn> iterator = groups.iterator();
iterator.hasNext(); ) {
IsIn isIn = iterator.next();
if (isIn.getUser().equals(this) &&
isIn.getGroup().equals(group)) {
iterator.remove();
isIn.setUser(null);
isIn.setGroup(null);
}
}
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isIs_active() {
return is_active;
}
public void setIs_active(boolean is_active) {
this.is_active = is_active;
}
public String getNotificationType() {
return notificationType;
}
public void setNotificationType(String notificationType) {
this.notificationType = notificationType;
}
public String getCreate_date() {
return create_date;
}
public void setCreate_date(String create_date) {
this.create_date = create_date;
}
}
Group
package entity;
import org.hibernate.annotations.NaturalIdCache;
import javax.persistence.*;
import java.util.Objects;
#Entity
#Table(name = "group")
#NaturalIdCache
public class Group {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "groupId")
private int groupId;
#Column(name = "groupName")
private String groupName;
#Column(name = "notificationMessage", nullable = false)
private String notificationMessage;
#Column(name = "create_date", nullable = false)
private String create_date;
#OneToOne
#JoinColumn(name = "created_by")
private User created_by;
#Column(name = "isPrivate")
private boolean isPrivate;
public Group() { }
public Group(String groupName, String notificationMessage, String create_date, boolean isPrivate) {
this.groupName = groupName;
this.notificationMessage = notificationMessage;
this.create_date = create_date;
this.isPrivate = isPrivate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Group group = (Group) o;
return Objects.equals(groupId, group.getGroupId());
}
#Override
public int hashCode() { return Objects.hash(groupId); }
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getNotificationMessage() { return notificationMessage; }
public void setNotificationMessage(String notificationMessage) {
this.notificationMessage = notificationMessage;
}
public String getCreate_date() {
return create_date;
}
public void setCreate_date(String create_date) {
this.create_date = create_date;
}
public boolean isPrivate() {
return isPrivate;
}
public void setPrivate(boolean aPrivate) {
isPrivate = aPrivate;
}
public User getCreated_by() {
return created_by;
}
public void setCreated_by(User created_by) {
this.created_by = created_by;
}
}
UserGroupId (Embeddable)
package Embedded;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
#Embeddable
public class UserGroupId implements Serializable {
#Column(name = "userId")
private int userId;
#Column(name = "groupId")
private int groupId;
private UserGroupId() {}
public UserGroupId(int userId, int groupId) {
this.userId = userId;
this.groupId = groupId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
UserGroupId that = (UserGroupId) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(groupId, that.groupId);
}
#Override
public int hashCode() {
return Objects.hash(userId, groupId);
}
}
IsIn
package entity;
import Embedded.UserGroupId;
import javax.persistence.*;
import java.util.Objects;
#Entity
#Table(name = "isin")
public class IsIn {
#EmbeddedId
private UserGroupId id;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("userId")
private User user;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("groupId")
private Group group;
#OneToOne
#JoinColumn(name = "typeId")
private UserType typeId;
#Column(name = "isBlocked", nullable = false)
private boolean isBlocked;
private IsIn() {}
public IsIn(User user, Group group) {
this.user = user;
this.group = group;
this.id = new UserGroupId(user.getUserId(), group.getGroupId());
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
IsIn that = (IsIn) o;
return Objects.equals(user, that.user) &&
Objects.equals(group, that.group);
}
#Override
public int hashCode() {
return Objects.hash(user, group);
}
public User getUser() {
return user;
}
public Group getGroup() {
return group;
}
public void setUser(User user) {
this.user = user;
}
public void setGroup(Group group) {
this.group = group;
}
public UserType getTypeId() {
return typeId;
}
public void setTypeId(UserType typeId) {
this.typeId = typeId;
}
public boolean isBlocked() {
return isBlocked;
}
public void setBlocked(boolean blocked) {
isBlocked = blocked;
}
}
Privilege
package entity;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "privilege")
public class Privilege {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "privilegeId")
private int privilegeId;
#Column(name = "privilegeName", nullable = false)
private String privilegeName;
#ManyToMany(mappedBy = "privilege")
private Set<UserType> usertypes = new HashSet<>();
public Privilege() {}
public Privilege(String privilegeName) {
this.privilegeName = privilegeName;
}
public int getPrivilegeId() {
return privilegeId;
}
public void setPrivilegeId(int privilegeId) {
this.privilegeId = privilegeId;
}
public String getPrivilegeName() {
return privilegeName;
}
public void setPrivilegeName(String privilegeName) { this.privilegeName = privilegeName; }
public Set<UserType> getUsertypes() { return usertypes; }
}
UserType
package entity;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "usertype")
public class UserType {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "typeId")
private int typeId;
#Column(name = "typeName", nullable = false)
private String typeName;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name = "hasprivilege",
joinColumns = { #JoinColumn(name = "typeId") },
inverseJoinColumns = { #JoinColumn(name = "privilegeId") }
)
Set<Privilege> privileges = new HashSet<>();
public UserType() { }
public UserType(String typeName) {
this.typeName = typeName;
}
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
Notification
package entity;
import javax.persistence.*;
#Entity
#Table(name = "notification")
public class Notification {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "notificationId")
private int notificationId;
#Column(name = "notificationMessage", nullable = false)
private String notificationMessage;
#Column(name = "frequency", nullable = false)
private String frequency;
#Column(name = "create_date", nullable = false)
private String create_date;
#Column(name = "update_date", nullable = false)
private String update_date;
public Notification() {}
public Notification(String notificationMessage, String frequency, String create_date, String update_date) {
this.notificationMessage = notificationMessage;
this.frequency = frequency;
this.create_date = create_date;
this.update_date = update_date;
}
public int getNotificationId() {
return notificationId;
}
public void setNotificationId(int notificationId) {
this.notificationId = notificationId;
}
public String getNotificationMessage() {
return notificationMessage;
}
public void setNotificationMessage(String notificationMessage) {
this.notificationMessage = notificationMessage;
}
public String getFrequency() {
return frequency;
}
public void setFrequency(String frequency) {
this.frequency = frequency;
}
public String getCreate_date() {
return create_date;
}
public void setCreate_date(String create_date) {
this.create_date = create_date;
}
public String getUpdate_date() {
return update_date;
}
public void setUpdate_date(String update_date) {
this.update_date = update_date;
}
}
Message
package entity;
import javax.persistence.*;
#Entity
#Table(name = "message")
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "messageId")
private String messageId;
#ManyToOne
#JoinColumn(name = "userId")
private User userId;
#ManyToOne
#JoinColumn(name = "groupId")
private Group groupId;
#Column(name = "message")
private String message;
#Column(name = "create_date")
private String create_date;
#ManyToOne
#JoinColumn(name = "notificationId")
private Notification notificationId;
public Message() { }
public Message(User userId, Group groupId, String message, String create_date, Notification notificationId) {
this.userId = userId;
this.groupId = groupId;
this.message = message;
this.create_date = create_date;
this.notificationId = notificationId;
}
public String getMessageId() {
return messageId;
}
public User getUserId() {
return userId;
}
public Group getGroupId() {
return groupId;
}
public String getMessage() {
return message;
}
public String getCreate_date() {
return create_date;
}
public Notification getNotificationId() {
return notificationId;
}
}
I've been looking on Stack for a solution on similar issues but the suggestions did not help in my case. I'm kinda stuck right now.
Any help will be highly appreciated. Thank your for your time.

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

How to update the record by adding one more child row for exciting child by using hibernate?

Here I am going to update the record. By adding one more child for the exciting parent and here I am removing the child by iterating the child's and then I am updating the record but its giving the exception as.
EXCEPTION:org.hibernate.HibernateException: Found two representations of same collection: com.treamis.entity.LibraryBookListEntity.chield
Here is my code.
LibraryBookForm lb = (LibraryBookForm) form;
int bookid = lb.getBooklistid();
System.out.println("bookidbookidbookid" + bookid);
String[] bar = lb.getBarcode();
String[] accission = lb.getAccessno();
System.out.println("accissionaccission" + bar);
UserEntity msg;
HttpSession session = request.getSession(false);
msg = (UserEntity) session.getAttribute("user");
int catid = lb.getCategory();
Session ses = HibernateUtil.getSessionFactory().openSession();
String d1 = lb.getBilldate();
java.util.Date temp = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(d1);
java.sql.Date date = new java.sql.Date(temp.getTime());
String d2 = lb.getDateAdded();
java.util.Date temp1 = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(d2);
java.sql.Date submissionDate = new java.sql.Date(temp1.getTime());
CategoryEntity ce = (CategoryEntity) ses.get(CategoryEntity.class, catid);
LibraryBookListEntity lbl = (LibraryBookListEntity) ses.load(LibraryBookListEntity.class, bookid);
Set<LibraryBarCodeEntity> s1 = lbl.getChield();
for (LibraryBarCodeEntity lbb : s1) {
System.out.println("inside delte");
ses.delete(lbb);
}
Transaction tx = ses.beginTransaction();
lbl.setEdition(lb.getEdition());
lbl.setPublisher(lb.getPublisher());
lbl.setPlace(lb.getPlace());
lbl.setPage(lb.getPag());
lbl.setSource(lb.getSource());
lbl.setBillno(lb.getBillno());
lbl.setBilldate(date);
lbl.setPublishedyear(lb.getPublishedyear());
lbl.setCallno(lb.getCallno());
lbl.setIsbn(lb.getIsbn());
lbl.setBooktitle(lb.getBooktitle());
lbl.setRack(lb.getRack());
lbl.setAuthor(lb.getAuthor());
lbl.setPrice(lb.getPrice());
lbl.setCategoryid(ce);
lbl.setDateAdded(submissionDate);
lbl.setTcopies(lb.getTcopies());
lbl.setAddedBy(msg);
lbl.setAddedate(new Date());
lbl.setModifiedBy(null);
lbl.setModifiedDate(null);
try {
java.util.List list = Arrays.asList(bar);
Document document = new Document(new Rectangle(PageSize.A4));
File file = new File("d://" + lb.getBooktitle() + ".pdf");
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file, false));
document.open();
Paragraph para = new Paragraph();
Set<LibraryBarCodeEntity> s = new HashSet<LibraryBarCodeEntity>();
LibraryBarCodeEntity mb = null;
for (int i = 0; i < list.size(); i++) {
System.out.println("inside library model edit");
mb = new LibraryBarCodeEntity();
System.out.println("bar[i]" + bar[i]);
System.out.println("bar[i]" + accission[i]);
mb.setBarCode(bar[i]);
mb.setAccessno(accission[i]);
mb.setParent(lbl);
para.add(new Phrase(new Chunk(BarcodeDao.genarateBarcode(bar[i], writer), 0, 0, true)));
para.add(new Phrase(Chunk.NEWLINE));
para.add(new Phrase(Chunk.NEWLINE));
// s.add(mb);
ses.saveOrUpdate(lbl);
}
// lbl.setChield(s);
tx.commit();
Here is my LibraryBookListEntity Entity
/*
* 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.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;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
/**
*
* #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)
#JoinColumn(name = "category_Id", referencedColumnName = "category_Id", nullable = true)
private CategoryEntity categoryid;
#OneToOne
private UserEntity addedBy;
#OneToOne
private UserEntity modifiedBy;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
#JoinColumn(name = "BookListId", referencedColumnName = "BookListId")
#Cascade({CascadeType.SAVE_UPDATE})
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;
// }
}
Here is my another entity
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.treamis.entity;
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;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
/**
*
* #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)
#JoinColumn(name = "BookListId", referencedColumnName = "BookListId")
#Cascade({CascadeType.ALL})
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;
}
}
You formed new set . You have to set that to the parent object (that is lb1). Then if u save lb1 changes in the child set will be saved. (Make sure you have given cascede save-update or all property in mapping for the set )
for (int i = 0; i < list.size(); i++) {
System.out.println("inside library model edit");
mb = new LibraryBarCodeEntity();
System.out.println("bar[i]" + bar[i]);
System.out.println("bar[i]" + accission[i]);
mb.setBarCode(bar[i]);
mb.setAccessno(accission[i]);
mb.setParent(lbl);
para.add(new Phrase(new Chunk(BarcodeDao.genarateBarcode(bar[i], writer), 0, 0, true)));
para.add(new Phrase(Chunk.NEWLINE));
para.add(new Phrase(Chunk.NEWLINE));
s.add(mb);
}
lbl.setChield(s);
ses.saveOrUpdate(lbl);
tx.commit();

Hibernate :Cannot delete or update a parent row: a foreign key constraint fails

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

Categories

Resources