Hibernate + Criteria: could not resolve Property

Asked

Viewed 232 times

0

I’m trying to search my bank when making the User registration.

Next, in my user registration have two Spinner(Company, Person) I would like to popular the person Spinner with only the people working in the selected company. But the logic that following me will not return me anything because the entity person does not have the company code. So how do I bring this filtered data?

I am using Hibernate + Criteria and my search code ta thus:

public class PessoaDAO extends GenericDAO<Pessoa>{
@SuppressWarnings({ "unchecked"})
public List<Pessoa> buscarPorEmpresa(Long empresaCodigo) {
    Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();
    try {
        Criteria c = sessao.createCriteria(Pessoa.class, "P");
        c.createAlias("usuario", "U");
        c.add(Restrictions.eq("P.codigo", "U.pessoa"));
        c.createAlias("empresa", "E");
        c.add(Restrictions.eq("U.empresa","E.codigo"));
        c.add(Restrictions.eq("E.codigo", empresaCodigo));

        List<Pessoa> pessoas = c.list();
        System.out.println("List: " + pessoas);
        return pessoas;
    } catch (RuntimeException erro) {
        throw erro;
    } finally {
        sessao.close();
    }
}

}

The mistake I get is this:

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
    at org.hibernate.type.descriptor.java.LongTypeDescriptor.unwrap(LongTypeDescrip
tor.java:36)
    at org.hibernate.type.descriptor.sql.BigIntTypeDescriptor$1.doBind(BigIntTypeDe
scriptor.java:63)
    at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:90)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBas
icType.java:286)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBas
icType.java:281)
    at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1995)
    at org.hibernate.loader.Loader.bindParameterValues(Loader.java:1966)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1901)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1839)
    at org.hibernate.loader.Loader.doQuery(Loader.java:910)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.ja
va:355)
    at org.hibernate.loader.Loader.doList(Loader.java:2554)
    at org.hibernate.loader.Loader.doList(Loader.java:2540)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
    at org.hibernate.loader.Loader.list(Loader.java:2365)
    at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1718)
    at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
    at br.com.riverp.dao.PessoaDAO.buscarPorEmpresa(PessoaDAO.java:25)
    at br.com.riverp.Bean.UsuarioBean.popular(UsuarioBean.java:157)
    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 com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.jav
a:105)
    at org.primefaces.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(Aj
axBehaviorListenerImpl.java:54)
    at javax.faces.event.AjaxBehaviorEvent.processListener(AjaxBehaviorEvent.java:1
13)
    at javax.faces.component.behavior.BehaviorBase.broadcast(BehaviorBase.java:106)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:805)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhas
e.java:81)
    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(Application
FilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterCh
ain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Application
FilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterCh
ain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.ja
va:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.ja
va:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase
.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141
)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogVa
lve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java
:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Proce
ssor.java:1099)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(Abstrac
tProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.jav
a:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:
1476)
    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.ja
va:61)
    at java.lang.Thread.run(Unknown Source)

In some researches I saw that the problem could be with my annotations @Manytoone @Onetoone, so I’ll put my Domain classes too.

User

    @SuppressWarnings("serial")
@Entity
@Table(name = "usuario")
public class Usuario extends GenericDomain {
    @Column(length = 32, nullable = false)
    private String senha;

    @Transient
    private String senhaSemCriptografia;

    @Column(nullable = false)
    private Character tipo;

    @Column(nullable = false)
    private Boolean ativo;

    @OneToOne
    @JoinColumn(nullable = false)
    private Pessoa pessoa;

    @OneToOne
    @JoinColumn(nullable = true)
    private Empresa empresa;

    public String getSenha() {
        return senha;
    }

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

    public String getSenhaSemCriptografia() {
        return senhaSemCriptografia;
    }

    public void setSenhaSemCriptografia(String senhaSemCriptografia) {
        this.senhaSemCriptografia = senhaSemCriptografia;
    }

    public Character getTipo() {
        return tipo;
    }

    public Empresa getEmpresa() {
        return empresa;
    }

    public void setEmpresa(Empresa empresa) {
        this.empresa = empresa;
    }



    @Transient
    public String getTipoFormatado() {
        String tipoFormatado = null;

        if(tipo == 'A') {
            tipoFormatado = "Administrador";
        }else if(tipo == 'B') {
            tipoFormatado = "Balconista";
        }else if(tipo == 'G') {
            tipoFormatado = "Gerente";
        }
        return tipoFormatado;
    }

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

    public Boolean getAtivo() {
        return ativo;
    }

    public String getAtivoFormatado() {
        String ativoFormatado = "Não";
        if(ativo) {
            ativoFormatado = "Sim";
        }
        return ativoFormatado;
    }

    public void setAtivo(Boolean ativo) {
        this.ativo = ativo;
    }

    public Pessoa getPessoa() {
        return pessoa;
    }

    public void setPessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
    }
}

Enterprise

@SuppressWarnings("serial")
@Entity
public class Empresa extends GenericDomain{

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

    @Column(length = 100, nullable = false)
    private String endereco;

    @Column(length = 50, nullable = false)
    private String bairro;

    @Column(length = 13, nullable = false)
    private String telefone;

    @Column(length = 20, nullable = false)
    private String cnpj;

    @Column(length = 20, nullable = false)
    private String insc_estadual;

    @Column(length = 20, nullable = false)
    private String insc_municipal;

    @Column(length = 100, nullable = false)
    private String contato;

    @Column(length = 50, nullable = false)
    private String email;

    @Column(nullable = false)
    private Character tipo;

    @Column(nullable = false)
    private Boolean ativo;

    @OneToOne
    @JoinColumn(nullable = false)
    private Pessoa pessoa;

    @ManyToOne
    @JoinColumn(nullable = false)
    private Cidade cidade;

    public String getBairro() {
        return bairro;
    }

    public void setBairro(String bairro) {
        this.bairro = bairro;
    }

    public Cidade getCidade() {
        return cidade;
    }

    public void setCidade(Cidade cidade) {
        this.cidade = cidade;
    }

    public String getCnpj() {
        return cnpj;
    }

    public void setCnpj(String cnpj) {
        this.cnpj = cnpj;
    }

    public String getContato() {
        return contato;
    }

    public void setContato(String contato) {
        this.contato = contato;
    }

    public String getEmail() {
        return email;
    }

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

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getInsc_estadual() {
        return insc_estadual;
    }

    public void setInsc_estadual(String insc_estadual) {
        this.insc_estadual = insc_estadual;
    }

    public String getInsc_municipal() {
        return insc_municipal;
    }

    public void setInsc_municipal(String insc_municipal) {
        this.insc_municipal = insc_municipal;
    }

    public String getNome() {
        return nome;
    }

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

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public Character getTipo() {
        return tipo;
    }

    public Pessoa getPessoa() {
        return pessoa;
    }

    public void setPessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
    }

    @Transient
    public String getTipoFormatado() {
        String tipoFormatado = null;

        if(tipo == 'A') {
            tipoFormatado = "Administrador";
        }else if(tipo == 'B') {
            tipoFormatado = "Balconista";
        }else if(tipo == 'G') {
            tipoFormatado = "Gerente";
        }
        return tipoFormatado;
    }

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

    public Boolean getAtivo() {
        return ativo;
    }

    public String getAtivoFormatado() {
        String ativoFormatado = "Não";
        if(ativo) {
            ativoFormatado = "Sim";
        }
        return ativoFormatado;
    }

    public void setAtivo(Boolean ativo) {
        this.ativo = ativo;
    }
}

Person

@SuppressWarnings("serial")
@Entity
public class Pessoa extends GenericDomain {
    @Column(length = 50, nullable = false)
    private String nome;

    @Column(length = 14, nullable = false)
    private String cpf;

    @Column(length = 12, nullable = false)
    private String rg;

    @Column(length = 100, nullable = false)
    private String rua;

    @Column(nullable = false)
    private Short numero;

    @Column(length = 30, nullable = false)
    private String bairro;

    @Column(length = 10, nullable = false)
    private String cep;

    @Column(length = 10, nullable = false)
    private String complemento;

    @ManyToOne
    @JoinColumn(nullable = false)
    private Cidade cidade;

    @Column(length = 13, nullable = false)
    private String telefone;

    @Column(length = 14, nullable = false)
    private String celular;

    @Column(length = 100, nullable = false)
    private String email;

    @ManyToOne
    @JoinColumn(nullable = true)
    private Empresa empresa;

    @OneToOne
    @JoinColumn(nullable = true)
    private Usuario usuario;

    public String getNome() {
        return nome;
    }

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

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getRg() {
        return rg;
    }

    public void setRg(String rg) {
        this.rg = rg;
    }

    public Cidade getCidade() {
        return cidade;
    }

    public void setCidade(Cidade cidade) {
        this.cidade = cidade;
    }

    public String getRua() {
        return rua;
    }

    public void setRua(String rua) {
        this.rua = rua;
    }

    public Short getNumero() {
        return numero;
    }

    public void setNumero(Short numero) {
        this.numero = numero;
    }

    public String getBairro() {
        return bairro;
    }

    public void setBairro(String bairro) {
        this.bairro = bairro;
    }

    public String getCep() {
        return cep;
    }

    public void setCep(String cep) {
        this.cep = cep;
    }

    public String getComplemento() {
        return complemento;
    }

    public void setComplemento(String complemento) {
        this.complemento = complemento;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public String getCelular() {
        return celular;
    }

    public void setCelular(String celular) {
        this.celular = celular;
    }

    public String getEmail() {
        return email;
    }

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

    public Empresa getEmpresa() {
        return empresa;
    }

    public void setEmpresa(Empresa empresa) {
        this.empresa = empresa;
    }

    public Usuario getUsuario() {
        return usuario;
    }

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

If anyone can help me, I’ve been in this same problem for a few days. Thanks in advance.

  • Its entity Pessoa does not own the property usuario. Even you didn’t post the class code Pessoa, but there shouldn’t be the relationship in it

  • As said your entity person does not have the user mapping, add the mapping on it and it will work. Aliases are created from the entity used to create the criteria

  • This way of working with Hibernate is @Deprecated, I recommend changing the way you work, using Criteria Builder. Your error is in the user property of the Person class, this class you did not put in the question.

  • I updated with the Person class. All right, I’ll make the appropriate changes and I’ll be right back with a reply.

  • I updated the Person Class and the Error Above. I did the Mapping and now it is returning me that can not convert String to Long in this line of People List<Pessoa> resultado = c.list(); what might be?

  • Someone can help me?

Show 1 more comment

1 answer

0

Hi,

It seems that the company code is a String and you are getting a Long in the DAO method.

Try to change this line

c.add(Restrictions.eq("E.codigo", String.valueOf(companyCodigo)));

  • Not a certain guy. I already redid the code of the criteria but returns the same error, Java String cannot be converted to Long.

  • Try debugging the line below in the popular method of the Usuariobean class. It may be that some table information is failing to be converted to Long.

  • br.com.riverp.Bean.Usuariobean.popular(Usuariobean.java:157)

Browser other questions tagged

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