1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

springでのクエリビルド

Last updated at Posted at 2025-03-31

概要

今回はjava, springboot環境にてクエリビルダーを実装したので、
ほとんどそのまま共有します。

開発環境想定や、Entityについて

※DBとの連携はJPAを使用しています。

Entityとしては、MainTabaleとSubTableの2つを用意します。
SubTableのフィールドには、MainTable_idを持っています。

その後、DTOに取得した情報を格納してreturnするという流れになります。

では、早速

service.java
@Service
public class Service {
    // クエリビルダーの準備
    @PersistenceContext
    private EntityManager entityManager;

    public List<SampleDto> queryBuilder() {
        // ビルド準備
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<SampleDto> cq = cb.createQuery(SampleDto.class);
        Root<MainTable> mainTable = cq.from(MainTable.class);

        // ここからクエリビルド
        // LEFT JOIN
        Join<MainTable, SubTable> subTable = mainTable.join("subTable", JoinType.LEFT);
        
        // WHERE
        List<Predicate> conditions = new ArrayList<>();
        conditions.add(cb.isNull(mainTable.get("enabled")));
        conditions.add(cb.equal(subTable.get("point"), 1));
        
        // COUNT
        Expression<Long> originalDate= cb.count(mainTable.get("id"));

        // ORDER BY, ORDER BY, SELECT
        // DTOクラスを作成して、MainTableとoriginalDateを紐づけてデータを扱う
        cq.select(cb.construct(SampleDto.class, MainTable, originalDate))
        .where(conditions.toArray(new Predicate[0]))
        .groupBy(mainTable.get("id"))
        .orderBy(cb.desc(originalDate));

        // SQL実行
        return entityManager.createQuery(cq).getResultList();
    }
}

補足

今回はDTOを作成していますが、必要ない場合は作成せずにEntityの取得だけで問題ありません。
1件のデータだけを取得したい場合は、SQL実行の部分を下記のように変更してください。

SQL実行.java
return entityManager.createQuery(cq).getResultList();
return entityManager.createQuery(cq).getSingleResult();

他に質問あればコメントお願いします!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?