Show in Autocomplete the attribute of a specific user

Asked

Viewed 190 times

0

I’m trying to make an autocomplete to show only the names of registered teachers. I believe the problem is in the search for the attribute, since to get the attribute I have to do the following way: GestaoMonografiasBean -> Monografia -> Professor -> Usuario -> name.

It may be that I’m doing a crazy gambit, but excuse my lack of knowledge, I’m new to this world.

Another issue is Convert. The problem may be in it too, since I’m sending it to the class ProfessorConverter an object Usuário, for it to take the name attribute, to be used in the autocomplete.

The mistake I make when I type some letter to get the name of the teacher is this below, I even understood that he can not catch the attribute name in class Professor, but in fact he pass by the class Professor and take the class Usuario the name referring to the teacher. I don’t know if I’m doing it right.

nov 19, 2017 11:04:47 pm com.sun.faces.lifecycle.Applyrequestvaluesphase execute ADVERTÊNCIA: /paginas/GestaoMonografias.xhtml @125,58 completeMethod="#{gestaoMonografiasBean.completarProfessor}": java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [nome] on this ManagedType [com.daniel.monografia.model.Professor] javax.el.ELException: /paginas/GestaoMonografias.xhtml @125,58 completeMethod="#{gestaoMonografiasBean.completarProfessor}": java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [nome] on this ManagedType [com.daniel.monografia.model.Professor] at com.sun.faces.facelets.el.TagMethodExpression.invoke(Tagmethodexpression.java:111) at org.primefaces.Component.autocomplete.Autocomplete.broadcast(Autocomplete.java:480) at javax.faces.Component.UIViewRoot.broadcastEvents(Uiviewroot.java:790) at javax.faces.Component.UIViewRoot.processDecodes(Uiviewroot.java:931) at com.sun.faces.lifecycle.Applyrequestvaluesphase.execute(Applyrequestvaluesphase.java:78) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.Lifecycleimpl.execute(Lifecycleimpl.java:198) at javax.faces.webapp.FacesServlet.service(Facesservlet.java:658) at org.apache.Catalina.core.Applicationfilterchain.internalDoFilter(Applicationfilterchain.java:231) at org.apache.Catalina.core.Applicationfilterchain.doFilter(Applicationfilterchain.java:166) at org.apache.Tomcat.websocket.server.WsFilter.doFilter(Wsfilter.java:52) at org.apache.Catalina.core.Applicationfilterchain.internalDoFilter(Applicationfilterchain.java:193) at org.apache.Catalina.core.Applicationfilterchain.doFilter(Applicationfilterchain.java:166) at org.apache.Catalina.core.Standardwrappervalve.invoke(Standardwrappervalve.java:198) at org.apache.Catalina.core.Standardcontextvalve.invoke(Standardcontextvalve.java:96) at org.apache.Catalina.authenticator.Authenticatorbase.invoke(Authenticatorbase.java:478) at org.apache.Catalina.core.Standardhostvalve.invoke(Standardhostvalve.java:140) at org.apache.Catalina.valves.Errorreportvalve.invoke(Errorreportvalve.java:80) at org.apache.Catalina.valves.Abstractaccesslogvalve.invoke(Abstractaccesslogvalve.java:624) at org.apache.Catalina.core.Standardenginevalve.invoke(Standardenginevalve.java:87) at org.apache.Catalina.connector.Coyoteadapter.service(Coyoteadapter.java:342) at org.apache.Coyote.http11.Http11processor.service(Http11processor.java:799) at org.apache.Coyote.AbstractProcessorLight.process(Abstractprocessorlight.java:66) at org.apache.Coyote.Abstractprotocol$Connectionhandler.process(Abstractprotocol.java:861) at org.apache.Tomcat.util.net.Nioendpoint$Socketprocessor.doRun(Nioendpoint.java:1455) at org.apache.Tomcat.util.net.SocketProcessorBase.run(Socketprocessorbase.java:49) at java.util.Concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.Concurrent.Threadpoolexecutor$Worker.run(Unknown Source) at org.apache.Tomcat.util.threads.Taskthread$Wrappingrunnable.run(Taskthread.java:61) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.Illegalargumentexception: Unable to locate Attribute with the Given name [name] on this Managedtype [com.daniel.monografia.model.Professor] at org.hibernate.metamodel.internal.Abstractmanagedtype.checkNotNull(Abstractmanagedtype.java:128) at org.hibernate.metamodel.internal.Abstractmanagedtype.getattribute(Abstractmanagedtype.java:113) at org.hibernate.query.criteria.Internal.path.Abstractfromimpl.locateAttributeInternal(Abstractfromimpl.java:116) at org.hibernate.query.criteria.Internal.path.Abstractpathimpl.locateAttribute(Abstractpathimpl.java:204) at org.hibernate.query.criteria.Internal.path.Abstractpathimpl.get(Abstractpathimpl.java:177) at com.daniel.monografia.repository.Professors.search(Professors.java:36) at com.daniel.monografia.controller.Gestaomonografiasbean.completeProfessor(Gestaomonografiasbean.java:94) at sun.reflect.Nativemethodaccessorimpl.invoke0(Native Method) at sun.reflect.Nativemethodaccessorimpl.invoke(Unknown Source) at sun.reflect.Delegatingmethodaccessorimpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.el.parser.Astvalue.invoke(Astvalue.java:247) at org.apache.el.MethodExpressionImpl.invoke(Methodexpressionimpl.java:267) at org.jboss.Weld.util.el.ForwardingMethodExpression.invoke(Forwardingmethodexpression.java:40) at org.jboss.Weld.el.Weldmethodexpression.invoke(Weldmethodexpression.java:50) at com.sun.faces.facelets.el.TagMethodExpression.invoke(Tagmethodexpression.java:105) ... 29 more

nov 19, 2017 11:04:47 pm com.sun.faces.context.Ajaxexceptionhandlerimpl handlePartialResponseError GRAVE: java.lang.Illegalargumentexception: Unable to locate Attribute with the Given name [name] on this Managedtype [com.daniel.monografia.model.Professor] at org.hibernate.metamodel.internal.Abstractmanagedtype.checkNotNull(Abstractmanagedtype.java:128) at org.hibernate.metamodel.internal.Abstractmanagedtype.getattribute(Abstractmanagedtype.java:113) at org.hibernate.query.criteria.Internal.path.Abstractfromimpl.locateAttributeInternal(Abstractfromimpl.java:116) at org.hibernate.query.criteria.Internal.path.Abstractpathimpl.locateAttribute(Abstractpathimpl.java:204) at org.hibernate.query.criteria.Internal.path.Abstractpathimpl.get(Abstractpathimpl.java:177) at com.daniel.monografia.repository.Professors.search(Professors.java:36) at com.daniel.monografia.controller.Gestaomonografiasbean.completeProfessor(Gestaomonografiasbean.java:94) at sun.reflect.Nativemethodaccessorimpl.invoke0(Native Method) at sun.reflect.Nativemethodaccessorimpl.invoke(Unknown Source) at sun.reflect.Delegatingmethodaccessorimpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.el.parser.Astvalue.invoke(Astvalue.java:247) at org.apache.el.MethodExpressionImpl.invoke(Methodexpressionimpl.java:267) at org.jboss.Weld.util.el.ForwardingMethodExpression.invoke(Forwardingmethodexpression.java:40) at org.jboss.Weld.el.Weldmethodexpression.invoke(Weldmethodexpression.java:50) at com.sun.faces.facelets.el.TagMethodExpression.invoke(Tagmethodexpression.java:105))

My self mplete

<p:outputLabel value="Orientador: " for="orientador" />
                <p:autoComplete id="orientador" size="80" 
                    value="#
 {gestaoMonografiasBean.monografia.professor.usuario}" 
                    completeMethod="#
 {gestaoMonografiasBean.completarProfessor}" 
                    converter="#{gestaoMonografiasBean.professorConverter}"
                    var="usuario"
                    itemLabel="#{usuario.nome}" itemValue="#{usuario}"/>

ProfessorConverter, where I think the problem might be, because I’m sending an object Usuário inside an object Professor, I think I’m talking shit, you correct me.

package com.daniel.monografia.controller;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import com.daniel.monografia.model.Professor;
import com.daniel.monografia.model.Usuario;

public class ProfessorConverter implements Converter{

    private List<Professor> listaProfessores;

    public ProfessorConverter(List<Professor> listaProfessores) {
        this.listaProfessores = listaProfessores;
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        System.out.println("NOME: " + value);
        if(value == null){
            return null;    
        }

        Long id = Long.valueOf(value);

        for(Professor professor: listaProfessores){
            if(id.equals(professor.getId())){
                return professor;
            }
        }

        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if(value == null){
            return null;
        }

        Professor professor = (Professor) value;

        return professor.getId().toString();
    }

}

The method completarProfessor within the GestaoMonografiasBean, by that bean that I intend to include the monograph with all the data

public List<Professor> completarProfessor(String termo) {
     List<Professor> listaProfessores = professores.pesquisar(termo);

    professorConverter = new ProfessorConverter(listaProfessores);

    return listaProfessores;
}

And after calling the method completarProfessor he will call the method pesquisar that is in my repository Professores, where it will list by name when I insert into the field that calls the autocomplete

package com.daniel.monografia.repository;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.daniel.monografia.model.Professor;

public class Professores implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private EntityManager manager;

    public Professores(){

    }

    public Professores(EntityManager manager){
        this.manager = manager;
    }

    public List<Professor> pesquisar(String nome){
        CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();

        CriteriaQuery<Professor> criteriaQuery = criteriaBuilder.createQuery(Professor.class);
        Root<Professor> root = criteriaQuery.from(Professor.class);
        criteriaQuery.select(root);
        criteriaQuery.where(criteriaBuilder.like(root.get("nome"),nome + '%'));

        TypedQuery<Professor> query = manager.createQuery(criteriaQuery);

        return query.getResultList();
    }
} 

Professor.

package com.daniel.monografia.model;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "professor")
public class Professor implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "usuario_id", nullable = false)
    private Usuario usuario;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Professor other = (Professor) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Professor [id=" + id + "]";
    }

}

Java user.

package com.daniel.monografia.model;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name="usuario")
public class Usuario implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotEmpty
    @Column(nullable = false, length = 40)
    private String nome;

    @NotEmpty
    @Email
    @Column(nullable = false, length = 40)
    private String email;

    @NotNull
    @Column(nullable = false, length = 8)
    private Long matricula;

    @NotEmpty
    @Column(nullable = false, length = 8)
    private String senha;

    @Column(name = "ultimo_acessso")
    @Temporal(TemporalType.DATE)
    private Date ultimoAcesso;

    @Column(nullable = false)
    private Character tipo;

    //Campos para usar no envio de email
    @Transient
    private String usuarioEmail = "[email protected]";
    @Transient
    private String senhaEmail = "monografia123";
    @Transient
    private String assunto;
    @Transient
    private String mensagem;

    @Transient
    private Professor professor;
    @Transient
    private List <Aluno> aluno;

    public Usuario() {
        super();

    }

    public Usuario(Long matricula, String senha) {
        super();
        this.matricula = matricula;
        this.senha = senha;

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public Date getUltimoAcesso() {
        return ultimoAcesso;
    }

    public void setUltimoAcesso(Date ultimoAcesso) {
        this.ultimoAcesso = ultimoAcesso;
    }

    public Long getMatricula() {
        return matricula;
    }

    public void setMatricula(Long matricula) {
        this.matricula = matricula;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getUsuarioEmail() {
        return usuarioEmail;
    }

    public void setUsuarioEmail(String usuarioEmail) {
        this.usuarioEmail = usuarioEmail;
    }

    public String getSenhaEmail() {
        return senhaEmail;
    }

    public void setSenhaEmail(String senhaEmail) {
        this.senhaEmail = senhaEmail;
    }

    public String getAssunto() {
        return assunto;
    }

    public void setAssunto(String assunto) {
        this.assunto = assunto;
    }

    public String getMensagem() {
        return mensagem;
    }

    public void setMensagem(String mensagem) {
        this.mensagem = mensagem;
    }

    public Character getTipo() {
        return tipo;
    }

    public void setTipo(Character tipo) {
        this.tipo = tipo;
    }

    public Professor getProfessor() {
        return professor;
    }

    public void setProfessor(Professor professor) {
        this.professor = professor;
    }

    public List<Aluno> getAluno() {
        return aluno;
    }

    public void setAluno(List<Aluno> aluno) {
        this.aluno = aluno;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Usuario other = (Usuario) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Usuario [id=" + id + "]";
    }



}

UPDATING

I managed to do the autocomplete to fetch all the usuários, but I only want the professores . Someone has an idea or a hint, because like class Professor inherits the attributes of Usuário, hence the attribute nome is in Usuário

My autocomplete was like this after this modification

<p:outputLabel value="Orientador: " for="orientador" />
                <p:autoComplete id="orientador" size="80" 
                    value="#{gestaoUsuariosBean.usuario.professor.usuario}" 
                    completeMethod="#{gestaoUsuariosBean.completarUsuario}" 
                    converter="#{gestaoUsuariosBean.usuarioConverter}"
                    var="usuario"
                    itemLabel="#{usuario.nome}" itemValue="#{usuario}"/>
  • I don’t get the ending, you just want the teachers and what you’re exhibiting isn’t right ?

  • Blz Douglas! It shows the names of all the users, but I want you to show only the names of the teachers. From what I researched I think the problem is in the method search in the bank, because it is searching all the names of users, I think I should make some kind of filter to search only the names of teachers, the problem is to know how to do this... I think I should make a Union with the Users and Teachers classes.

  • Is bringing data from some other class you inherit from User ?

  • Yes, it brings the name attribute of all classes that inherit from User. But I don’t do User Xtended in Teacher, I’m using.

  • Post your class Teacher please.

  • User pole also

  • Thanks for the help Douglas. I’ve edited and posted the classes

Show 2 more comments

1 answer

1

Analyzing your code, it’s as follows:

  • Your completeMethod is wrong because it triggers gestaoUsuariosBean.completarUsuario when it should trigger completarProfessor. Soon it will bring users.

  • Another thing is that you can enjoy object orientation (Study the subject). I say this because Teacher can and should inherit User. Of course I don’t know your project in depth but from what I could abstract it is correct.

Change your completeMethod="#{gestaoUsuariosBean.completarUsuario}" for completeMethod="#{GestaoMonografiasBean.completarProfessor()}"

  • I will follow your tips and try to implement something, put here the result

  • A doubt. Since I’m using Hibernate for mapping and it uses composition to relate tables, wouldn’t it be better to use composition rather than inheritance? I may be talking nonsense I don’t know...

Browser other questions tagged

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