Home JPA saving null values when update
Reply: 0

JPA saving null values when update

user2067
1#
user2067 Published in August 15, 2018, 5:37 am

I would like to know what is wrong with this relationship bellow. When I create a new record, its saving correctly, but when I try to update it, the JPA saves null value into my database. I'm using Spring Data JPA:

Entity class:

@Entity
@Table(name = "rac")
public class Rac {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idRac;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "rac", cascade = {CascadeType.ALL})
    @JsonManagedReference 
    private List<RacNatureza> racNaturezas;

// (getters and setters ok)
}

@Entity
@Table(name = "rac_natureza")
public class RacNatureza implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "id_rac")
    @Id
    @JsonBackReference 
    private Rac rac;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "id_natureza")
    @Id
    private Natureza natureza;

    @Column(name = "principal")
    private Boolean principal;

// getters and setters ok
}

@Entity
@Table(name = "natureza")
public class Natureza {

    @Id
    private Integer idNatureza;
    private String descricao;

    @OneToMany(mappedBy = "natureza", fetch = FetchType.LAZY)
    @JsonIgnore
    private List<RacNatureza> racNatureza;

// getters and setters ok
}

The code bellow is related to the service which update the object:

public Rac atualizar(Long codigo, Rac rac) {
    Rac novaRac = this.racRepository.findById(codigo).get();
    for (RacNatureza racNat: rac.getRacNaturezas()) {
        racNat.setRac(novaRac);
    }
    return racRepository.save(rac);
}

If I save as new record, works perfectly. The method which I've created is very simple:

public Rac salvar(Rac rac) {
    return racRepository.save(rac);
}

I'm wonder to know why when I save a new record its working, but when I try to update one, the system insert null values in the database like it:

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.297031 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO