开发者

JPA Collection mapping to Master table

开发者 https://www.devze.com 2023-04-03 17:52 出处:网络
I have a number of ServiceDefinition entities. I\'m trying to create a series of License entities that contain a reference to one or more ServiceDefinition entities;

I have a number of ServiceDefinition entities. I'm trying to create a series of License entities that contain a reference to one or more ServiceDefinition entities;

@Entity

public class License {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
private int id;

@Column(name="serial")
private int serialNumber;

@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
protected List<ServiceDefinition> definitions;

    <-- rest of class omitted -->

  @Entity
  public class ServiceDefinition implements Serializable {


/**
 * 
 */
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
private int id;

  <-- rest of class omitted -->  

When the d开发者_StackOverflowatabase is instantiated JPA creates me a ServiceDefinition table, a License table and a License_ServiceDefinition table.

I have been able to add and update records into this structure, but when I try to delete a License enity, JPA deletes the entries from the License_ServiceDefinition table and the License table. Then JPA tries to delete from the ServiceDefinition table which I don't want.

The ServiceDefinition is a "Master" table and in the same way as an OrderHeader entity might contain a reference to a Customer entity and deleting the OrderHeader should not result in deletion of the Customer, I want to be able to delete a License and it's references to ServiceDefinition entities without deleting the ServiceDefinition itself. I hope that makes sense.

Is this possible or do I need to deal with this manually.

Regards

Regards


Just remove the cascade=CascadeType.ALL and orphanRemoval=true from the annotation.

orphanRemoval=true means that if a service definition is removed from the list of service definitions, it should be removed.

CascadeType.ALL means that every operation made on a license should be cascaded to each service definition in the list. So if you delete the license, the service definitions in the list are deleted in cascade.

Those attibutes have a meaning, and have consequences. Don't use them without understanding their meaning. And don't add them everywhere thinking you code might magically work better.

0

精彩评论

暂无评论...
验证码 换一张
取 消