Search in associative table

Asked

Viewed 408 times

3

How can I do an associative table search ? There are two entities, Pessoa and Time. Where I came from the Personal association_time that has id_person and id_time.

My goal is to list all the id_time of a certain id_person

Following error:

HTTP Status 500 - org.hibernate.hql.ast.QuerySyntaxException: pessoa_time is not mapped [select t from pessoa_time u where u.id_pessoa = :pPessoa]

Personal:

public List<Time> listarmeustimes(Pessoa pessoa) {

        Pessoa resultado = new Pessoa();

        String consulta = "select t from pessoa_time u where u.id_pessoa = :pPessoa";
        Query query = getEm().createQuery(consulta);

        query.setParameter("pPessoa", pessoa.getNomeUsuario());

        List<Time> meustimes = query.getResultList();
        for (Time time : meustimes) {
            System.out.println(time.getNome());

        }
        return meustimes;
    }

Personal:

public void listarmeustimes(){
        getDao().listarmeustimes(getPessoa());  
    }

Pessoa Model:

@ManyToMany(mappedBy="listaPessoas")
private List<Time> listaTimes; 

Time Model:

@ManyToMany
 @JoinTable(name="Pessoa_Time",joinColumns={@JoinColumn(name="id_time")}, 
 inverseJoinColumns={@JoinColumn(name="id_pessoa")})
private List<Pessoa> listaPessoas;

1 answer

3


There is an error in your query.

Note here where u.id_pessoa = :pPessoa". The query expects to receive in the parameter :pPessoa the id of Person, but you’re passing is the name here query.setParameter("pPessoa", pessoa.getNomeUsuario());

The right thing should be query.setParameter("pPessoa", pessoa.getId());

But since what you really want is to list all the teams that are related to a person, then change your query to look like this String consulta = "from Time t join t.pessoas p where p.id = :pPessoa";

And in the setParameter pass the id instead of name, thus: query.setParameter("pPessoa", pessoa.getId());

  • Submitted the following error: HTTP Status 500 - org.hibernate.hql.ast.Querysyntaxexception: Unexpected token: * near line 1, column 8 [select * from pessoa_time]

  • @Rafaelaugusto I made a modification in consultation. I edited the answer. See if it works.

Browser other questions tagged

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