Automatically setting child's parent using Hibernate


#1

I have two classes: Pessoa and Telefone (person and phone)

@OneToMany(mappedBy="pessoa",cascade = CascadeType.ALL)
    private List<Telefone> telefones = new ArrayList<Telefone>();

and on Telefone side:

 @ManyToOne
 @JoinColumn(name = "pessoa_id",referencedColumnName = "id",foreignKey = @ForeignKey(name="Fk_TelefonePessoa"))
    private Pessoa pessoa;

If I add a phone by directly calling the “add()” method of the List, the phone object will stay with the .pessoa property null, then I have to set it before saving.

If i dont, when hibernate save that objects, the foreign key will be null.

   Pessoa pessoa = new Pessoa();
         pessoa.setNome("Teste de inclusao de pessoa 2");
         pessoa.getTelefones().add(new Telefone("15", "12345123"));
         pessoa.getTelefones().add(new Telefone("15", "123123232"));   
         pessoa.getTelefones().add(new Telefone( "15", "3232233232"));
         pessoa.setTipo(Pessoa.TipoPessoa.F);
         pessoa.setSexo(Pessoa.Sexo.M);
         DAO.salvar(pessoa);

Is there a way to make hibernate set this property for me automatically or it is not possible?

Regards


#2

You could use the hibernate.enhancer.enableAssociationManagement Bytecode Enhancement option, but I don’t recommend it.

Better to add two utility methods: addChild and removeChild to synchronize both ends of the association. For more detail, check out this article.


#3

Why is hibernate.enhancer.enableAssociationManagement not recommended?


#4

Because it only applies to the parent side, not to changes done on the child side.


#5

Thank you for the answer!