Foreign key exclusion

Asked

Viewed 500 times

0

It helps the logic. My question is this::

I have a simple relationship between Lancamento and Pessoa, where people is the foreign key in Lancamento

Model Class

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

When I delete Launches everything works correctly, however when I delete Person the system does not accept even when there are no data in the Lancamento table, I tried to make a logic for such and unsuccessful. The correct message would be that it is not possible to exclude a Person because it is linked to Lancamento, but if there is no Lancamento, I would have to exclude Person, and this 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>

3 answers

0

@NotNull
@ManyToOne(optional = false,cascade=CascadeType.REMOVE)   
@JoinColumn(name = "pessoa_id")
public Pessoa getPessoa() {
    return pessoa;
}
  • Which error is shown with you try to delete?

  • This solution did not work. Caused by: com.mysql.jdbc.exceptions.jdbc4.Mysqlintegrityconstraintviolationexception: Cannot delete or update a Parent Row: a Foreign key strainCont fails (financeiro.lancamento, CONSTRAINT FK_ax5wcm3fcn1xss5lkmlbt68pu FOREIGN KEY (pessoa_id) REFERENCES pessoa (id))

  • Change person relationship to release.

  • No friend, this is not the solution.

0

0


I was able to solve it this way:

In the Repository class, includes the flush, as below:

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

Browser other questions tagged

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