Foreign key deletion

0

Help in logic. My question is:

I have a simple relationship between Launch and Person, where person_id is the foreign key in Launch

Class Model

@NotNull
@ManyToOne(optional = false)
@JoinColumn(name = "pessoa_id")
public Pessoa getPessoa() {
    return pessoa;
}

When I delete the Postings everything works correctly, but when I delete Person the system does not accept even when there are no data in the Launching table, I tried to do a logic to this and to no avail. The correct would be the message that it is not possible to exclude a Person because it is linked to the Release, but if there is no Release, I would have to exclude Person, and that does not happen.

Service Class

@Transactional
public void excluir(Pessoa pessoa) throws NegocioException {
    pessoa = this.pessoas.porId(pessoa.getId());

    if (lancamento.getPessoa().getNome().contains(pessoa.getNome())) {
        throw new NegocioException("Pessoa vinculada a um Lançamento.");
    } else {
        this.pessoas.remover(pessoa);
    }
}

Repository Class

public class Pessoas implements Serializable  {

private static final long serialVersionUID = 1L;

private EntityManager manager;

@Inject
public Pessoas(EntityManager manager) {
    this.manager = manager;
}

public void remover(Pessoa pessoa) {
    this.manager.remove(pessoa);
}

public Pessoa porId(Long id) {
    return manager.find(Pessoa.class, id);
}

}

XHTML

<p:commandButton icon="ui-icon-trash" title="Excluir" process="@this" 
   update="@form"
   action="#{consultaPessoasBean.excluir}">
   <f:setPropertyActionListener value="#{pessoa}" 
        target="#{consultaPessoasBean.pessoaSelecionada}" />
</p:commandButton>
    
asked by anonymous 12.01.2018 / 18:31

3 answers

0

I was able to resolve it as follows:

In the repository class, include the flush, as below:

public void remover(Pessoa pessoa) {
    this.manager.remove(pessoa);
    this.manager.flush();
}
    
02.02.2018 / 17:52
0
@NotNull
@ManyToOne(optional = false,cascade=CascadeType.REMOVE)   
@JoinColumn(name = "pessoa_id")
public Pessoa getPessoa() {
    return pessoa;
}
    
12.01.2018 / 20:17
0

Good afternoon.

When creating the table you need to add the ON DELETE CASCADE options.

And in your remove method you need to validate if there is any related record, otherwise execute the method.

See reference below.

link

    
01.02.2018 / 17:34