Build a Sales Analytics Dashboard in Java with Querier and Chart.js
Building analytics features in enterprise Java applications can become surprisingly complicated.
You start with a few reporting requirements:
- Show revenue over time.
- Identify the best-performing products.
- Understand the distribution of orders by status.
- Find the customers generating the most revenue.
Then things start getting messy.
SQL queries are scattered across repositories, aggregations are implemented differently across services, query parameters are manually managed, and frontend developers have to maintain JavaScript chart configurations for every report.
What if we could simplify that?
In this article, I'll demonstrate how to build a small but realistic Sales Analytics Service using Querier.
We'll use two modules:
- querier-core: Build type-safe SQL queries using Java method references, aggregations, joins, filtering, and more.
- querier-ui: Turn those queries into server-side HTML dashboards powered by Chart.js, without writing JavaScript.
We'll use Spring Boot and JdbcTemplate for database execution, but the interesting part is that Querier itself doesn't depend on either.
Let's build something!
1. What we're building
Our example is an analytics service for an application managing customers, products, and orders.
The service will expose a sales dashboard containing four charts:
- Daily revenue trend.
- Top products by revenue.
- Order distribution by status.
- Top 10 customers by revenue and average order value.
We'll also look at a window-function query to demonstrate how Querier can support more advanced analytical requirements.
The goal isn't just to display a few charts. It's to demonstrate how to keep analytical query definitions readable, reusable, and independent of the database execution mechanism.
2. Our domain model
We'll use three existing entity classes.
Product
@Table(name = "products") @Entity(name = "products") public class Product { @Id private Long id; private String name; private BigDecimal price; // Getters and setters } Customer
@Table(name = "customers") @Entity(name = "customers") public class Customer { @Id private Long id; private String name; private String email; // Getters and setters } Order
@Table(name = "orders") @Entity(name = "orders") public class Order { @Id private Long id; private Long customerId; private Long productId; private BigDecimal total; @Enumerated(EnumType.STRING) private OrderStatus status; private LocalDate createdAt; // Getters and setters } Our order status enum:
public enum OrderStatus { PENDING, PAID, SHIPPED, DELIVERED, CANCELLED } The complete classes include the appropriate JPA table and column annotations, including the explicit mappings for customer_id, product_id, and created_at.
Notice something important: we don't have @ManyToOne relationships between Order, Customer, and Product.
That's perfectly fine for this example.
Querier can build joins directly from entity getter references and their foreign-key columns. We don't need to introduce an ORM object graph just to construct analytical queries.
3. Add Querier to your project
For this tutorial, we'll use version 2.0.3.
Add the following dependency to your Maven project:
<dependency> <groupId>com.aytmatech</groupId> <artifactId>querier-ui</artifactId> <version>2.0.3</version> </dependency> That's it.
You don't need to declare querier-core separately because querier-ui already includes it as a transitive dependency.
If you're only interested in building SQL queries without dashboards, you can use querier-core independently:
<dependency> <groupId>com.aytmatech</groupId> <artifactId>querier-core</artifactId> <version>2.0.3</version> </dependency> Repository: https://github.com/AytmaTech/Querier
4. Understanding the architecture
Before writing queries, let's understand how the pieces fit together.
Querier separates query construction from query execution.
Java Entity Classes | v querier-core | v Select Object | v SQL + Parameters | v QueryRunner | v Database Layer | v Query Results | v querier-ui | v Chart.js HTML Dashboard The important part is QueryRunner.
Querier doesn't need to know whether your application uses Spring JDBC, plain JDBC, Hibernate, or another execution mechanism.
It builds the query and exposes SQL with its associated parameters. Your application decides how to execute it.
The UI module uses the same separation: it receives a QueryRunner, executes each dashboard query through it, and transforms the results into Chart.js-powered HTML.
This is particularly useful in enterprise applications where query construction shouldn't be coupled to a particular persistence implementation.
5. Build our analytical queries
Let's start writing some actual queries.
We'll use these imports throughout the examples:
import com.aytmatech.querier.Aggregate; import com.aytmatech.querier.Condition; import com.aytmatech.querier.OrderBy; import com.aytmatech.querier.Select; import com.aytmatech.querier.WindowFunction; import com.aytmatech.querier.dashboard.*; We'll also define a common filtering condition:
private Condition paidOrdersBetween( LocalDate from, LocalDate to) { return Condition.and( Condition.eq(Order::getStatus, OrderStatus.PAID.name()), Condition.between(Order::getCreatedAt, from, to) ); } This gives us a reusable business condition for paid orders within an inclusive date range.
Notice that we're using method references rather than manually writing column names. But, we need to carefully take care of enum mapping, in our case OrderStatus is mapped to String with @Enumerated(EnumType.STRING) which force us to use .name() method since Querier is not handling enum value mapping for now. If enum value kept without manual mapping, the ORM framework will try to do the mapping based on its defaults. For example, Hibernate will try to map the enum to integer, which corresponds to calling .ordinal().
Query 1: Daily revenue trend
The first requirement is straightforward:
How much revenue did we generate each day during the selected period?
We need:
- The order creation date.
- The sum of order totals.
- A date range.
- Only paid orders.
- Grouping by date.
- Chronological ordering.
Here's the query:
Select dailyRevenueQuery = Select.builder() .select(Order::getCreatedAt, "order_date") .select(Aggregate.sum(Order::getTotal).as("revenue")) .from(Order.class) .where(paidOrdersBetween(from, to)) .groupBy(Order::getCreatedAt) .orderBy(OrderBy.asc(Order::getCreatedAt)) .build(); Conceptually, this generates SQL similar to:
SELECT orders.created_at AS order_date, SUM(orders.total) AS revenue FROM orders WHERE orders.status = :param0 AND orders.created_at BETWEEN :param1 AND :param2 GROUP BY orders.created_at ORDER BY orders.created_at ASC; The actual parameter names are generated by Querier.
What's interesting here is that our Java code describes the analytical operation without requiring us to manually maintain the SQL or bind parameters.
We can use this query directly in our dashboard.
Query 2: Top products by revenue
Now let's introduce a JOIN.
Which products generate the most revenue?
Our Order entity contains productId, while the product name is stored in the products table.
We can combine both entities using a type-safe join:
Aggregate aggregateOrderTotalSum = Aggregate.sum(Order::getTotal); Select productRevenueQuery = Select.builder() .select(Product::getId, "product_id") .select(Product::getName, "product_name") .select(aggregateOrderTotalSum.as("revenue")) .from(Order.class) .join( Product.class, Condition.eq(Order::getProductId, Product::getId) ) .where(paidOrdersBetween(from, to)) .groupBy(Product::getId) .groupBy(Product::getName) .orderBy( OrderBy.desc(aggregateOrderTotalSum.toSqlWithoutAlias()) ) .limit(10) .build(); This query demonstrates several useful features:
- JOIN between two entity classes.
- Type-safe foreign-key comparison.
- Aggregation using
SUM. - Multiple GROUP BY expressions.
- Sorting by aggregate revenue.
- Limiting the result set.
We group by both product ID and name so that two different products with identical names aren't accidentally merged.
This is a good example of where Querier becomes valuable: the query is still readable even though we're doing considerably more than a simple SELECT.
Query 3: Order distribution by status
Next, let's understand our order lifecycle.
How many orders are pending, paid, shipped, delivered, or cancelled?
Select orderStatusQuery = Select.builder() .select(Order::getStatus, "status") .select(Aggregate.countAll().as("order_count")) .from(Order.class) .where(Condition.between( Order::getCreatedAt, from, to )) .groupBy(Order::getStatus) .build(); This query returns a result similar to:
| status | order_count |
|---|---|
| PENDING | 35 |
| PAID | 120 |
| SHIPPED | 80 |
| DELIVERED | 240 |
| CANCELLED | 12 |
These are illustrative values, not actual database results.
We intentionally don't filter by paid status here because we want to understand the complete order distribution.
This query will be ideal for a doughnut chart.
Query 4: Top customers by revenue
Now let's make things more interesting.
Which customers generate the most revenue, and what's their average order value?
We'll join orders and customers, aggregate the order totals, and calculate the average order value for each customer.
Aggregate aggregateOrderTotalSum = Aggregate.sum(Order::getTotal); Select topCustomersQuery = Select.builder() .select(Customer::getId, "customer_id") .select(Customer::getName, "customer_name") .select( aggregateOrderTotalSum.as("total_revenue") ) .select( Aggregate.avg(Order::getTotal).as("average_order_value") ) .from(Order.class) .join( Customer.class, Condition.eq(Order::getCustomerId, Customer::getId) ) .where(paidOrdersBetween(from, to)) .groupBy(Customer::getId) .groupBy(Customer::getName) .orderBy( OrderBy.desc(aggregateOrderTotalSum.toSqlWithoutAlias()) ) .limit(10) .build(); This query gives us two important business metrics per customer:
- Total revenue generated.
- Average value of their paid orders.
We'll use both as datasets in the same chart.
Notice how the query builder allows us to select several aggregate expressions and combine them with normal entity fields.
No manual SQL string concatenation is required.
6. Go further with window functions
The previous examples are already useful for many business dashboards.
But enterprise analytics often requires more advanced calculations.
For example:
How does each customer's cumulative spending evolve over time?
This is where SQL window functions become useful.
Querier supports building window expressions using WindowFunction.
Select customerRunningSpendQuery = Select.builder() .select(Order::getId, "order_id") .select(Order::getCustomerId, "customer_id") .select(Order::getCreatedAt, "created_at") .select(Order::getTotal, "order_total") .select( WindowFunction.of( Aggregate.sum(Order::getTotal) ) .partitionBy(Order::getCustomerId) .orderBy(OrderBy.asc(Order::getCreatedAt)) .as("running_customer_spend") ) .from(Order.class) .where(Condition.eq( Order::getStatus, OrderStatus.PAID.name() )) .orderBy( OrderBy.asc(Order::getCustomerId), OrderBy.asc(Order::getCreatedAt) ) .build(); This generates a running total for each customer, resetting the calculation when the customer changes.
Conceptually, the SQL expression is:
SUM(orders.total) OVER ( PARTITION BY orders.customer_id ORDER BY orders.created_at ASC ) You can use this kind of query to build customer spending histories, financial reports, cumulative revenue charts, and other analytical features.
For production reporting, add a deterministic tie-breaker such as order ID when multiple orders can share the same creation date.
Other core capabilities worth exploring include:
- Common Table Expressions (CTEs).
- Subqueries.
- HAVING conditions.
- UNION, INTERSECT, and EXCEPT.
- Database-specific SQL functions.
You don't have to use all these features in every application. The point is that your query builder can grow with the complexity of your reporting requirements.
7. Turn our queries into a Chart.js dashboard
Now comes the interesting part.
We already have four analytical queries. Let's turn them into a dashboard.
With querier-ui, a dashboard consists of three main concepts:
-
Dashboard: The dashboard definition and layout. -
DashboardWidget: A chart backed by a QuerierSelect. -
ChartDataset: Configuration describing which query-result columns should become chart datasets.
Let's create a Spring service.
Implement the database execution adapter
First, we'll define our QueryRunner using Spring's JdbcTemplate.
QueryRunner queryRunner = select -> { Select.PositionalSqlAndParams sp = select.toPositionalSql(); return jdbcTemplate.queryForList( sp.sql(), sp.params().toArray() ); }; That's all we need to connect Querier to our database.
The adapter receives a Select, generates SQL with positional parameters, executes it using JdbcTemplate, and returns the resulting rows.
The dashboard renderer doesn't need to know anything about JdbcTemplate.
Define the dashboard widgets
Let's implement our first widget.
Daily revenue:
private DashboardWidget dailyRevenueWidget( LocalDate from, LocalDate to) { Select query = Select.builder() .select(Order::getCreatedAt, "order_date") .select(Aggregate.sum(Order::getTotal).as("revenue")) .from(Order.class) .where(paidOrdersBetween(from, to)) .groupBy(Order::getCreatedAt) .orderBy(OrderBy.asc(Order::getCreatedAt)) .build(); return DashboardWidget.builder() .title("Daily Revenue") .chartType(ChartType.LINE) .query(query) .labelColumn("order_date") .dataset(ChartDataset.of("revenue") .label("Revenue") .backgroundColor("rgba(78, 121, 167, 0.2)") .borderColor("#4e79a7") .fill(true) .build()) .chartOptions(ChartOptions.builder() .xAxisLabel("Date") .yAxisLabel("Revenue") .legendPosition(ChartOptions.LegendPosition.TOP) .build()) .build(); } We simply associate the revenue result column with a Chart.js dataset and use order_date as the chart label.
No JavaScript chart initialization code.
Top products by revenue:
private DashboardWidget productRevenueWidget( LocalDate from, LocalDate to) { Aggregate aggregateOrderTotalSum = Aggregate.sum(Order::getTotal); Select query = Select.builder() .select(Product::getId, "product_id") .select(Product::getName, "product_name") .select(aggregateOrderTotalSum.as("revenue")) .from(Order.class) .join(Product.class, Condition.eq( Order::getProductId, Product::getId ) ) .where(paidOrdersBetween(from, to)) .groupBy(Product::getId) .groupBy(Product::getName) .orderBy( OrderBy.desc( aggregateOrderTotalSum.toSqlWithoutAlias() ) ) .limit(10) .build(); return DashboardWidget.builder() .title("Top 10 Products by Revenue") .chartType(ChartType.BAR) .query(query) .labelColumn("product_name") .dataset(ChartDataset.of("revenue") .label("Revenue") .backgroundColor("#4e79a7") .borderColor("#2e5a8a") .build()) .chartOptions(ChartOptions.builder() .xAxisLabel("Product") .yAxisLabel("Revenue") .legendPosition(ChartOptions.LegendPosition.TOP) .build()) .build(); } Order distribution:
private DashboardWidget orderStatusWidget( LocalDate from, LocalDateSource:https://dev.to/aissam_assouik/build-a-sales-analytics-dashboard-in-java-with-querier-and-chartjs-1ckRelated posts
Charging Exactly Once: Handling Duplicate and Concurrent Payment Webhooks in Node.js and PostgreSQL
Mounting a 60 GHz Radar in a Child's Room: Geometry, Occlusion, and What It Cannot See
