Save only if it is not null

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 write Obs if some value has been entered.

    
asked by anonymous 16.02.2017 / 13:30

1 answer

1

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

In addition, the inverse relationship (since it is bidirectional) can be done with 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 are that the fields should be private. Do not use public fields, this is a bad programming practice.

To insert an entity, you would do something like this:

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

Finally, to make bidirectional mapping work, you should manually set the two sides of the relationship as you would any other two Java objects that need to be cyclically referenced.

    
16.02.2017 / 13:44