问题
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