Hi,
I’m refactoring a project after remove enable_lazy_load_no_trans, and I’m following the best practices from Vlad’s blog.
I read the article: https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/ and it suggests that the best way is mapping an unidirectional association.
Actually in my project I have a lot of @OneToOne bidirectional and that’s what I’m doing (I’ll show only three of them):
public class Pessoa extends AppModel implements Serializable {
...
@OneToOne(cascade = CascadeType.ALL, mappedBy = "pessoa", orphanRemoval = true, fetch = FetchType.LAZY)
private PessoaFisica pessoaFisica;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "pessoa", orphanRemoval = true, fetch = FetchType.LAZY)
private PessoaJuridica pessoaJuridica;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "pessoa", orphanRemoval = true, fetch = FetchType.LAZY)
private Cliente cliente;
...
}
And all of them are like this:
public class PessoaFisica extends AppModel implements Serializable {
...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@MapsId
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "id")
private Pessoa pessoa;
...
}
So when I need to persist my Pessoa entity, I set them like this:
pessoa.setCliente(new Cliente());
pessoa.getCliente().setPessoa(pessoa);
getEntityManager().merge(pessoa);
One of my doubt is if I change to the way which article recommends I have to merge pessoa first and them merge pessoaJuridica, pessoaFisica, cliente and others? Like this:
...
getEntityManager().merge(pessoa);
pessoaJuridica.setPessoa(pessoa);
getEntityManager().merge(pessoaJuridica);
cliente.setPessoa(cliente);
getEntityManager().merge(cliente);
...
My second doubt is Pessoa could be PessoaJuridica or PessoaFisica but not both of them (Always one of them are null) and the others @OneToOne like Cliente are optional.
And all over the Controller I already have a lot of verifications that I actually doing, to check if a Pessoa entity is PessoaFisica or PessoaJudirica and if is Cliente or a different type of Pessoa.
What’s the best practice for this situation, I’m asking because if I always JOIN FETCH all of them, I’ll always making a new Query in my Database, is it a good a idea have a flag to define the type of them and do the JOIN FETCH only if it’s necessary?
Thanks in advance