Save only if not null

Asked

Viewed 82 times

1

How do I map with Hibernate @OneToOne and save only if the information has data in the related table?

Example:

public class ObservacaoPessoa {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer id;

    public Integer PessoaId;
    public String TextoObservacao;

}

public class Pessoas {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer id;

    public String Nome;

    public ObservacaoPessoa Obs;

}

I want to make Pessoas.Save but only record the Obs if any value has been reported.

  • I believe this treatment should be done at the time of saving the entity.

1 answer

1


I think what you want is the optional = true in the @OneToOne.

In addition, the inverse relationship (because it is bidirectional) can be done with the mappedBy:

public class ObservacaoPessoa {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @OneToOne(mappedBy = "obs")
    private Pessoa pessoa;

    private String textoObservacao;

}
public class Pessoas {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String nome;

    @OneToOne(optional = true, cascade = CascadeType.ALL)
    private ObservacaoPessoa obs;

}

Other things I notice is that the fields should be private. Do not use public fields, this is a bad programming practice.

To enter an entity, you would do something more or less like this:

EntityManager em = ...;
Pessoa p = ...;
ObservacaoPessoa obs = ...;
if (obs != null) {
    p.setObs(obs);
    obs.setPessoa(p);
}
em.persist(p);

Finally, to make bi-directional mapping work, you must manually set both sides of the relation as you would with any other two Java objects that need to be referenced cyclically.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.