开发者

CASCADETYPE in EclipseLink JPA

I have two classess. The first class is 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;
}
}

and the other class is 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;
}
}

I have all type of note开发者_运维技巧s stored in database. I just want to persist a new TNota as follows, but I got an error because it persists a new NTipoNota with id= 5 which already exists in database. Using TopLink I never had this trouble:

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

I fixed as follow:

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

I would like not to have to change all code due to this problem. Is there any form to make that do not persist the objects when we create a new instance of them?.

Thanks for all.


You new code is correct, and your previous code is not correct. You could also call merge to resolve the relationship.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜