Reputation: 11
everyone. I am have Customer and Service tables in one to many relation - one customer can have no or many services. The Service table has a customer_id column which is a foreign key referencing the primary key of the Customer table. When retrieving customers from the database I need to get only the IDs of the related services and that is why I decided to use the @ElementCollection annotation. My mapping for the Customer is as follows:
@Entity
@Table(name = "customer")
public class CustomerEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(nullable = false)
private String name;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "service", joinColumns = @JoinColumn(name = "customer_id", updatable = false, insertable = true))
@Column(name = "id", updatable = false, insertable = true)
private Set<Integer> serviceIds;
}
Everything works perfect when I get data from the database. The problem is when I try to update a customer in the database. Upon update Hibernate deletes all the Service table rows which reference the updated customer if the serviceIds member of the customer entity was set to null or an empty Set. I would like to avoid this behavior. I would like this serviceIds member to be read only for Hibernate and to be ignored when the customer is updated in the database - i.e. I want to update only the customer table and nothing else. Is it possible to achieve this using ElementCollection?
By the way I tried the following mapping and the update of the Customer does not lead to any deletions in the Service table even if I set the serviceIds to null or an empty Set.
@OneToMany
@JoinColumn(name = "customer_id", referencedColumnName = "id", updatable = false, insertable = false)
private Set<ServiceEntity> serviceIds;
Thank You for Your help.
Upvotes: 1
Views: 1997
Reputation: 818
When modifying - even - a single element in an @ElementCollection, Hibernate will delete the old collection (the one persisted in DB) and then insert the new image of the collection. The question was already asked here:
Hibernate - @ElementCollection - Strange delete/insert behavior
In order to avoid this problem you can:
Use a List of Integer with the @OrderColumn annotation as described in the above link.
Create an Entity class wrapping your Integer (+ @Generated @Id).
Best regards
Upvotes: 3