Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

jpa - Counting Null values in JPQL

i want to count null values in JPQL but count (case when "column" is null then.. end) doesn't work it work only on MYSQL ,i don't want to use count(*) what is the solution ??

String jpql ="select c.commande.user.login ,count(CASE WHEN c.commande.commandeTms is Null THEN 1 else 0 END) AS count1   from Designation c GROUP BY c.commande.user.login";

here my database

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here you go : I have used CriteriaBuilder to count them ... as a result, you get a List of Tuple containing the user login and count elements ... you may want to change names and "count cases" according to your needs :

public List<Tuple> test() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
    Root<Designation> designation = cq.from(Designation.class);

    Join<Designation, Commande> commande = designation.join("commande");
    Join<Commande, User> user = commande.join("user");

    Expression expr = commande.get("commandeTms");

    cq.multiselect(user.get("login").alias("login"), 
            cb.sum(cb.<Long>selectCase().when(expr.isNotNull(), 1L).otherwise(0L)).alias("NotNull"),
            cb.sum(cb.<Long>selectCase().when(expr.isNull(), 1L).otherwise(0L)).alias("Null"));
    cq.groupBy(user.get("login"));

    Query query = entityManager.createQuery(cq);
    return query.getResultList();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...