简体   繁体   English

休眠动态参数查询

[英]Hibernate dynamic parameters query

I have a query that need to use "dynamic" parameters set. 我有一个查询,需要使用“动态”参数集。 But coundn´t realize how to do it, i tried to not add the where string but it gives me erros because the parameter is seted. 但是由于没有意识到该怎么做,我尝试不添加where字符串,但是由于设置了参数,它给了我错误信息。

Any tips? 有小费吗?

String queryS = "select object(c) from "
                           + entityClassName + " as c " +
                            "where 1 = 1" ;

            if(codigoPaciente.compareTo("") != 0)
            {
                queryS += " and c.CodigoDoPaciente =:paciente";
            }
            if(codServicoPrincipal.compareTo("") != 0)
                queryS += " and c.codigoServicoPrincipal =:servico";
            if(data != null)
                queryS += " and c.codigoServicoPrincipal =:data";
            if(TipoServico.compareTo("") != 0)
                queryS += " and c.codigoServicoPrincipal =:tipoServico";


            Query query = em.createQuery(queryS);
            query.setParameter("paciente", codigoPaciente);
            query.setParameter("codigoServicoPrincipal", codServicoPrincipal);
            query.setParameter("data", data);
            query.setParameter("tipoServico", TipoServico);


            return query.getResultList();

Rather than doing a bunch of string concatenation to create a query, the criteria API could be used to construct the query in a more "safe" manner. 与其执行一堆字符串连接来创建查询,不如使用条件API来以更“安全”的方式构造查询。 Then you could add the condition and the value in a single conditional check. 然后,您可以在单个条件检查中添加条件和值。

You are not setting your parameters inside if conditions... Maybe set the parameter for each string you concatenate? 如果条件不存在,您不会在其中设置参数...也许要为每个连接的字符串设置参数?

if(codigoPaciente.compareTo("") != 0)
            {
                queryS += " and c.CodigoDoPaciente =:paciente";
            }

Query query = em.createQuery(queryS);

// etc etc...
if(codigoPaciente.compareTo("") != 0)
    query.setParameter("paciente", codigoPaciente);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM