在 JPQL Query 中设置可选参数 [英] Set optional parameters in JPQL Query

查看:16
本文介绍了在 JPQL Query 中设置可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这个硬币列表,我想用这 3 个可选参数(货币、数量)过滤和年份)

如何将 JPQL 中的参数设置为可选?我不想做 9 个if else"来检查它是否为空

How can I set parameters in JPQL as optional? I dont want to do 9 "if else" for checking if its null

我得到了 filtradoMonedas (filterCoins) 函数,它使用 3 个可选参数过滤对象 Moneda(coin),但如果有一个空参数,它就不起作用.

I got the function filtradoMonedas (filterCoins) that filter the object Moneda(coin) using that 3 OPTIONAL parameters but its not working if there´s a null parameter.

如果不设置空参数,如果 cantidad 或 ano 是 "" 返回错误查询的异常,这只会很好地工作.只是想把它作为一个可选的.方法如下:

This just work well if dont set empty parameters, if cantidad or ano is "" returns exception of bad query. Just want it as an optional. Heres the method:

public List<Moneda> filtradoMonedas(Divisa divisa, BigDecimal cantidad, 
        BigDecimal ano){

    EntityManager em = getEntityManager();

    Query consulta = em.createQuery("SELECT m FROM Moneda m "
            + "WHERE m.divisa = :divisa "
            + "AND m.cantidad= :cantidad "
            + "AND m.ano = :ano");

    consulta.setParameter("divisa", divisa);
    consulta.setParameter("cantidad", cantidad);
    consulta.setParameter("ano", ano);

    List<Moneda> filtradoMonedas = (List<Moneda>) consulta.getResultList();
    // sincronizar los objetos devueltos con la base de datos
    for (Moneda m : filtradoMonedas) {
        em.refresh(m);
    }

    em.close();
    return filtradoMonedas;
}

推荐答案

在阅读 Ilya Dyoshin 的评论后,以及背后的聪明想法你应该认为不是参数是可选的,而是条件是可选的"我决定走自己的路,将 JPQL 与 @Query 注释结合使用,并创建一个运行良好的动态 SQL 查询.

After reading Ilya Dyoshin's comment, and the smart thinking behind "you should think that not parameters are optional but rather conditions are optional" I decided to go my own way by using JPQL with @Query annotation, and creating one dynamic SQL query which works beautifully.

关键是应用一些 SQL 逻辑,使条件成为可选的,而不是参数:

The key is to apply some SQL logic to make the conditions optional rather than the parameters:

    @Query("SELECT a " +
           "FROM amazing " +
           "WHERE (:filterSuperAwesome IS NULL " +
                        "OR a.filterSuperAwesome = :filterSuperAwesome)"); 

    List<FilterSuperAwesome> filterAwesomeORSuperAwesome(
                    @Param("filterSuperAwesome ") FilterSuperAwesome filterSuperAwesome);

注意这里 ☝️,我使用 OR 语句的原因是我的参数可以呈现两种形式,一个 FilterSuperAwesome 或 NULL 的实例.当为 NULL 时,条件始终为 True,就好像它不存在一样.

Note how here ☝️, I use an OR statement based on the fact that my parameter can present two forms, an instance of FilterSuperAwesome or NULL. When NULL, the condition is always True, as if it wasn't there.

这在 JHipster 项目的 JpaRepository 类中工作得很好.

This works just fine inside a JpaRepository class of a JHipster project.

这篇关于在 JPQL Query 中设置可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆