简体   繁体   English

复杂条件查询:使用JPA代替NativeQuery

[英]Complex criteria query: using JPA instead of NativeQuery

I've in my Java EE project this NativeQuery for MySQL: 我在我的Java EE项目中使用了MySQL的NativeQuery:

SELECT 
    *,
    ROUND((price_2-price_1)*100/price_1,2) AS varprice_1,
    ROUND((quantity_2-quantity_1)*100/quantity_1,2) AS varcant_1,
    ROUND((price_3-price_2)*100/price_2,2) AS varprice_2,
    ROUND((quantity_3-quantity_2)*100/quantity_2,2) AS varcant_2,
    1 
FROM ( 
    SELECT   
        c.id_customer AS id_customer, 
        c.name AS customer,   
        r.id_rep AS id_rep, 
        r.descr AS rep,   
        a.id_article AS id_article, 
        a.name AS article, 
        ROUND(SUM(if(docdate BETWEEN '2013-06-30' AND '2013-12-30',quantity ,0)),2) AS quantity_1,
        ROUND(SUM(if(docdate BETWEEN '2013-06-30' AND '2013-12-30',net_price,0)),2) AS price_1,
        ROUND(SUM(if(docdate BETWEEN '2012-06-30' AND '2012-12-30',quantity ,0)),2) AS quantity_2,
        ROUND(SUM(if(docdate BETWEEN '2012-06-30' AND '2012-12-30',net_price,0)),2) AS price_2,
        ROUND(SUM(if(docdate BETWEEN '2011-06-30' AND '2011-12-30',quantity ,0)),2) AS quantity_3,
        ROUND(SUM(if(docdate BETWEEN '2011-06-30' AND '2011-12-30',net_price,0)),2) AS price_3, 
        1 
    FROM documento d 
    RIGHT JOIN pedido_cabezal pc ON d.id_documento = pc.id_documento 
    LEFT JOIN pedido_linea pl ON pc.id_documento = pl.id_documento 
    LEFT JOIN article a ON pl.id_article = a.id_article 
    LEFT JOIN customer c ON pc.id_customer=c.id_customer 
    LEFT JOIN rep r ON c.id_rep=r.id_rep 
    WHERE ( 
        (docdate BETWEEN '2013-06-30' AND '2013-12-30') OR
        (docdate BETWEEN '2012-06-30' AND '2012-12-30') OR  
        (docdate BETWEEN '2011-06-30' AND '2012-12-30')  
        )  
    GROUP BY a.id_article  
) subq 
ORDER BY price_1 DESC

this is a dinamically generated query, depending on user input. 这是一个动态生成的查询,具体取决于用户输入。 I don't like using native queries so I'm using it for now and I'm planning to change it with a criteria query, but I need help: I cannot figure out how this kind of queries can be substituted by a criteria query. 我不喜欢使用本机查询,所以我现在正在使用它,并且打算使用标准查询来更改它,但是我需要帮助:我无法弄清楚如何用标准查询代替这种查询。 Is there a way or it's ok to use native queries in cases like this and I should stop worrying about it? 有没有办法在这种情况下使用本机查询,我应该不再担心它了?

Thank you 谢谢

Unfortunately you cannot use JPA subquery results in the from clause. 不幸的是,您不能在from子句中使用JPA子查询结果。 Neither in Criteria queries, nor in JPQL ones. 在条件查询和JPQL查询中都没有。 This looks like the biggest problem in translating your query into a JPA one. 这似乎是将查询转换为JPA的最大问题。

Secondarily, there is no Round function, either. 其次,也没有Round函数。 But it shouldn't be a problem to overcome this by using CriteriaBuilder#selectCase() 但是使用CriteriaBuilder#selectCase()克服这个问题应该不是问题

See also: 也可以看看:

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

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