Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Hibernate动态参数查询_Java_Hibernate_Hsqldb - Fatal编程技术网

Java Hibernate动态参数查询

Java Hibernate动态参数查询,java,hibernate,hsqldb,Java,Hibernate,Hsqldb,我有一个需要使用“动态”参数集的查询。 但是我没有意识到怎么做,我试图不添加where字符串,但是它给了我错误,因为参数已经设置好了 有什么建议吗 String queryS = "select object(c) from " + entityClassName + " as c " + "where 1 = 1" ; if(codigoPaciente.co

我有一个需要使用“动态”参数集的查询。 但是我没有意识到怎么做,我试图不添加where字符串,但是它给了我错误,因为参数已经设置好了

有什么建议吗

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();

如果条件满足,则不能在内部设置参数。。。可以为连接的每个字符串设置参数吗

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

Query query = em.createQuery(queryS);

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

而不是做一堆字符串连接来创建一个查询,可以使用来以一种更“安全”的方式构造查询。然后您可以在一个条件检查中添加条件和值。

我同意joel的观点。我只部分同意自己的观点。使用criteriaAPI不是一件愉快的事。这可能是一件痛苦的事,但从长远来看,避免连接东西通常会有回报……我试图避免使用criteriaAPI……但这是唯一的方法,请参见QueryDSL。强类型动态查询,而无需使用CriteriaAPI。另一点,;如果删除WHERE子句并继续连接and,而不检查某些条件是否已连接,则条件将以and开头。这当然会给您带来一个错误。无法在生成查询的IF上设置参数,因为对象“query”不存在。显然,IF是在创建查询对象后使用的。此解决方案违反了DRY——我们如何定义查询并同时设置参数。