zx_wing
zx_wing

Reputation: 1966

JPA: prevent cascade operation[persist, remove ...]

I have two entities

@Entity
@Table(name="parent")
public class Parent {
  @Id
  String uuid;

  @ElementCollection(fetch=FetchType.EAGER)
  @CollectionTable(
      name="child",
      joinColumns=@JoinColumn(name="parent_uuid", insertable=false, updatable=false)
  )

  @Column(name="uuid")
  private Set<String> childrenUuids = new HashSet<String>();
}

@Entity
@Table(name="child") 
public class Child {
  @Id
  String uuid;

  @Column(name="parent_uuid")
  String parentUuid;

}

now when I persist Parent, the children in childrenUuids are automatically persisted because the ManyToOne relationship. I want to prevent all operations to Parent(e.g. persist, remove ...) being cascaded to Child, is it possible for JPA? I have been researching for a few days, but could not find the answer. thank you.

Upvotes: 3

Views: 9199

Answers (2)

zx_wing
zx_wing

Reputation: 1966

@ElementCollection does always cascade. I finally resolve this by implementing my solution for @ElementCollection. I still use JPA annotations, instead, I add @Transient above @ElementCollection to make JPA ignore it. then I put my implementation as a JPA post-load listener to each entity, which will fill up each collection after the entity is loaded.

Upvotes: 0

Integrating Stuff
Integrating Stuff

Reputation: 5303

You should use @OneToMany instead of @ElementCollection. A @OneToMany does not cascade by default. A @ElementCollection always cascades, as far as I know, which kind of makes sense, since "@ElementCollection defines a collection of instances of a basic type or embeddable class", and basic types/embeddables are considered an integral part of their parent.

Upvotes: 1

Related Questions