JPA Hibernate two entities with the same name, always saving in the same entity

Asked

Viewed 131 times

0

I have a jCombobox where all the entidades students. It happens to have two entities with the same name (two students Rodrigo Silva for example). Both are loaded on combo.

To the gravar the data in banco, no matter which one entidades listed with the same name I choose, is always recorded to the id lower (in this case the id 1). What I’m doing wrong, how can I fix this?

public T save(T t) throws Exception {
EntityManager em = getEm();
try {
    em.getTransaction().begin();
    if (t.getId() == null) {
        em.persist(t);

    } else {
        if (em.contains(t)) {
            if (em.find(t.getClass(), t.getId()) == null) {
                throw new Exception("Erro");
            }
        }
        t = em.merge(t);

    }
    em.getTransaction().commit();
} finally {
    em.close();
}
return t;

}

    ocorrencia.setAluno((Aluno) jCAluno.getSelectedItem());
    OcorrenciaDao oc = new OcorrenciaDao();
    oc.save(ocorrencia);

Method that populates the combo:

  public void loadComboAluno() {
    AutoCompleteDecorator.decorate(this.jCAluno);
    AlunoDao alunoDao = new AlunoDao();
    List<Aluno> listaAlunos = alunoDao.consultarAlunos();
    for (Aluno set : listaAlunos) {
        jCAluno.addItem(set);
    }
}

Consultation method:

   public List<Aluno> consultarAlunos() {
    EntityManager em = getEm();
    List<Aluno> listaAlunos;
    try {
        Query q = em.createNamedQuery("Aluno.findAll");
        listaAlunos = q.getResultList();
    } catch (Exception e) {
        listaAlunos = new ArrayList<>();

    } finally {
        em.close();

    }
    return listaAlunos;

}

Pupil Class:

    @Entity
@DynamicUpdate(value=true)
@NamedQueries({
    @NamedQuery(name = "Aluno.findAll", query = "SELECT c FROM Aluno c"),
    @NamedQuery(name = "Aluno.findByAlunoId", query = "SELECT c FROM Aluno c WHERE c.id = :id"),
    @NamedQuery(name = "Aluno.findByAlunoNome", query = "SELECT c FROM Aluno c WHERE c.nome = :nome")})
public class Aluno implements EntidadeBase, Serializable {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idAluno")
    private Integer id;
    @Column(name = "nomeAluno")
    private String nome;
  • How is your student class? How are you populating jcombobox with students?

  • 1

    What you call the method getId if t is generic?

  • @Renan if you have some kind of "contract" in the signature of this class that has this method, I think it works.

  • I added more code snippets to see if it helps to clarify.

  • After a while I realized that what happens is that the selectedItem changes to the first of the list, after the click, and so does the insert always for the same entity. Someone has had this problem?

No answers

Browser other questions tagged

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