Monday 16 November 2015

Upgrading Querydsl 3 to 4

Querydsl is for some time now my weapon of choice when it comes to writing typesafe JPA queries. Main advantage is great readibility of code comparing to standard JPA Criteria API. Sometimes I also use Querydsl SQL module when JPA is not avaliable or JPA entity mapping is too poor (sadly common case) that can't be used in complex queries.

Anyway, today I've been upgrading from Querydsl 3.6.x to latest 4.0.x and I've met numerous API changes. Unfortunately I did not find any migration instructions so here comes my notes. Might be useful to someone.

Simple query

Before:
QEntity qEntity = QEntity.entity;
List<Entity> list = new JPAQuery(emDomain).from(qEntity).list(qEntity);
After:
QEntity qEntity = QEntity.entity;
List<Entity> list = new JPAQuery<Entity>(emDomain).from(qEntity).fetch();

SearchResults -> QueryResults

Before:
SearchResults<Tuple> results = query.listResults(qEntity.id, qEntity.name);
After:
QueryResults<Tuple> results = query.select(qEntity.id, qEntity.name).fetchResults();

Join fetch

Before:
query.leftJoin(qEntity.approvedCreatives).fetch();
After:
query.leftJoin(qEntity.approvedCreatives).fetchJoin();

Single result

Before:
Tuple tuple = query.singleResult(qEntity.id, qEntity.name);
After:
Tuple tuple = query.select(qEntity.id, qEntity.name).fetchOne();

Subqueries

Before:
JPAQuery query = new JPAQuery(emDomain);
ListSubQuery<Long> subQuery = new JPASubQuery().from(qCampaing).where(qCampaing.id.eq(campaingId)).join(qCampaing.segments, qSegment).list(qSegment.id);
query.from(qSegment).where(qSegment.id.in(subQuery));
After:
JPAQuery<Segment> query = new JPAQuery(emDomain);
JPQLQuery<Long> subQuery = JPAExpressions.selectFrom(qCampaing).where(qCampaing.id.eq(campaingId)).join(qCampaing.segments, qSegment).select(qSegment.id);
query.from(qSegment).where(qSegment.id.in(subQuery));

Happy typesafe Querdsling!