Slide 19
Slide 19 text
@Entity
@SqlResultSetMapping(
name = "ChartMapping",
columns = {
@ColumnResult(name = "label", type = String.class),
@ColumnResult(name = "cnt", type = Integer.class),
@ColumnResult(name = "chage", type = Integer.class)
})
@NamedNativeQueries(
@NamedNativeQuery(
name = "ChartQuery",
resultSetMapping = "ChartMapping",
query = ""
+ "WITH \n"
+ " previous_month AS\n"
+ " (SELECT p.track_id, count(*) as cnt, \n"
+ " dense_rank() over(order by count(*) desc) as
position \n"
+ " FROM plays p \n"
+ " WHERE trunc(p.played_on, 'DD') between date'2016-04-01'
and date'2016-04-30' GROUP BY p.track_id),\n"
+ " current_month AS\n"
+ " (SELECT p.track_id, count(*) as cnt, \n"
+ " dense_rank() over(order by count(*) desc) as
position \n"
+ " FROM plays p \n"
+ " WHERE trunc(p.played_on, 'DD') between date'2016-05-01'
and date'2016-05-31' GROUP BY p.track_id)\n"
+ "SELECT a.artist || ' - ' || t.name || ' (' || t.album || ')'
as label,\n"
+ " current_month.cnt, \n"
+ " previous_month.position - current_month.position as
change\n"
+ " FROM tracks t\n"
+ " JOIN artists a on a.id = t.artist_id\n"
+ " JOIN current_month current_month on current_month.track_id
= t.id\n"
+ " LEFT OUTER join previous_month on previous_month.track_id
= t.id\n"
+ " ORDER BY current_month.cnt desc, label asc"
)
)
public class PlayEntity {
public static void main(String... a) {
// Don't do this at home
EntityManager entityManager;
List results =
entityManager.createNamedQuery("ChartQuery").setMaxResults(20).getResultList();
results.stream().forEach((record) -> {
String label = (String) record[0];
Integer cnt = (Integer) record[1];
Integer change = (Integer) record[2];
});
}
}
ERNSTHAFT? SQL TRIFFT JAVA
this.create
.with(currentMonth)
.with(previousMonth)
.select(label,
currentMonth.field("cnt"),
previousMonth.field("position").minus(
currentMonth.field("position")
).as("change")
)
.from(TRACKS)
.join(ARTISTS).onKey()
.join(currentMonth)
.on(currentMonth.field("track_id", BigDecimal.class)
.eq(TRACKS.ID))
.leftOuterJoin(previousMonth)
.on(previousMonth.field("track_id", BigDecimal.class)
.eq(TRACKS.ID))
.orderBy(currentMonth.field("cnt").desc(), label.asc())
.limit(n)
.fetch()
.formatJSON(response.getOutputStream());