JPA Specification complex query

倾然丶 夕夏残阳落幕 提交于 2019-12-25 06:29:03

问题


I have below data :-

Product Reason Qty
Pepsi   IN     10
Pepsi   Out    2
Pepsi   In     15
Pepsi   Out    5 
Coke    IN     100
Coke    Out    20
Coke    In     35
Coke    Out    25

and from JPA Specification i want to execute below query something like below :-

select * from (
(select SUM(QTY) from stock where reason like 'IN') as INDATA -
(select SUM(QTY) from stock where reason like 'OUT') as OUTDATA

) as TBL;

result will be below :-

Product Qty
Pepsi   18
Coke    90

I am using JPA Specification for the first time and i dont no idea how to execute the query to get current stock from stock table.


回答1:


Assuming that you have an Entity, say Beverage, that is mapped to the above table Stock as :

@Entity
@Table(name="Stock")
class Beverage {
    public Beverage(String brand, String reason, int quantity) {
        this.brand = brand;
        this.reason = reason;
        this.quantity = quantity;
    }

    public Beverage() {}

    @Id
    @GeneratedValue
    Integer id;

    String brand;
    String reason;
    int quantity;
}

You can use case statement along with sum as below with JPQL:

Query query = entityManager.createQuery("select new map(b.brand as brand, sum(case b.reason when 'IN' then b.quantity else -b.quantity end) as quantity)  from Beverage b group by b.brand");
List<Map> list = query.getResultList();
for(Map m : list)
    System.out.println(m.get("brand") + "-" + m.get("quantity"));


来源:https://stackoverflow.com/questions/36347705/jpa-specification-complex-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!