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,
LocalDate to) {
Select query = 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();
return DashboardWidget.builder()
.title("Order Distribution")
.chartType(ChartType.DOUGHNUT)
.query(query)
.labelColumn("status")
.dataset(ChartDataset.of("order_count")
.label("Orders")
.backgroundColor(
"#4e79a7",
"#f28e2b",
"#e15759",
"#76b7b2",
"#59a14f"
)
.build())
.chartOptions(ChartOptions.builder()
.legendPosition(ChartOptions.LegendPosition.RIGHT)
.build())
.build();
}
Top customers:
Here's where multiple datasets become particularly interesting.
private DashboardWidget topCustomersWidget(
LocalDate from,
LocalDate to) {
Aggregate aggregateOrderTotalSum = Aggregate.sum(Order::getTotal);
Select query = 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();
return DashboardWidget.builder()
.title("Top 10 Customers")
.chartType(ChartType.BAR)
.query(query)
.labelColumn("customer_name")
.dataset(ChartDataset.of("total_revenue")
.label("Total Revenue")
.backgroundColor("#4e79a7")
.build())
.dataset(ChartDataset.of("average_order_value")
.label("Average Order Value")
.backgroundColor("#f28e2b")
.build())
.chartOptions(ChartOptions.builder()
.xAxisLabel("Customer")
.yAxisLabel("Amount")
.legendPosition(ChartOptions.LegendPosition.TOP)
.stacked(false)
.build())
.build();
}
The important detail is that we can call .dataset() multiple times.
One query can provide multiple chart datasets without executing a separate query for every series.
Here both metrics are monetary values, making them suitable for comparison on the same axis.
8. Assemble and render the complete dashboard
Now let's put everything together.
@Service
public class SalesDashboardService {
private final JdbcTemplate jdbcTemplate;
public SalesDashboardService(
JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public String renderDashboard(
LocalDate from,
LocalDate to) {
if (from == null || to == null || from.isAfter(to)) {
throw new IllegalArgumentException(
"Invalid reporting date range"
);
}
QueryRunner runner = select -> {
Select.PositionalSqlAndParams sp =
select.toPositionalSql();
return jdbcTemplate.queryForList(
sp.sql(),
sp.params().toArray()
);
};
Dashboard dashboard = Dashboard.builder()
.title("Sales Performance Dashboard")
.layout(DashboardLayout.GRID_2_COLS)
.addWidget(dailyRevenueWidget(from, to))
.addWidget(productRevenueWidget(from, to))
.addWidget(orderStatusWidget(from, to))
.addWidget(topCustomersWidget(from, to))
.build();
return DashboardRenderer.builder()
.dashboard(dashboard)
.queryRunner(runner)
.build()
.renderHtml();
}
// Add the four widget methods shown above.
// Add paidOrdersBetween(...) as the shared filter.
}
We're now assembling four independently defined widgets into one dashboard.
The renderer takes care of executing the queries, mapping their results to chart data, and generating the HTML.
The final result is simply a Java String containing the rendered dashboard.
9. Expose the dashboard through Spring MVC
We can now expose the generated dashboard through a regular Spring MVC endpoint.
@Controller
public class SalesDashboardController {
private final SalesDashboardService dashboardService;
public SalesDashboardController(
SalesDashboardService dashboardService) {
this.dashboardService = dashboardService;
}
@GetMapping(
value = "/analytics/sales",
produces = MediaType.TEXT_HTML_VALUE
)
@ResponseBody
public String salesDashboard(
@RequestParam LocalDate from,
@RequestParam LocalDate to) {
return dashboardService.renderDashboard(from, to);
}
}
For example:
GET /analytics/sales?from=2026-10-01&to=2026-10-31
And that's it!
You now have a server-side analytics endpoint that generates its dashboard directly from Querier queries.
You can also use:
.renderFragment()
instead of:
.renderHtml()
when you want to embed the dashboard inside an existing Thymeleaf, JSP, or other HTML page.
10. What makes this useful for enterprise applications?
The real value here isn't just reducing the amount of JavaScript we write.
It's the separation of concerns and the ability to reuse analytical query definitions.
Execution independence
Our query definitions don't know anything about JdbcTemplate.
The same Select can produce different SQL parameter formats:
// Named parameters
Select.SqlAndParams named = query.toSqlAndParams();
// Positional parameters
Select.PositionalSqlAndParams positional =
query.toPositionalSql();
// Indexed parameters
Select.IndexedSqlAndParams indexed =
query.toIndexedSql();
That allows querier-core to be integrated with different execution technologies.
For example:
- Spring NamedParameterJdbcTemplate.
- Spring JdbcTemplate.
- Plain JDBC.
- Hibernate native queries.
- jOOQ.
- R2DBC DatabaseClient.
- Vert.x SQL Client.
The execution adapter is the responsibility of your application.
One distinction worth mentioning: execution independence doesn't mean every database uses identical SQL syntax. Database-specific functions and SQL dialect features still need appropriate handling.
Query definitions can be reused
An analytical query doesn't have to belong to a dashboard.
The same Select object can be used to:
- Generate a dashboard chart.
- Populate an exportable report.
- Provide data to an API endpoint.
- Feed another business calculation.
- Execute through a different database adapter.
This is particularly useful when the same business metric is needed across several application features.
More advanced SQL without losing readability
Real enterprise reporting rarely stops at simple aggregations.
You may eventually need:
- Multiple joins.
- Nested conditions.
- Subqueries.
- Window functions.
- CTEs.
- Database-specific functions.
- Complex parameterized filters.
Querier gives you a consistent builder API for these operations while keeping entity column references strongly tied to Java methods.
Server-side dashboard generation
The querier-ui module removes a significant amount of repetitive dashboard development work.
You don't have to maintain:
- A separate JavaScript chart initialization for every widget.
- Manual SQL-to-Chart.js dataset mapping.
- Repetitive dashboard HTML templates.
- A custom chart rendering pipeline.
You describe the widget and its data using Java, and Querier generates the HTML.
The default Chart.js URL uses a CDN. For controlled or offline environments, you can configure a self-hosted Chart.js bundle:
DashboardRenderer.builder()
.dashboard(dashboard)
.queryRunner(runner)
.chartJsUrl("/static/js/chart.umd.min.js")
.build()
.renderHtml();
This can be useful for enterprise deployments with restricted internet access or strict Content Security Policies.
11. A few production considerations
Before using this approach in a real analytics service, there are a few things worth considering.
Tenant isolation and authorization
Don't assume that generating parameterized queries is sufficient for multi-tenant security.
Every reporting query must respect the authenticated user's permissions and tenant boundaries. Apply those constraints consistently to all relevant widgets.
Performance
A dashboard containing four widgets may execute four separate SQL queries.
Use appropriate indexes, analyze execution plans, consider pre-aggregated reporting tables or materialized views for expensive analytics, and avoid returning unnecessarily large datasets.
Date handling
The example uses LocalDate and inclusive date ranges because our entity stores order creation dates as LocalDate.
If your production application stores timestamps, define the timezone and date-boundary rules explicitly.
Reactive applications
querier-core can generate SQL for R2DBC, but the dashboard QueryRunner integration shown here uses a synchronous result-list execution model. Don't assume the dashboard renderer automatically provides reactive execution or backpressure.
Rendering and security
Serve generated dashboards through appropriately protected endpoints. Be deliberate about the Chart.js source, Content Security Policy, and any untrusted data used in labels or other displayed values.
Conclusion
Building analytical features shouldn't require coupling every report to a database execution framework or manually maintaining JavaScript chart configurations.
With Querier, we can build type-safe queries using Java method references, combine them with real SQL capabilities such as JOINs, GROUP BY, aggregations and window functions, and turn the results into Chart.js-powered dashboards.
The responsibilities stay clear:
-
querier-corebuilds the queries. - Your application decides how to execute them.
-
querier-uitransforms query results into dashboards.
And because these are independent components, you can adopt them incrementally.
You can start with querier-core for reporting and query construction, then introduce querier-ui when you need server-side dashboards.
Explore the project:
- GitHub: https://github.com/AytmaTech/Querier
- Project documentation: https://aytmatech.com/projects/querier/
- Maven Central: https://central.sonatype.com/artifact/com.aytmatech/querier-core
- Maven Central: https://central.sonatype.com/artifact/com.aytmatech/querier-ui
Feedback, suggestions, and contributions are welcome!
Top comments (0)