find By Id Could not work in Spring Boot - java

return null using FindById
Lead.java
import java.io.Serializable;
import java.time.LocalDate;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.lang.Nullable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name = "leads")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},allowGetters = true)
public class Lead implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank(message = "Name is mandatory")
private String name;
#Nullable
private String phone;
#Nullable
private String standard;
#Nullable
private String stream;
#Column(columnDefinition = "boolean default true")
private Boolean active = true;
#Nullable
private String remark;
#Column(columnDefinition = "VARCHAR(30) NOT NULL default 'lead'")
private String type="lead";
#ManyToOne(fetch = FetchType.LAZY, optional = false )//, cascade = CascadeType.REMOVE)
#JoinColumn(name = "school_id", nullable = false )
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
private School school;
#Nullable
#Column(name = "school_id", insertable = false, updatable = false)
private Long schoolId;
#ManyToOne
#JoinColumn(name = "lead_status_id", nullable = false)
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
private LeadStatus leadStatus;
#Nullable
#Column(name = "lead_status_id", insertable = false, updatable = false)
private Long leadStatusId;
#ManyToOne
#JoinColumn(name = "user_id", nullable = false)
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
private User user;
#Nullable
#Column(name = "user_id", insertable = false, updatable = false)
private Long userId;
#CreationTimestamp
private LocalDate createdAt;
#UpdateTimestamp
private LocalDate updatedAt;
public Lead() {
// TODO Auto-generated constructor stub
}
public Lead(#NotBlank(message = "Name is mandatory") String name, String phone, String standard, String stream, String remark, String type, School school) {
this.name = name;
this.phone = phone;
this.standard = standard;
this.stream = stream;
this.remark = remark;
this.school = school;
}
public LeadStatus getLeadStatus() {
return leadStatus;
}
public void setLeadStatus(LeadStatus leadStatus) {
this.leadStatus = leadStatus;
}
public Long getLeadStatusId() {
return leadStatusId;
}
public void setLeadStatusId(Long leadStatusId) {
this.leadStatusId = leadStatusId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
public Long getSchoolId() {
return schoolId;
}
public void setSchoolId(Long schoolId) {
this.schoolId = schoolId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public LocalDate getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDate createdAt) {
this.createdAt = createdAt;
}
public LocalDate getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDate updatedAt) {
this.updatedAt = updatedAt;
}
}
Controller method
#GetMapping("/{id}")
public HashMap<String, Object> getLeadById(#PathVariable(value = "id") Long leadId) {
System.out.println(leadId);
Lead lead = leadRepository.findById(leadId).orElseThrow(() -> new ItemNotFoundException("Lead", "id", leadId));
return ResponseFormat.createFormat(lead, "Listed Successfully");
}
LeadRepository.java
package com.lakshya.lakshya.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.lakshya.lakshya.model.Lead;
public interface LeadRepository extends PagingAndSortingRepository<Lead, Long> {
}

did you try to extends JpaRepository< , > ? maybe it will be the solution
public interface LeadRepository extends JpaRepository<Lead, Long> {
}
JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch
because of this inheritance relationship, the JpaRepository contains the full API of CrudRepository and PagingAndSortingRepository.
Notify me if it works

Related

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.

Can't save child objects with OneToMany Relationship in Springboot/Hibernate

I am building an order tracking system in Spring Boot, using Hibernate annotations and Repositories. I have an Order class, which can have a list of OrderItems. These map to a ORDER and ORDER_ITEMS table respectively. The code I have representing the two is below.
Order.java
package net.township.order;
import org.hibernate.annotations.Cascade;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Set;
#Entity
#Table(name = "orders")
public class Order {
public Order() {
}
public Order(long merchantId, String firstDeliveryName, String
lastDeliveryName, String deliveryAddress, String status, Date createDate,
Date updateDate) {
this.merchantId = merchantId;
this.lastDeliveryName = lastDeliveryName;
this.firstDeliveryName = firstDeliveryName;
this.deliveryAddress = deliveryAddress;
this.status = status;
this.createDate = createDate;
this.updateDate = updateDate;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "order_id", unique = true)
private long orderId;
#Column(name = "merchant_id")
private long merchantId;
#Column(name = "first_delivery_name")
private String firstDeliveryName;
#Column(name = "last_delivery_name")
private String lastDeliveryName;
#Column(name = "delivery_address")
private String deliveryAddress;
#Column
private String status;
#OneToMany(mappedBy = "order", cascade = {
CascadeType.ALL,CascadeType.PERSIST,CascadeType.MERGE })
private List<OrderItem> orderItems;
#Column(name = "create_date")
private Date createDate;
#Column(name = "update_date")
private Date updateDate;
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public long getMerchantId() {
return merchantId;
}
public void setMerchantId(long merchantId) {
this.merchantId = merchantId;
}
public List<OrderItem> getOrderItems() {
return orderItems;
}
public void setOrderItems(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
public String getLastDeliveryName() {
return lastDeliveryName;
}
public void setLastDeliveryName(String lastDeliveryName) {
this.lastDeliveryName = lastDeliveryName;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public String getFirstDeliveryName() {
return firstDeliveryName;
}
public void setFirstDeliveryName(String firstDeliveryName) {
this.firstDeliveryName = firstDeliveryName;
}
public String getDeliveryAddress() {
return deliveryAddress;
}
public void setDeliveryAddress(String deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
OrderItem.java
package net.township.order;
import com.fasterxml.jackson.annotation.JsonBackReference;
import org.hibernate.annotations.Cascade;
import javax.persistence.*;
#Entity
#Table(name = "order_items")
public class OrderItem {
#Id
#GeneratedValue
#Column(name = "id")
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
#Column
private String name;
#Column
private String description;
#Column
private Long quantity;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn (name="ORDER_ID")
#JsonBackReference
#Cascade(value={org.hibernate.annotations.CascadeType.ALL})
private Order order;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
}
When I POST a new Order from my front-end, it is mapped to an Order object correctly. All OrderItems that were provided in the JSON are present in the object as a List as well. However, after I save it to the database using my OrderRepository's save method (it's just a CrudRepository), my database contains a new Order object with the correct fields, but nothing is ever created in ORDER_ITEMS.
I've poked around the documentation for both Hibernate and JPA OneToMany annotations, and I don't see where I'm going wrong here. I'll also add that I'm doing no manual schema creation, letting SpringBoot handle setting up everything in H2 for me.
This is what ultimately worked for me.
Order.java
package net.township.order;
import org.hibernate.annotations.Cascade;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Set;
#Entity
#Table(name = "orders")
public class Order {
public Order() {
}
public Order(long merchantId, String firstDeliveryName, String lastDeliveryName, String deliveryAddress, String status, Date createDate, Date updateDate) {
this.merchantId = merchantId;
this.lastDeliveryName = lastDeliveryName;
this.firstDeliveryName = firstDeliveryName;
this.deliveryAddress = deliveryAddress;
this.status = status;
this.createDate = createDate;
this.updateDate = updateDate;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "order_id", unique = true)
private long orderId;
#Column(name = "merchant_id")
private long merchantId;
#Column(name = "first_delivery_name")
private String firstDeliveryName;
#Column(name = "last_delivery_name")
private String lastDeliveryName;
#Column(name = "delivery_address")
private String deliveryAddress;
#Column
private String status;
#OneToMany( cascade = CascadeType.ALL)
#JoinColumn(name = "order_id", referencedColumnName = "order_id")
private List<OrderItem> orderItems;
#Column(name = "create_date")
private Date createDate;
#Column(name = "update_date")
private Date updateDate;
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public long getMerchantId() {
return merchantId;
}
public void setMerchantId(long merchantId) {
this.merchantId = merchantId;
}
public List<OrderItem> getOrderItems() {
return orderItems;
}
public void setOrderItems(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
public String getLastDeliveryName() {
return lastDeliveryName;
}
public void setLastDeliveryName(String lastDeliveryName) {
this.lastDeliveryName = lastDeliveryName;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public String getFirstDeliveryName() {
return firstDeliveryName;
}
public void setFirstDeliveryName(String firstDeliveryName) {
this.firstDeliveryName = firstDeliveryName;
}
public String getDeliveryAddress() {
return deliveryAddress;
}
public void setDeliveryAddress(String deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
OrderItem.java
package net.township.order;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.*;
#Entity
#Table(name = "order_items")
public class OrderItem {
#Id
#GeneratedValue
#Column(name = "id")
private Long id;
#Column(name = "order_id")
private Long orderId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column
private String name;
#Column
private String description;
#Column
private Long quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
}
Add CascadeType.ALL to your mapping.

Hibernate criteria issue : could not resolve property:

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.

Spring data Join multiple tables

This is it my database project:
I have a problem with the correct combination of tables, as it is in the picture.
This is my files:
Category.java
#Entity
public class Category {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String categoryName;
protected Category() {}
public Category(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryName() {
return categoryName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
#Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s']",
id, categoryName);
}
}
Items.java
#Entity
#Table(name = "Items")
public class Items {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int ItemId;
private String ItemName;
private String price;
private Set<Locals> locals = new HashSet<Locals>(0);
public Items(){
}
public Items(String price, String itemName) {
this.price = price;
this.ItemName = itemName;
}
public void setItemId(int itemId) {
ItemId = itemId;
}
public void setLocals(Set<Locals> locals) {
this.locals = locals;
}
public void setPrice(String price) {
this.price = price;
}
public void setItemName(String itemName) {
ItemName = itemName;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ItemId", unique = true, nullable = false)
public int getItemId() {
return ItemId;
}
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "itemsTo")
public Set<Locals> getLocals() {
return locals;
}
#Column(name = "price", nullable = false, length = 10)
public String getPrice() {
return price;
}
#Column(name = "ItemName", nullable = false, length = 10)
public String getItemName() {
return ItemName;
}
}
Locals.java
#Entity
#Table(name = "Locals")
public class Locals {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int LocalId;
private String localName;
private String address;
private String phoneNumber;
private String coorX;
private String coorY;
private Set<Items> itemsTo = new HashSet<Items>(0);
public Locals(){
}
public Locals(String localName,String address,String phoneNumber, String coorY, String coorX) {
this.coorY = coorY;
this.coorX = coorX;
this.phoneNumber = phoneNumber;
this.address = address;
this.localName = localName;
}
public Locals(String localName,String address,String phoneNumber, String coorY, String coorX, Set<Items> itemsTo) {
this.coorY = coorY;
this.coorX = coorX;
this.phoneNumber = phoneNumber;
this.address = address;
this.localName = localName;
this.itemsTo = itemsTo;
}
public void setLocalId(int localId) {
LocalId = localId;
}
public void setLocalName(String localName) {
this.localName = localName;
}
public void setAddress(String address) {
this.address = address;
}
public void setCoorX(String coorX) {
this.coorX = coorX;
}
public void setCoorY(String coorY) {
this.coorY = coorY;
}
public void setItemsTo(Set<Items> itemsTo) {
this.itemsTo = itemsTo;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "LocalId", unique = true, nullable = false)
public int getLocalId() {
return LocalId;
}
#Column(name = "localName", unique = false, nullable = false, length = 10)
public String getLocalName() {
return localName;
}
#Column(name = "address", unique = false, nullable = false, length = 10)
public String getAddress() {
return address;
}
#Column(name = "phoneNumber", unique = false, nullable = false, length = 10)
public String getPhoneNumber() {
return phoneNumber;
}
#Column(name = "coorX", unique = false, nullable = false, length = 10)
public String getCoorX() {
return coorX;
}
#Column(name = "coorY", unique = false, nullable = false, length = 10)
public String getCoorY() {
return coorY;
}
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "ItemsFinall", joinColumns = {
#JoinColumn(name = "LocalId", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "ItemId",
nullable = false, updatable = false) })
public Set<Items> getItemsTo() {
return itemsTo;
}
}
and ItemsFinall.java
#Entity
#Table(name = "ItemsFinall")
public class ItemsFinall {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private int ItemId;
private int CategoryId;
private int LocalId;
public ItemsFinall(int id, int localId, int categoryId, int itemId) {
this.LocalId = localId;
this.CategoryId = categoryId;
this.ItemId = itemId;
this.id=id;
}
public void setId(int id) {
this.id = id;
}
public void setLocalId(int localId) {
LocalId = localId;
}
public void setCategoryId(int categoryId) {
CategoryId = categoryId;
}
public void setItemId(int itemId) {
ItemId = itemId;
}
public int getLocalId() {
return LocalId;
}
public int getCategoryId() {
return CategoryId;
}
public int getItemId() {
return ItemId;
}
public int getId() {
return id;
}
}
I get the following error: Caused by: org.springframework.data.mapping.PropertyReferenceException: No property categoryName found for type ItemsFinall!
I do not know what to do to properly connect the table.
ItemsServiceImpl.java
package dnfserver.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Łukasz on 2015-03-14.
*/
#Component
public class CategoryServiceImpl implements CategoryService {
#Autowired
private CategoryRepository categoryRepository;
private Map<Integer,String> categoryMap = new HashMap<Integer, String>();
#Override
public Category create(Category category) {
Category createdCategory = category;
return categoryRepository.save(createdCategory);
}
#Override
public Category delete(int id) {
return null;
}
#Autowired
public Map<Integer,String> findAll(){
int i=0;
for (Category cat : categoryRepository.findAll()) {
categoryMap.put(i,cat.toString());
i++;
}
return categoryMap;
}
#Override
public Category update(Category shop) {
return null;
}
#Override
public Category findById(int id) {
return categoryRepository.findOne(id);
}
}
In hibernate/JPA you model the relationship between Entities, but not use plain Ids!
For example
#Entity
#Table(name = "ItemsFinall")
public class ItemsFinall {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
//instead of: private int ItemId;
#OneToMany
private Item item;
//instead of: private int CategoryId;
#OneToMany
private Category category;
//instead of: private int LocalId;
#OneToMany
private Local local;
...
(You also need to fix the Set<Locals> locals in item)

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