EclipseLink JPA中的CASCADETYPE

时间:2011-10-05 14:52:21

标签: java jpa eclipselink

我有两个classess。第一堂课是TNota。

@Entity
@Table(name = "t_nota")
public class TNota implements Serializable {    
@Id
@SequenceGenerator(name="seq_t_nota", sequenceName="seq_t_nota", initialValue=37,   allocationSize=1)
@GeneratedValue(generator="seq_t_nota")
@Basic(optional = false)
@Column(name = "id_nota", nullable = false)
private double idNota;

@Basic(optional = false)
@Column(name = "nota", nullable = false, length = 255)
private String nota;

@JoinColumn(name = "id_tipo_nota", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false)
private NTipoNota nTipoNota;

public TNota() {
}

public TNota(Long idNota) {
    this.idNota = idNota;
}

public double getIdNota() {
    return idNota;
}

public void setIdNota(double idNota) {
    this.idNota = idNota;
}

public String getNota() {
    return nota;
}

public void setNota(String nota) {
    this.nota = nota;
}

public NTipoNota getNTipoNota() {
     return nTipoNota;
}

public void setNTipoNota(NTipoNota nTipoNota) {
    this.nTipoNota = nTipoNota;
}
}

另一类是NtipoNota ..

@Entity
@Table(name = "n_tipo_nota")
public class NTipoNota implements Serializable {
@Id
@Basic(optional = false)
@Column(name = "id", nullable = false)
private Integer id;
@Basic(optional = false)
@Column(name = "nombre", nullable = false, length = 255)
private String nombre;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "nTipoNota",fetch=FetchType.LAZY)
private List<TNota> tNotaList;

public NTipoNota() {
}

public NTipoNota(Integer id) {
    this.id = id;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}    

public List<TNota> getTNotaList() {
    return tNotaList;
}

public void setTNotaList(List<TNota> tNotaList) {
    this.tNotaList = tNotaList;
}
}

我将所有类型的笔记存储在数据库中。我只是想坚持一个新的TNota如下,但我得到一个错误,因为它持续存在id = 5的新NTipoNota已经存在于数据库中。使用TopLink我从未遇到过这个问题:

TNota note = new TNota();
note.setNota("Hola mundo");
note.setNTipoNota(new NTipoNota(5));
manager.persist(note);

我修正如下:

TNota note = new TNota();
note.setNota("Hola mundo");
note.setNTipoNota(manager.find(NTipoNota.class, 5);
manager.persist(note);

由于此问题,我不想更改所有代码。是否有任何形式可以在我们创建它们的新实例时不持久保存对象?

谢谢大家。

1 个答案:

答案 0 :(得分:1)

您的新代码是正确的,并且您之前的代码不正确。您也可以调用merge来解决关系。