Home JPA saving null values when update
Reply: 0

JPA saving null values when update

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:

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

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

// (getters and setters ok)

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

    private static final long serialVersionUID = 1L;

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

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

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

// getters and setters ok

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

    private Integer idNatureza;
    private String descricao;

    @OneToMany(mappedBy = "natureza", fetch = FetchType.LAZY)
    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()) {
    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