Cascading persist and existing object

Posted by user322061 on Stack Overflow See other posts from Stack Overflow or by user322061
Published on 2010-04-21T09:20:20Z Indexed on 2010/04/21 9:23 UTC
Read the original article Hit count: 384

Filed under:
|
|

Hello,

I am working with JPA and I would like to persist an object (Action) composed of an object (Domain).

There is the Action class code:

@Entity(name="action")
@Table(name="action")
public class Action {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  @Column(name="num")
  private int num;

  @OneToOne(cascade= { CascadeType.PERSIST, CascadeType.MERGE,
      CascadeType.REFRESH })
  @JoinColumn(name="domain_num")
  private Domain domain;

  @Column(name="name")
  private String name;

  @Column(name="description")
  private String description;

  public Action() {
  }

  public Action(Domain domain, String name, String description) {
    super();
    this.domain=domain;
    this.name=name;
    this.description=description;
  }

  public int getNum() {
    return num;
  }

  public Domain getDomain() {
    return domain;
  }

  public String getName() {
    return name;
  }

  public String getDescription() {
    return description;
  }
}

When I persist an action with a new Domain, it works. Action and Domain are persisted. But if I try to persist an Action with an existing Domain, I get this error:

javax.persistence.EntityExistsException: 
Exception Description: Cannot persist detached object [isd.pacepersistence.common.Domain@1716286]. Class> isd.pacepersistence.common.Domain Primary Key> [8]

How can I persist my Action and automatically persist a Domain if it does not exist? If it exists, how can I just persist the Action and link it with the existing Domain.

Best Regards,

FF

© Stack Overflow or respective owner

Related posts about jpa

Related posts about cascading