Spring JPA – Saving list items in entity

Spring JPA provides easy way to saving entity in database than traditional SQL operation. Here, developer can populate entity object and trigger save function in relevant repository. In entity population, developer must be aware on list operation.

Scenario:

@Entity
@Table(name="hotelinfo")
public class HotelInfoEntity {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private Long id;
 
 private String name;
 
 private String address;
 
 @ManyToOne(fetch=FetchType.LAZY)
 @JoinColumn(name = "countryid")
 private CountryEntity country;
 
 @OneToMany(mappedBy = "hotelInfo", cascade = CascadeType.ALL, orphanRemoval=true)
 private List rooms = new ArrayList<>();

 public List getRooms() {
  return rooms;
 }

 public void setRooms(List rooms) {
  this.rooms = rooms;
 }

 ... getter and setter methods of rest 
}

Incorrect implementation:

Most of developer do mistake when set list parameters ( Eg: setRooms(List rooms) ). They create the array and call to setter function to set list attribute to object.

It is wrong. It could cause to following error, specially in update operation.

Error:

This object keeps the reference to room list. When developer crates new array and assigned using setter method, reference to room list in hotel entity might be lost. Hence following error could happen.

2017-11-08 10:38:37.557 ERROR 3756 --- [nio-8080-exec-7] r.r.h.p.setup.service.PromotionService : IN SAVE 
org.springframework.orm.jpa.JpaSystemException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: com.example.samplespringboot.entity.RoomEntity; nested exception is org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: com.example.samplespringboot.entity.RoomEntity
 at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333)
 at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
 at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
 at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)

Solution:

To add list items

Stop creating new array and assigned to list directly.
Do add element to list.
Eg:

hotelInfoEnt.getRooms().add(e);

To clear list

Clear list
Eg:

hotelInfoEnt.getRooms().clear();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s