Cannot create a ManyToMany relationship between two entites - java

As I referenced in the title I have two entities in google app engine project. The first one is "store" and the other is "product". Before adding the ManyToMany annotation the entities stored regularly but after the relationship addition the entities cannot be stored even though there is a successful message returned!!
Here are the entities:
Store.java
package com.cheapchase.server;
import java.util.Date;
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.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name="store", catalog="content", uniqueConstraints={
#UniqueConstraint(columnNames = "STORE_NAME"),
#UniqueConstraint(columnNames = "STORE_CODE")})
public class Store{
private int storeCode;
private Date dueDate;
private String emailAddress;
private String storeName;
private String storeAddress;
private String storeDescription;
private String userId;
private Long id;
private Set<Product> product;
public Store(){
}
public Store(String storeName, int storeCode){
this.storeName = storeName;
this.setStoreCode(storeCode);
}
public Store(String storeName, int storeCode, Set<Product> product){
this.storeName = storeName;
this.storeCode = storeCode;
this.product = product;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "STORE_ID", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="STORE_NAME", nullable=false)
public String getStoreName() {
return this.storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
/*
* Define the Many To Many relationship with product
*/
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "storae_product", catalog = "content", joinColumns = {
#JoinColumn(name = "STORE_ID", nullable = false)},
inverseJoinColumns = {#JoinColumn(name = "PRODUCT_ID", nullable = false)})
public Set<Product> getProduct(){
return this.product;
}
public void setProduct(Set<Product> product){
this.product = product;
}
/*
* Define the rest getters and setters
*/
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public String getEmailAddress() {
return this.emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getStoreDescription() {
return storeDescription;
}
public void setStoreDescription(String storeDescription) {
this.storeDescription = storeDescription;
}
public String getStoreAddress() {
return storeAddress;
}
public void setStoreAddress(String storeAddress) {
this.storeAddress = storeAddress;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public int getStoreCode() {
return storeCode;
}
public void setStoreCode(int storeCode) {
this.storeCode = storeCode;
}
public String toString(){
StringBuilder builder = new StringBuilder();
builder.append("Store [dueDate=");
builder.append(dueDate);
builder.append(", name=");
builder.append(storeName);
builder.append(", description=");
builder.append(storeDescription);
builder.append("]");
return builder.toString();
}
}
Product.java
package com.cheapchase.server;
import java.util.Set;
import java.util.HashSet;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Column;
import com.google.appengine.api.datastore.Blob;
#Entity
#Table(name = "product", catalog = "content")
public class Product {
private Long productId;
private String name;
private String description;
private int barCode;
Blob image;
private Set<Store> stores = new HashSet<Store>(0);
public Product(){
}
public Product(String name, String description){
this.name = name;
this.description = description;
}
public Product(String name, String description, Set<Store> stores){
this.name = name;
this.description = description;
this.stores = stores;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "PRODUCT_ID", unique = true, nullable = false)
public Long getProductId(){
return this.productId;
}
public void setProductId(Long productId){
this.productId = productId;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "product")
public Set<Store> getStore(){
return this.stores;
}
public void setStore(Set<Store> store){
this.stores = store;
}
public int getBarCode() {
return barCode;
}
public void setBarCode(int barCode) {
this.barCode = barCode;
}
}

Related

How to handle many-to-many relationship in Hibernate with non-primary key?

I have two objects - Role and Privilege. They have a many-to-many relationship. The code of each object is shown below.
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.NaturalId;
#Entity
#Table(name = "rml_privilege")
public class RmlPrivilege extends RmlBase implements Serializable{
/**
*
*/
private static final long serialVersionUID = -6810028565979325754L;
public static final String ATTR_NAME = "name";
#Column(name="name",nullable=false,unique=true)
private String name;
#Column(name="description")
private String description;
public String getName() {
return name;
}
public void setName(String privilege) {
this.name = privilege;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
This is the RmlRole file.
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "rml_role")
public class RmlRole extends RmlBase {
public final static String ATTR_ORG = "org.id";
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "organization")
private RmlOrganization organization;
//TODO: In case of LAZY loading, recieve an error
#ManyToMany(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
#JoinTable(name = "rml_role_privilege", joinColumns = {
#JoinColumn(name = "role", referencedColumnName = "id") }, inverseJoinColumns = {
#JoinColumn(name = "privilege", referencedColumnName = "name") })
Set<RmlPrivilege> privileges;
public RmlOrganization getOrganization() {
return organization;
}
public void setOrganization(RmlOrganization organization) {
this.organization = organization;
}
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 Set<RmlPrivilege> getPrivileges() {
return privileges;
}
public void setPrivileges(Set<RmlPrivilege> privileges) {
this.privileges = privileges;
}
}
When I try to get the RmlRole object, I end up getting the "privileges' variable to be blank. I expect the privilege object set to be prepared. I am doing it wrong somewhere but unable to identify.
My Hibernate version: 5
Java 1.8
Spring Boot application
Any help would be highly appreciated.

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.

Error: org.hibernate.MappingException: Could not determine type for: java.util.List

I keep getting the mapping exception error for a many to many project I'm trying to create. I have already tried everything that I found in previous answers on StackOverflow. I have also tried downloading a more recent version of hibernate.
Here are my models for Products and Categories. Please, if anyone has any idea of what I'm doing wrong. Please let me know.
PRODUCT MODEL
package com.cheryl.productgroups.models;
import java.util.Date;
import java.util.List;
import javax.management.relation.Role;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.JoinColumn;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name="products")
public class Product {
#Id
#GeneratedValue
private Long id;
private String name;
private String description;
private float price;
private Date createdAt;
private Date updatedAt;
#Access(AccessType.PROPERTY)
#ManyToMany(fetch = FetchType.LAZY)
#ElementCollection(targetClass=Role.class)
#JoinTable(
name = "categories_products",
joinColumns = #JoinColumn(name = "product_id"),
inverseJoinColumns = #JoinColumn(name = "category_id")
)
#PrePersist
protected void onCreate(){
this.createdAt = new Date();
}
#PreUpdate
protected void onUpdate(){
this.updatedAt = new Date();
}
private List<Category> categories;
public Product() {
}
public Product(String name, String description, float price) {
this.name = name;
this.description = description;
this.price = price;
this.createdAt = new Date();
this.updatedAt = new Date();
}
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
#Transient
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
}
CATEGORY MODEL
package com.cheryl.productgroups.models;
import java.util.Date;
import java.util.List;
import javax.management.relation.Role;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.JoinColumn;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name="categories")
public class Category {
#Id
#GeneratedValue
private Long id;
private String name;
private Date createdAt;
private Date updatedAt;
#Access(AccessType.PROPERTY)
#ManyToMany(fetch = FetchType.LAZY)
#ElementCollection(targetClass=Role.class)
#JoinTable(
name = "categories_products",
joinColumns = #JoinColumn(name = "category_id"),
inverseJoinColumns = #JoinColumn(name = "product_id")
)
#PrePersist
protected void onCreate(){
this.createdAt = new Date();
}
#PreUpdate
protected void onUpdate(){
this.updatedAt = new Date();
}
private List<Product> products;
public Category() {
}
public Category(String name) {
this.name = name;
this.createdAt = new Date();
this.updatedAt = new Date();
}
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 Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
#Transient
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
The problem here is that you are annotating the onCreate method with #ManyToMany.
Only class fields can be mapped, either by annotating the field directly or annotating its getter method.
And don't mix both field level and accessors level mapping, if you decided to choose one of them then do it with all your fields.
So in your case use the #ManyToMany and the relative annotations with the categories list:
#Access(AccessType.PROPERTY)
#ManyToMany(fetch = FetchType.LAZY)
#ElementCollection(targetClass=Role.class)
#JoinTable(
name = "categories_products",
joinColumns = #JoinColumn(name = "category_id"),
inverseJoinColumns = #JoinColumn(name = "product_id")
)
private List<Category> categories;
anotate your many to many join on List variable of categories

How to generate Code with hibernate with list and many to many relationships?

I am generating my Annotated Code Classes with hibernate and eclipse JBoss plugin, For the One to Many & Many to Many Relationships etc, the code generated used Set type for collections and generate many to many as one to many relation.
Project:
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Project generated by hbm2java
*/
#Entity
#Table(name = "project", schema = "public")
public class Project implements java.io.Serializable
{
private int projectId;
private Type type;
private Customer customer;
private String projectName;
private String description;
private Double totalContractAmount;
private Set projectConstructionMaterials = new HashSet( 0 );
public Project()
{
}
public Project(int projectId)
{
this.projectId = projectId;
}
public Project(int projectId, Type type, Customer customer, String projectName, String description,
Double totalContractAmount,
Set projectConstructionMaterials)
{
this.projectId = projectId;
this.type = type;
this.customer = customer;
this.projectName = projectName;
this.description = description;
this.totalContractAmount = totalContractAmount;
this.projectConstructionMaterials = projectConstructionMaterials;
}
#Id
#Column(name = "project_id", unique = true, nullable = false)
public int getProjectId()
{
return this.projectId;
}
public void setProjectId(int projectId)
{
this.projectId = projectId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "type_id")
public Type getType()
{
return this.type;
}
public void setType(Type type)
{
this.type = type;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "customer_id")
public Customer getCustomer()
{
return this.customer;
}
public void setCustomer(Customer customer)
{
this.customer = customer;
}
#Column(name = "project_name")
public String getProjectName()
{
return this.projectName;
}
public void setProjectName(String projectName)
{
this.projectName = projectName;
}
#Column(name = "description", length = 500)
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project") //it should be many to many annotation
public Set getProjectConstructionMaterials()
{
return this.projectConstructionMaterials;
}
public void setProjectConstructionMaterials(Set projectConstructionMaterials)
{
this.projectConstructionMaterials = projectConstructionMaterials;
}
}
ProjectConstructionMaterial
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* ProjectConstructionMaterial generated by hbm2java
*/
#Entity
#Table(name = "project_construction_material", schema = "public")
public class ProjectConstructionMaterial implements java.io.Serializable
{
private int projectConstructionMaterialId;
private ConstructionMaterialInventory constructionMaterialInventory;
private Project project;
private String description;
private String quantityArrived;
private String quantityConsumed;
public ProjectConstructionMaterial()
{
}
public ProjectConstructionMaterial(int projectConstructionMaterialId)
{
this.projectConstructionMaterialId = projectConstructionMaterialId;
}
public ProjectConstructionMaterial(int projectConstructionMaterialId,
ConstructionMaterialInventory constructionMaterialInventory, Project project, String description,
String quantityArrived, String quantityConsumed)
{
this.projectConstructionMaterialId = projectConstructionMaterialId;
this.constructionMaterialInventory = constructionMaterialInventory;
this.project = project;
this.description = description;
this.quantityArrived = quantityArrived;
this.quantityConsumed = quantityConsumed;
}
#Id
#Column(name = "project_construction_material_id", unique = true, nullable = false)
public int getProjectConstructionMaterialId()
{
return this.projectConstructionMaterialId;
}
public void setProjectConstructionMaterialId(int projectConstructionMaterialId)
{
this.projectConstructionMaterialId = projectConstructionMaterialId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "construction_material_id")
public ConstructionMaterialInventory getConstructionMaterialInventory()
{
return this.constructionMaterialInventory;
}
public void setConstructionMaterialInventory(ConstructionMaterialInventory constructionMaterialInventory)
{
this.constructionMaterialInventory = constructionMaterialInventory;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "project_id")
public Project getProject()
{
return this.project;
}
public void setProject(Project project)
{
this.project = project;
}
#Column(name = "description", length = 500)
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
#Column(name = "quantity_arrived")
public String getQuantityArrived()
{
return this.quantityArrived;
}
public void setQuantityArrived(String quantityArrived)
{
this.quantityArrived = quantityArrived;
}
#Column(name = "quantity_consumed")
public String getQuantityConsumed()
{
return this.quantityConsumed;
}
public void setQuantityConsumed(String quantityConsumed)
{
this.quantityConsumed = quantityConsumed;
}
}
ConstructionMaterialInventory
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* ConstructionMaterialInventory generated by hbm2java
*/
#Entity
#Table(name = "construction_material_inventory", schema = "public")
public class ConstructionMaterialInventory implements java.io.Serializable
{
private int constructionMaterialId;
private Type type;
private SubType subType;
private String quantity;
private String description;
private Set projectConstructionMaterials = new HashSet( 0 );
public ConstructionMaterialInventory()
{
}
public ConstructionMaterialInventory(int constructionMaterialId)
{
this.constructionMaterialId = constructionMaterialId;
}
public ConstructionMaterialInventory(int constructionMaterialId, Type type, SubType subType, String quantity,
String description, Set projectConstructionMaterials)
{
this.constructionMaterialId = constructionMaterialId;
this.type = type;
this.subType = subType;
this.quantity = quantity;
this.description = description;
this.projectConstructionMaterials = projectConstructionMaterials;
}
#Id
#Column(name = "construction_material_id", unique = true, nullable = false)
public int getConstructionMaterialId()
{
return this.constructionMaterialId;
}
public void setConstructionMaterialId(int constructionMaterialId)
{
this.constructionMaterialId = constructionMaterialId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "type_id")
public Type getType()
{
return this.type;
}
public void setType(Type type)
{
this.type = type;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "sub_type_id")
public SubType getSubType()
{
return this.subType;
}
public void setSubType(SubType subType)
{
this.subType = subType;
}
#Column(name = "quantity")
public String getQuantity()
{
return this.quantity;
}
public void setQuantity(String quantity)
{
this.quantity = quantity;
}
#Column(name = "description", length = 500)
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "constructionMaterialInventory")
public Set getProjectConstructionMaterials()
{
return this.projectConstructionMaterials;
}
public void setProjectConstructionMaterials(Set projectConstructionMaterials)
{
this.projectConstructionMaterials = projectConstructionMaterials;
}
}
Data Model
I want to change it to many to many annotations and also want to use List or ArrayList instead of Set. Can anyone please tell me how to do this with automatically code generation? Beause i have dozens of table like this and change in tables manually takes too much time..
For Example: Annotation Must be generate automatically as described in this example.
Many to Many annotation Example

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