Looking for an HQL builder (Hibernate Query Language)

后端 未结 11 908
-上瘾入骨i
-上瘾入骨i 2021-02-04 16:45

I\'m looking for a builder for HQL in Java. I want to get rid of things like:

StringBuilder builder = new StringBuilder()
    .append(\"select stock from \")
            


        
11条回答
  •  独厮守ぢ
    2021-02-04 17:24

    I wrote a GPL'd solution for OMERO which you could easily build suited to your situation.

    • Source: QueryBuilder.java
    • Test: QueryBuilderMockTest

    Usage:

    QueryBuilder qb = new QueryBuilder();
    qb.select("img");
    qb.from("Image", "img");
    qb.join("img.pixels", "pix", true, false);
    
    // Can't join anymore after this
    qb.where(); // First
    qb.append("(");
    qb.and("pt.details.creationTime > :time");
    qb.param("time", new Date());
    qb.append(")");
    qb.and("img.id in (:ids)");
    qb.paramList("ids", new HashSet());
    qb.order("img.id", true);
    qb.order("this.details.creationEvent.time", false);
    

    It functions as a state machine "select->from->join->where->order", etc. and keeps up with optional parameters. There were several queries which the Criteria API could not perform (see HHH-879), so in the end it was simpler to write this small class to wrap StringBuilder. (Note: there is a ticket HHH-2407 describing a Hibernate branch which should unify the two. After that, it would probably make sense to re-visit the Criteria API)

提交回复
热议问题