org.hibernate.exception.ConstraintViolationException with onetomany annotation in hibernate - spring

I am new to exploring spring boot and hibernate and facing a certain issue which i believe is not new. However with all the suggestions in place, I still could not find a way to resolve the problem that I am currently facing.
Can anyone of you please point where I am going wrong?
Following is the scenario -
I have a Category class and each instance of the category class can have many instances of sub-categories.
I have setup the relationship using #OneToMany annotation. However when trying to save records to the database, I am facing the
org.hibernate.exception.ConstraintViolationException with exception reported saying foreign key value cannot be NULL.
Please find below the class declarations
Category.class
import java.util.Date;
import java.util.Set;
import javax.persistence.JoinColumn;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.springframework.context.annotation.Scope;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#Table(name="Category")
#Scope("session")
#EntityListeners(AuditingEntityListener.class)
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Category_Id")
private Long Id;
private String CategoryName;
private String CategoryValue;
#Column(name = "IsActive", columnDefinition = "BOOLEAN")
private Boolean IsActive;
// #OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
#OneToMany(fetch = FetchType.EAGER, mappedBy = "category")
// #JoinTable(name = "Category_SubCategory", joinColumns = { #JoinColumn(name = "Category_Id") }, inverseJoinColumns = { #JoinColumn(name = "Sub_Category_Id") })
private Set<SubCategory> SubCategories;
#CreatedBy
#Column(nullable = false, updatable = false)
private String CreatedBy;
#CreatedDate
#Column(nullable = false, updatable = false)
private Date CreatedDate;
#LastModifiedBy
#Column(nullable = false)
private String ModifiedBy;
#LastModifiedDate
#Column(nullable = false)
private Date ModifiedDate;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getCategoryName() {
return CategoryName;
}
public void setCategoryName(String categoryName) {
CategoryName = categoryName;
}
public String getCategoryValue() {
return CategoryValue;
}
public void setCategoryValue(String categoryValue) {
CategoryValue = categoryValue;
}
public Boolean getIsActive() {
return IsActive;
}
public void setIsActive(Boolean isActive) {
IsActive = isActive;
}
public Set<SubCategory> getSubCategories() {
return SubCategories;
}
public void setSubCategories(Set<SubCategory> subCategories) {
SubCategories = subCategories;
}
public String getCreatedBy() {
return CreatedBy;
}
public void setCreatedBy(String createdBy) {
CreatedBy = createdBy;
}
public Date getCreatedDate() {
return CreatedDate;
}
public void setCreatedDate(Date createdDate) {
CreatedDate = createdDate;
}
public String getModifiedBy() {
return ModifiedBy;
}
public void setModifiedBy(String modifiedBy) {
ModifiedBy = modifiedBy;
}
public Date getModifiedDate() {
return ModifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
ModifiedDate = modifiedDate;
}
}
SubCategory.class
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.springframework.context.annotation.Scope;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#Table(name="SubCategory")
#Scope("session")
#EntityListeners(AuditingEntityListener.class)
public class SubCategory {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Sub_Category_Id")
private Long Id;
private String SubCategoryName;
private String SubCategoryValue;
#Column(name = "IsActive", columnDefinition = "BOOLEAN")
private Boolean IsActive;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "Category_Id", nullable = false)
private Category category;
#CreatedBy
#Column(nullable = false, updatable = false)
private String CreatedBy;
#CreatedDate
#Column(nullable = false, updatable = false)
private Date CreatedDate;
#LastModifiedBy
#Column(nullable = false)
private String ModifiedBy;
#LastModifiedDate
#Column(nullable = false)
private Date ModifiedDate;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getSubCategoryName() {
return SubCategoryName;
}
public void setSubCategoryName(String subCategoryName) {
SubCategoryName = subCategoryName;
}
public String getSubCategoryValue() {
return SubCategoryValue;
}
public void setSubCategoryValue(String subCategoryValue) {
SubCategoryValue = subCategoryValue;
}
public Boolean getIsActive() {
return IsActive;
}
public void setIsActive(Boolean isActive) {
IsActive = isActive;
}
public String getCreatedBy() {
return CreatedBy;
}
public void setCreatedBy(String createdBy) {
CreatedBy = createdBy;
}
public Date getCreatedDate() {
return CreatedDate;
}
public void setCreatedDate(Date createdDate) {
CreatedDate = createdDate;
}
public String getModifiedBy() {
return ModifiedBy;
}
public void setModifiedBy(String modifiedBy) {
ModifiedBy = modifiedBy;
}
public Date getModifiedDate() {
return ModifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
ModifiedDate = modifiedDate;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
ServiceImpl -
#Override
public void save(Category category) {
Set<SubCategory> subCategoryRec = category.getSubCategories();
if(subCategoryRec != null && subCategoryRec.size() > 0) {
for(SubCategory rec: subCategoryRec) {
try {
subcategoryRepository.save(rec);
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
try {
categoryRepository.save(category);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Not sure where I am wrong.
The exception reported has the following stacktrace -
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2855)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3426)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:619)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:273)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:254)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:299)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:272)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:109)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:775)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:748)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:753)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347)
at com.sun.proxy.$Proxy113.persist(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
at com.sun.proxy.$Proxy113.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:508)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:513)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:498)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:475)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 104 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'category_id' cannot be null

The reason is you are trying to save a child object before saving parent object. Hence change the implementation as first save parent object followed by child object as shown below.
categoryRepository.save(category);
Set<SubCategory> subCategoryRec = category.getSubCategories();
if(subCategoryRec != null && subCategoryRec.size() > 0) {
for(SubCategory rec: subCategoryRec) {
subcategoryRepository.save(rec);
}
}

Well, actually you should not do this manually. For this exact problem you should use CASCADING
From here:
In cascade, after one operation (save, update and delete) is done, it decide whether it need to call other operations (save, update and delete) on another entities which has relationship with each other.
So this should basically solve your problem:
#OneToMany(fetch = FetchType.EAGER, mappedBy = "category", cascade=CascadeType.PERSIST)
private Set<SubCategory> SubCategories;
You can choose between several Cascade-Types, if you want a different behaviour for DELETE etc.:
The cascade types supported by the Java Persistence Architecture are as below:
CascadeType.PERSIST : means that save() or persist() operations cascade to related entities.
CascadeType.MERGE : means that related entities are merged when the owning entity is merged.
CascadeType.REFRESH : does the same thing for the refresh() operation.
CascadeType.REMOVE : removes all related entities association with this setting when the owning entity is deleted.
CascadeType.DETACH : detaches all related entities if a “manual detach” occurs.
CascadeType.ALL : is shorthand for all of the above cascade operations.
See here.
EDIT: (Referencing the other proposed answer):
Calling .save will not automatically commit the transaction, try .saveAndFlush if you really want to do it manually, but i would recommend using Cascade.
See: Difference between save and saveAndFlush in Spring data jpa

Related

Targeting unmapped class error in Spring boot app

I work on basic exemplary app that is about #OneToMany & ManyToOne annotation. I define mapping between two classes, apparently there is no error but on running app it gives me an error : Use of #OneToMany or #ManyToMany targeting an unmapped class: com.orchard.orchard.model.AppUser.userRole[ com.orchard.orchard.model.UserRole]
I'm failed to understand where does problem lies as mapping also describe in AppUser. I'd be grateful for the help.
Classes are as follows:
AppUser.java
package com.orchard.orchard.model;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
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.JoinColumn;
import javax.persistence.OneToMany;
#Entity
public class AppUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(updatable = false, nullable = false)
private Integer id;
private String name;
#Column(unique = true)
private String username;
private String password;
private String email;
#Column(columnDefinition = "text")
private String bio;
private Date createdDate;
#OneToMany(mappedBy = "appUser", cascade = CascadeType.ALL, fetch =
FetchType.EAGER)
private Set<UserRole> userRole = new HashSet<>();
public AppUser() {
}
public AppUser(Integer id, String name, String username, String
password, String email, String bio,
Date createdDate, Set<UserRole> userRoles) {
this.id = id;
this.name = name;
this.username = username;
this.password = password;
this.email = email;
this.bio = bio;
this.createdDate = createdDate;
this.userRole = userRoles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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 String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Set<UserRole> getUserRoles() {
return userRole;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRole = userRoles;
}
}
UserRole.java
package com.orchard.orchard.model;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserRole {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long userRoleId;
#ManyToOne
#JoinColumn(name = "user_id")
#JsonIgnore
private AppUser appUser;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "role_id")
private Role role;
public UserRole() {
}
public UserRole(long userRoleId, AppUser appUser, Role role) {
this.userRoleId = userRoleId;
this.appUser = appUser;
this.role = role;
}
public long getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(long userRoleId) {
this.userRoleId = userRoleId;
}
public AppUser getAppUser() {
return appUser;
}
public void setAppUser(AppUser appUser) {
this.appUser = appUser;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
You forgot to add #Entity annotation to your UserRole class
#Entity
public class UserRole {
}

problem with saving data in many-to-many intermediate table spring boot

following are my entity
package bt.gov.dit.inventoryservice.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
//import org.hibernate.mapping.Set;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "items")
public class Items implements Serializable {
private Long Id;
#Column(name = "item_name")
private String itemName;
// #ManyToOne(fetch = FetchType.LAZY)
// #JoinColumn(name = "categories_id",nullable = false, referencedColumnName = "id")
private Categories categories;
private Stores stores;
//#Temporal(TemporalType.TIMESTAMP)
#Column(name = "insert_date")
private Date insertDate = new Date();
// #Temporal(TemporalType.TIMESTAMP)
#Column(name = "update_date")
private Date updateDate = new Date();
private Set<Logs> logs = new HashSet<Logs>() ;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "categories_id", nullable = false, referencedColumnName = "id")
public Categories getCategories() {
return categories;
}
public void setCategories(Categories categories) {
this.categories = categories;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "stores_id", nullable = false, referencedColumnName = "id")
public Stores getStores() {
return stores;
}
public void setStores(Stores stores) {
this.stores = stores;
}
public Date getInsertDate() {
return insertDate;
}
public void setInsertDate(Date insertDate) {
this.insertDate = insertDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "items_logs", joinColumns = #JoinColumn(name = "items_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "logs_id",referencedColumnName = "id") )
public Set<Logs> getLogs() {
return logs;
}
public void setLogs(Set<Logs> logs) {
this.logs = logs;
}
}
package bt.gov.dit.inventoryservice.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "logs")
public class Logs {
private Long id;
#Column(name = "cadet_id")
private Long cadetId;
private Set<Items> items = new HashSet<Items>() ;
#Column(name = "borrowed_date")
//#Temporal(TemporalType.TIMESTAMP)
private Date borrowedDate = new Date();
private String status;
private String comments;
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCadetId() {
return cadetId;
}
public void setCadetId(Long cadetId) {
this.cadetId = cadetId;
}
public Date getBorrowedDate() {
return borrowedDate;
}
public void setBorrowedDate(Date borrowedDate) {
this.borrowedDate = borrowedDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
#ManyToMany(fetch = FetchType.LAZY,mappedBy = "logs")
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}
}
I have many to many relationship between them. Due to that there is an intermediate table created with field item_id and log_id. Now I don't know how to save data in that table. I can save items and i can save log. But I have problem with saving the many-to-many relationship between them?

Function saves new record for room table instead of booking table (booking table has room_id as foreign key)

Ive tried to save record for booking in the bookings table, but it does not create a record and instead adds a room for the room table which i do not want as the room table is not supposed to change, only records of bookings should be added into the bookings table with a foreign key room_id of the room that was booked.
Any help would be much appreciated! Thanks!
Tbl_Bookings Entity
package com.sam.ResourceBookingMS.model;
import java.io.Serializable;
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.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
#Entity
#Table(name = "Tbl_Bookings")
public class Tbl_Bookings implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "booking_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Integer getEmployee_id() {
return employee_id;
}
public void setEmployee_id(Integer employee_id) {
this.employee_id = employee_id;
}
public Integer getEquipment_id() {
return equipment_id;
}
public void setEquipment_id(Integer equipment_id) {
this.equipment_id = equipment_id;
}
#Column(name = "type")
private String type;
#Column(name = "date")
private String date;
#Column(name = "time")
private String time;
#Column(name = "employee_id")
private Integer employee_id;
#Column(name = "equipment_id")
private Integer equipment_id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "room_id", insertable = false, updatable = false)
#Fetch(FetchMode.JOIN)
private Tbl_Rooms thisroom;
public Tbl_Rooms getThisroom() {
return thisroom;
}
public void setThisroom(Tbl_Rooms thisroom) {
this.thisroom = thisroom;
}
public Tbl_Bookings() {
}
public Tbl_Bookings(String type, String date, String time, Integer employee_id, Integer equipment_id) {
this.type = type;
this.date = date;
this.time = time;
this.employee_id = employee_id;
this.equipment_id = equipment_id;
}
}
Tbl_Rooms Entity
package com.sam.ResourceBookingMS.model;
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.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "Tbl_Rooms")
public class Tbl_Rooms implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "room_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "name")
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCapacity() {
return capacity;
}
public void setCapacity(String capacity) {
this.capacity = capacity;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "capacity")
private String capacity;
#Column(name = "location")
private String location;
#Column(name = "description")
private String description;
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "id", orphanRemoval = false, fetch = FetchType.LAZY)
private Set<Tbl_Bookings> bookings;
public Set<Tbl_Bookings> getBookings() {
return bookings;
}
public void setBookings(Set<Tbl_Bookings> bookings) {
this.bookings = bookings;
}
public Tbl_Rooms() {
}
public Tbl_Rooms(String name, String capacity, String location, String description) {
this.name = name;
this.capacity = capacity;
this.location = location;
this.description = description;
}
}
Controller
package com.sam.ResourceBookingMS;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.sam.ResourceBookingMS.model.Tbl_Bookings;
import com.sam.ResourceBookingMS.model.Tbl_Rooms;
#RestController
public class BookRmController {
#Autowired
private TblBkRepository tbr;
#Autowired
private TblRmRepository trr;
#Autowired
private EntityManager entityManager;
#RequestMapping(value = "/bookRm", method = RequestMethod.POST)
#ResponseBody
public String sendData(#RequestBody Tbl_Bookings bk) {
Tbl_Rooms rm = entityManager.getReference(Tbl_Rooms.class, 1);
System.out.println(rm.getId());
Tbl_Bookings booking = new Tbl_Bookings();
booking.setDate(bk.getDate());
booking.setType(bk.getType());
booking.setTime(bk.getTime());
Tbl_Rooms room = new Tbl_Rooms();
room.setCapacity(rm.getCapacity());
room.setDescription(rm.getDescription());
room.setLocation(rm.getLocation());
room.setName(rm.getName());
Set<Tbl_Bookings> bookingOfRoom = new HashSet<Tbl_Bookings>();
bookingOfRoom.add(booking);
room.setBookings(bookingOfRoom);
booking.setThisroom(room);
trr.save(room);
return "Confirmed";
}
}
This is the json data being sent to the controller.
{"room_id":2,"date":"2019-07-26","time":"10:00am to 10:30am","type":"Room"}
mappedBy in parent must be matched with a name defined in the child
(change id to thisroom)
case: "save Child with Parents ID" (might be above UseCase)
For that, we have to request the Child Entity with Parent ID (see JSON request at the controller and set the Parent for that Child) and using Child Repository save the object instead of using parent repository.
case: "save child-parent at same request"
For that, we have to request the Parent Entity which has multiple children (for OneToMany) and using for setting the childerns
Parent
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "thisroom", orphanRemoval = false, fetch = FetchType.LAZY, cascade=CascadeType.ALL)
private Set<Tbl_Bookings> bookings;
Child
#ManyToOne(cascade=CascadeType.ALL,fetch = FetchType.LAZY)
#JoinColumn(name = "room_id", insertable = false, updatable = false)
#Fetch(FetchMode.JOIN)
private Tbl_Rooms thisroom;
Parent-Child Relationship for referance
Parent.java
#Entity
#Table(name = "parent")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int parentId;
private String name;
#OneToMany(mappedBy="parent",fetch=FetchType.LAZY,cascade = CascadeType.PERSIST)
private List<Child> child = new ArrayList<Child>();
}
Child.java
#Entity
#Table(name = "child")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int childId;
private String account;
#ManyToOne(fetch = FetchType.LAZY, targetEntity = Parent.class)
#JoinColumn(name="parentId", referencedColumnName = "parentId", nullable = false)
private Parent parent;
}
Controller
#RestController
public class RelationshipController {
#Autowired ParentRepository parentRepository;
#Autowired ChildRepository childRepository;
//save Child with Parent at same
#PostMapping(value = "/onetomany")
public String OneToMany(#RequestBody Parent parent)
{
for (Child child : parent.getChild()) {
child.setParent(parent);
}
parent.setChild(parent.getChild());
parentRepository.save(parent);
return "saved";
/*{
"name":"Romil",
"child":[
{"account":"1"},
{"account":"2"}
]
}*/
}
//save Child with Parent's ID
#PostMapping(value = "/onetomanyPID")
public String OneToMany(#RequestBody Child child)
{
child.setParent(child.getParent());;
childRepository.save(child);
return "saved";
/*{
"account":"3",
"parent":{
"parentId":"1",
"name":"Romil"
}
}*/
}
}
UPDATE
Controller
#PostMapping("/save")
public String save(#RequestBody Tbl_Bookings bookings)
{
bookings.setThisroom(bookings.getThisroom());
tbr.save(bookings);
return "Confirmed";
}
JSON
{
"thisroom":{
"id":"1"
},
"date":"2019-07-26",
"time":"10:00am to 10:30am",
"type":"Room"
}
Tbl_Bookings
#Entity
#Table(name = "Tbl_Bookings")
public class Tbl_Bookings implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "booking_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id", referencedColumnName = "room_id")
private Tbl_Rooms thisroom;
}
Tbl_Rooms
#Entity
#Table(name = "Tbl_Rooms")
public class Tbl_Rooms implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "room_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "thisroom", orphanRemoval = false, fetch = FetchType.LAZY, cascade=CascadeType.ALL)
private List<Tbl_Bookings> bookings = new ArrayList<Tbl_Bookings>();
}
There are two points you made mistakes.
First) You need to change OneToMany relation in Tbl_Rooms class as below:
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "thisroom", orphanRemoval = false, fetch = FetchType.LAZY)
private Set<Tbl_Bookings> bookings;
The mappedBy attribute should be the class member of owner side.
Second) You create a new Tbl_Rooms instance in controller. So it is natural a new record would be created for rooms too.

Spring (Hibernate) - incomplete serialization result / many-to-many

Rest Application / Spring MVC - 3 entities: User, AccessRole, AccessPermision.
Each user has only one role, each role has one or more privileges.
The problem occurs during serialization of users with the same role.
In such case, the JSON serialization result, contains permissions only for the first user.
User Entity
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import socialcreek.access.model.AccessRole;
import socialcreek.user.views.UserViews;
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "users")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
public class User {
/**-----------------------------------------------------
* Constructor
-------------------------------------------------------*/
public User(){ }
public User(String username, String password, AccessRole accessRole) {
this.username = username;
this.password = password;
this.userAccessRole = accessRole;
}
/**-----------------------------------------------------
* Entity Properties
-------------------------------------------------------*/
#Column()
#Id
#JsonView(UserViews.BasicView.class)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JsonView(UserViews.BasicView.class)
private String username;
private String password;
#JsonView(UserViews.BasicView.class)
#ManyToMany(mappedBy = "users",fetch=FetchType.EAGER)
private Set<UsersGroup> usersGroups;
#ManyToOne(targetEntity = AccessRole.class, optional = false,fetch = FetchType.EAGER, cascade=CascadeType.MERGE)
#JoinColumn(name = "user_role")
#JsonView(UserViews.BasicView.class)
private AccessRole userAccessRole;
/**-----------------------------------------------------
* Setters & Getters
-------------------------------------------------------*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<UsersGroup> getUsersGroups() {
return usersGroups;
}
public void setUsersGroups(Set<UsersGroup> usersGroups) {
this.usersGroups = usersGroups;
}
public AccessRole getUserAccessRole() {
return userAccessRole;
}
public void setUserAccessRole(AccessRole userAccessRole) {
this.userAccessRole = userAccessRole;
}
}
AccessRole Entity
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import socialcreek.user.views.UserViews;
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "access_role")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
public class AccessRole {
/**-----------------------------------------------------
* Entity Properties
-------------------------------------------------------*/
#Id
#JsonView(UserViews.BasicView.class)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JsonView(UserViews.BasicView.class)
private String roleName;
#JsonView(UserViews.BasicView.class)
#ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#JoinTable(name = "access_role_permissions")
private Set<AccessPermission> accessPermissions;
/**-----------------------------------------------------
* Setters & Getters
-------------------------------------------------------*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Set<AccessPermission> getAccessPermissions() {
return accessPermissions;
}
public void setAccessPermissions(Set<AccessPermission> accessPermissions) {
this.accessPermissions = accessPermissions;
}
}
AccessPermission Entity
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import socialcreek.user.views.UserViews;
import javax.persistence.*;
#Entity
#Table(name = "access_permission")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
public class AccessPermission {
/**-----------------------------------------------------
* Entity Properties
-------------------------------------------------------*/
#Id
#JsonView(UserViews.BasicView.class)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JsonView(UserViews.BasicView.class)
private String permissionName;
/**-----------------------------------------------------
* Setters & Getters
-------------------------------------------------------*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPermissionName() {
return permissionName;
}
public void setPermissionName(String permissionName) {
this.permissionName = permissionName;
}
}
Serialization Result:
[ { "id":70, "username":"admin", "usersGroups":[], "userAccessRole":{
"id":68, "roleName":"ROLE_ADMIN", "accessPermissions":[
{
"id":69,
"permissionName":"FULL_ACCESS"
}]} },
{ "id":71, "username":"admin2", "usersGroups":[], "userAccessRole":68}
]
Please, have a look at accessRole and accessPermision information - it's complete only for the user:admin. In case of user:admin2 there is only information about accessRoleId ( no information about roleName, accessPermision)
It happens only when both users have the same accessRole. If I change accessRole of user:admin2 to another role - everythnink will be ok.
I found the similar issue with the correct answer (https://stackoverflow.com/a/27117097/4694022).
The problem is caused by #JsonIdentityInfo. After I removed it - it works ...now I need to find the solution to handle serialization for recursive structure but it's another story ...

org.hibernate.HibernateException: More than one row with the given identifier was found: 681

Dec 17, 2015 3:49:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [/crafartweb] threw exception [Request processing failed; nested
exception is org.hibernate.HibernateException: More than one row with
the given identifier was found: 681, for class:
com.crafart.dataobjects.StoreDO] with root cause
org.hibernate.HibernateException: More than one row with the given identifier was found: 681, for class: com.crafart.dataobjects.StoreDO
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:104)
at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:161)
at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2374)
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:722)
at org.hibernate.type.EntityType.resolve(EntityType.java:492)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:168)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:137)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1112)
at org.hibernate.loader.Loader.processResultSet(Loader.java:969)
at org.hibernate.loader.Loader.doQuery(Loader.java:917)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:348)
at org.hibernate.loader.Loader.doList(Loader.java:2548)
at org.hibernate.loader.Loader.doList(Loader.java:2534)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2364)
at org.hibernate.loader.Loader.list(Loader.java:2359)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:357)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1194)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at com.crafart.data.SellerDAOImpl.getSellerDetails(SellerDAOImpl.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy78.getSellerDetails(Unknown Source)
at com.crafart.seller.service.ManageSellerServiceImpl.getSellerDetails(ManageSellerServiceImpl.java:170)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy89.getSellerDetails(Unknown Source)
at com.crafart.MenuController.showManageSellers(MenuController.java:216)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run
(Thread.java:744)
My StoreClass is ---
/**
*
*/
package com.crafart.dataobjects;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* store entity data object maps to store table in crafart database. Property
* belongs to store table and store_id is primary key which is generated by db
* sequence <blockquote>seq_store<blockquote>
*
* #author Karthi
* #version 1.0
*
*/
#Entity
#Table(name = "STORE")
public class StoreDO implements Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = -3168290124126749175L;
#Id
#Column(name = "store_id")
#SequenceGenerator(name = "seq_store", sequenceName = "seq_store", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_store")
private long storeId;
#ManyToOne
#JoinColumn(name = "seller_id", nullable = false)
private SellerDO sellerDO;
#Column(name = "name")
private String name;
#Column(name = "store_url")
private String storeUrl;
#Column(name = "store_description")
private String storeDescription;
#Column(name = "return")
private String storeReturn;
public SellerDO getSellerDO() {
return sellerDO;
}
public void setSellerDO(SellerDO sellerDO) {
this.sellerDO = sellerDO;
}
public long getStoreId() {
return storeId;
}
public void setStoreId(long storeId) {
this.storeId = storeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStoreUrl() {
return storeUrl;
}
public void setStoreUrl(String storeUrl) {
this.storeUrl = storeUrl;
}
public String getStoreDescription() {
return storeDescription;
}
public void setStoreDescription(String store_Description) {
this.storeDescription = store_Description;
}
public String getStoreReturn() {
return storeReturn;
}
public void setStoreReturn(String store_Return) {
this.storeReturn = store_Return;
}
}
**
storeBO class is this
**
/**
*
*/
package com.crafart.dataobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* seller entity data object maps to seller table in crafart database. Property
* belongs to seller table and seller_id is primary key which is generated by db
* sequence <blockquote>seq_seller<blockquote>
*
* #author karthi
* #version 1.0
*/
#Entity
#Table(name = "SELLER")
public class SellerDO implements Serializable, Cloneable {
/**
* generated serial id
*/
private static final long serialVersionUID = 2950842206999695829L;
#Id
#Column(name = "seller_id")
#SequenceGenerator(name = "seq_seller", sequenceName = "seq_seller", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_seller")
private long sellerId;
#OneToMany(mappedBy = "sellerDO", targetEntity=StoreDO.class, cascade = CascadeType.ALL)
private StoreDO storeDO;
#Column(name = "first_Name")
private String firstName;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(name = "SELLER_ADDRESS", joinColumns = { #JoinColumn(name = "SELLER_ID") }, inverseJoinColumns = { #JoinColumn(name = "ADDRESS_ID") })
private List<AddressDO> addressDOs = new ArrayList<>();
#OneToMany(cascade = { CascadeType.ALL })
#JoinTable(name = "SELLER_CONTACT", joinColumns = { #JoinColumn(name = "SELLER_ID") }, inverseJoinColumns = { #JoinColumn(name = "CONTACT_ID") })
private List<ContactDO> contactDOs = new ArrayList<>();
#ManyToMany(mappedBy = "sellerDOs")
private List<ProductDO> productDOs = new ArrayList<>();
#Column(name = "last_Name")
private String lastName;
#Column(name = "gender")
private int gender;
#Column(name = "dob")
private String dateOfBirth;
private int tin_no;
#Column(name = "company_Name")
private String companyName;
#Column(name = "company_Logo")
private String companyLogo;
#Column(name = "epch_no")
private String epchNo;
#Column(name = "vat_no")
private String vat_no;
#Column(name = "cst_no")
private String cst_no;
/*
* add variables
* */
#Column(name = "gst_no")
private String gst_no;
#Column(name = "officeno")
private int officeno;
#Column(name = "mobileno")
private int mobileno;
#Column(name = "email")
private String email;
#Column(name = "panno")
private String panno;
#OneToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "commission_id",nullable = true)
private CommissionDO commissionDO;
private int status;
private int approved;
#Column(name = "password")
private String password;
#Column(name = "confirm_password")
private String confirmpassword;
public String getEpchNo() {
return epchNo;
}
public void setEpchNo(String epchNo) {
this.epchNo = epchNo;
}
public String getConfirmpassword() {
return confirmpassword;
}
public void setConfirmpassword(String confirmpassword) {
this.confirmpassword = confirmpassword;
}
public long getSellerId() {
return sellerId;
}
public void setSellerId(long sellerId) {
this.sellerId = sellerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getTin_no() {
return tin_no;
}
public void setTin_no(int tin_no) {
this.tin_no = tin_no;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyLogo() {
return companyLogo;
}
public void setCompanyLogo(String companyLogo) {
this.companyLogo = companyLogo;
}
public String getEpch_no() {
return epchNo;
}
public void setEpch_no(String epch_no) {
this.epchNo = epch_no;
}
public String getVat_no() {
return vat_no;
}
public int getOfficeno() {
return officeno;
}
public void setOfficeno(int officeno) {
this.officeno = officeno;
}
public int getMobileno() {
return mobileno;
}
public void setMobileno(int mobileno) {
this.mobileno = mobileno;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPanno() {
return panno;
}
public void setPanno(String panno) {
this.panno = panno;
}
public void setVat_no(String vat_no) {
this.vat_no = vat_no;
}
public String getCst_no() {
return cst_no;
}
public void setCst_no(String cst_no) {
this.cst_no = cst_no;
}
public String getGst_no() {
return gst_no;
}
public void setGst_no(String gst_no) {
this.gst_no = gst_no;
}
public CommissionDO getCommissionDO() {
return commissionDO;
}
public void setCommissionDO(CommissionDO commissionDO) {
this.commissionDO = commissionDO;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getApproved() {
return approved;
}
public void setApproved(int approved) {
this.approved = approved;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public List<ContactDO> getContactDOs() {
return contactDOs;
}
public void setContactDOs(List<ContactDO> contactDOs) {
this.contactDOs = contactDOs;
}
public StoreDO getStoreDO() {
return storeDO;
}
public void setStoreDO(StoreDO storeDO) {
this.storeDO = storeDO;
}
public List<AddressDO> getAddressDOs() {
return addressDOs;
}
public void setAddressDOs(List<AddressDO> addressDOs) {
this.addressDOs = addressDOs;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<ProductDO> getProductDOs() {
return productDOs;
}
public void setProductDOs(List<ProductDO> productDOs) {
this.productDOs = productDOs;
}
}
You have an invalid mapping
#OneToMany(mappedBy = "sellerDO", targetEntity=StoreDO.class, cascade = CascadeType.ALL)
private StoreDO storeDO;
Should be
#OneToMany(mappedBy = "sellerDO", targetEntity=StoreDO.class, cascade = CascadeType.ALL)
private List<StoreDO> storeDO;
#OneToMany(mappedBy = "sellerDO", targetEntity=StoreDO.class, cascade = CascadeType.ALL)
private Set<StoreDO> storeDO;

Resources