1
---
2
name: java-helidon
3
description: 'Get best practices for developing applications with Helidon 4 (SE and MP). Use when working with Helidon SE or Helidon MP, HttpService routing, Helidon DB Client, MicroProfile Config, Helidon Security, or Helidon testing in Java 21+ projects.'
4
---
5
6
# Helidon Best Practices
7
8
Your goal is to help me write high-quality Helidon applications by following established best practices.
9
10
## Helidon 3 → 4 API changes
11
12
Helidon 4 renamed or resignatured APIs that appear widely in their Helidon 3 form.
13
The left column does not compile on Helidon 4. Check generated code against this table
14
before returning it.
15
16
| Do not use (Helidon 3) | Use (Helidon 4) |
17
| ---------------------------------------------------------- | ------------------------------------------------------------------ |
18
| `io.helidon.common.http.Http.Status` | `io.helidon.http.Status` |
19
| `io.helidon.webserver.Service` | `io.helidon.webserver.http.HttpService` |
20
| `Routing.Rules`, `update(Routing.Rules)` | `HttpRules`, `routing(HttpRules)` |
21
| `request.path().param("id")` | `request.path().pathParameters().get("id")` |
22
| `String s = column.as(String.class)` | `column.getString()` or `column.get(String.class)` |
23
| `dbClient.execute(exec -> ...)` returning `Single`/`Multi` | `dbClient.execute()` returning `Optional<DbRow>` / `Stream<DbRow>` |
24
| `javax.*` | `jakarta.*` |
25
| `helidon-microprofile-tests-junit5` | `helidon-microprofile-testing-junit5` |
26
27
`Value.as(Class)` in Helidon 4 returns `OptionalValue<T>`, not `T`. This is the single
28
most common Helidon 4 compile error in generated code.
29
30
## Project Setup & Structure
31
32
- **Programming Model:** Determine whether the project uses Helidon SE or Helidon MP before generating code. Do not mix the two programming models unless explicitly required.
33
- **Java Version:** Use Java 21 or later for Helidon 4 applications.
34
- **Build Tool:** Use Maven (`pom.xml`) or Gradle (`build.gradle`) for dependency management.
35
- **Dependency Management:** Use the Helidon BOM or platform to keep Helidon module versions aligned.
36
- **Package Structure:** Organize code by feature or domain, such as `com.example.app.order` and `com.example.app.customer`, rather than only by technical layer.
37
38
## Helidon SE
39
40
- **Explicit Composition:** Construct services and dependencies explicitly in the application bootstrap layer.
41
- **Constructor Injection:** Pass required dependencies through constructors and declare dependency fields as `private final`.
42
- **HTTP Services:** Group related routes in focused `HttpService` implementations.
43
- **Business Logic:** Keep business logic outside route handlers.
44
- **Virtual Threads:** Prefer straightforward blocking code with Helidon 4 virtual-thread-based request handling. Do not introduce reactive complexity without a clear reason. Helidon 4 is not reactive; do not generate `Single`, `Multi`, or `CompletionStage` chains.
45
46
## Helidon MP
47
48
- **Jakarta and MicroProfile:** Prefer standard Jakarta EE and Eclipse MicroProfile APIs when available.
49
- **Dependency Injection:** Use CDI with constructor injection for required dependencies.
50
- **Bean Scopes:** Use CDI scopes such as `@ApplicationScoped` and `@RequestScoped` intentionally.
51
- **Normal-Scoped Beans:** Add a non-private no-argument constructor to normal-scoped beans that use constructor injection, so the CDI client proxy can be created portably.
52
- **Business Logic:** Keep Jakarta REST resource classes thin and delegate business operations to service classes.
53
- **Portability:** Prefer portable Jakarta and MicroProfile APIs over Helidon-specific APIs when portability is important.
54
55
## Configuration
56
57
- **Externalized Configuration:** Store non-secret configuration in `application.yaml` or `application.properties`.
58
- **Helidon SE Configuration:** Use Helidon Config and pass configuration values or typed configuration objects to components.
59
- **Helidon MP Configuration:** Use MicroProfile Config for injected application settings.
60
- **Environment Overrides:** Use environment variables or deployment-specific configuration sources for environment-dependent values.
61
- **Secrets Management:** Never hardcode credentials, API keys, tokens, or private certificates.
62
63
## Web Layer
64
65
- **DTOs:** Use dedicated request and response models. Do not expose persistence entities directly through APIs.
66
- **Validation:** Validate path parameters, query parameters, headers, and request bodies before invoking business logic.
67
- **Status Codes:** Return appropriate HTTP status codes for successful, invalid, unauthorized, forbidden, missing, and failed requests. On `PUT` and `DELETE`, return 404 when the target does not exist rather than succeeding unconditionally.
68
- **Error Handling:** Use centralized error handling in Helidon SE and Jakarta REST `ExceptionMapper` implementations in Helidon MP.
69
- **Sensitive Information:** Do not expose stack traces, database details, filesystem paths, or internal exception messages to clients.
70
71
### Helidon SE Example
72
73
Use an `HttpService` to register routes programmatically. Keep request handlers small and delegate business logic to a service.
74
75
```java
76
import io.helidon.http.Status;
77
import io.helidon.webserver.http.HttpRules;
78
import io.helidon.webserver.http.HttpService;
79
import io.helidon.webserver.http.ServerRequest;
80
import io.helidon.webserver.http.ServerResponse;
81
82
public final class CustomerHttpService implements HttpService {
83
84
private final CustomerService customerService;
85
86
public CustomerHttpService(CustomerService customerService) {
87
this.customerService = customerService;
88
}
89
90
@Override
91
public void routing(HttpRules rules) {
92
rules.get("/{id}", this::findById);
93
}
94
95
private void findById(ServerRequest request, ServerResponse response) {
96
var id = request.path().pathParameters().get("id");
97
98
customerService.findById(id)
99
.ifPresentOrElse(
100
response::send,
101
() -> response.status(Status.NOT_FOUND_404).send()
102
);
103
}
104
}
105
```
106
107
Register the HTTP service when constructing the server:
108
109
```java
110
import io.helidon.webserver.WebServer;
111
112
WebServer server = WebServer.builder()
113
.routing(routing -> routing.register("/customers", customerHttpService))
114
.build()
115
.start();
116
```
117
118
### Helidon MP Example
119
120
Use Jakarta REST annotations for endpoints and CDI for dependency injection.
121
122
```java
123
import jakarta.enterprise.context.RequestScoped;
124
import jakarta.inject.Inject;
125
import jakarta.ws.rs.GET;
126
import jakarta.ws.rs.Path;
127
import jakarta.ws.rs.PathParam;
128
import jakarta.ws.rs.Produces;
129
import jakarta.ws.rs.core.MediaType;
130
import jakarta.ws.rs.core.Response;
131
132
@Path("/customers")
133
@RequestScoped
134
@Produces(MediaType.APPLICATION_JSON)
135
public class CustomerResource {
136
137
private final CustomerService customerService;
138
139
protected CustomerResource() {
140
this.customerService = null;
141
}
142
143
@Inject
144
public CustomerResource(CustomerService customerService) {
145
this.customerService = customerService;
146
}
147
148
@GET
149
@Path("/{id}")
150
public Response findById(@PathParam("id") String id) {
151
return customerService.findById(id)
152
.map(customer -> Response.ok(customer).build())
153
.orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build());
154
}
155
}
156
```
157
158
## Service Layer
159
160
- **Transactions:** Define transaction boundaries around complete business operations.
161
- **Entity Mapping:** Map persistence entities to API models at the service boundary so that service method signatures expose only API models. A service returning `Optional<CustomerEntity>` where the caller expects `Optional<Customer>` is a common generated-code compile error.
162
- **Concurrency:** Avoid mutable shared state in application-scoped components unless access is properly coordinated.
163
164
### Helidon SE Example
165
166
Helidon SE services are normally plain Java classes with explicitly supplied dependencies.
167
168
```java
169
public final class CustomerService {
170
171
private final CustomerRepository customerRepository;
172
173
public CustomerService(CustomerRepository customerRepository) {
174
this.customerRepository = customerRepository;
175
}
176
177
public Optional<Customer> findById(String id) {
178
if (id == null || id.isBlank()) {
179
throw new IllegalArgumentException("Customer ID is required");
180
}
181
182
return customerRepository.findById(id);
183
}
184
185
public Customer create(CreateCustomerRequest request) {
186
if (request.name() == null || request.name().isBlank()) {
187
throw new IllegalArgumentException("Customer name is required");
188
}
189
190
var customer = new Customer(request.id(), request.name().trim());
191
192
customerRepository.save(customer);
193
return customer;
194
}
195
}
196
```
197
198
Construct the dependency graph explicitly:
199
200
```java
201
var repository = new DbCustomerRepository(dbClient);
202
var service = new CustomerService(repository);
203
var httpService = new CustomerHttpService(service);
204
```
205
206
### Helidon MP Example
207
208
Use CDI scopes and constructor injection. Apply transactions at the service layer when a business operation changes persistent state. Map the persistence entity to the API model here, so the service never leaks `CustomerEntity` to callers.
209
210
```java
211
import jakarta.enterprise.context.ApplicationScoped;
212
import jakarta.inject.Inject;
213
import jakarta.transaction.Transactional;
214
215
@ApplicationScoped
216
public class CustomerService {
217
218
private final JpaCustomerRepository customerRepository;
219
220
protected CustomerService() {
221
this.customerRepository = null;
222
}
223
224
@Inject
225
public CustomerService(JpaCustomerRepository customerRepository) {
226
this.customerRepository = customerRepository;
227
}
228
229
public Optional<Customer> findById(String id) {
230
if (id == null || id.isBlank()) {
231
throw new IllegalArgumentException("Customer ID is required");
232
}
233
234
return customerRepository.findById(id)
235
.map(Customer::fromEntity);
236
}
237
238
@Transactional
239
public Customer create(CreateCustomerRequest request) {
240
if (request.name() == null || request.name().isBlank()) {
241
throw new IllegalArgumentException("Customer name is required");
242
}
243
244
var entity = new CustomerEntity(request.id(), request.name().trim());
245
246
customerRepository.save(entity);
247
return Customer.fromEntity(entity);
248
}
249
}
250
```
251
252
## Data Layer
253
254
- **Database Access:** Use Helidon DB Client, Jakarta Persistence, or another persistence mechanism already established by the project.
255
- **Parameterized Queries:** Always use parameter binding or prepared statements. Never concatenate untrusted input into SQL.
256
- **Column Accessors:** Read a typed column value with `column("name").getString()` (or `getInt()`, `getLong()`, and so on) or with `column("name").get(String.class)`. `DbColumn.as(String.class)` returns an `OptionalValue<String>` in Helidon 4, not a `String`.
257
- **Nullable Columns:** Read nullable columns through `asOptional()` or another optional-aware accessor. Direct `getString()` and similar accessors throw when the column value is null.
258
- **Row Mapping:** For whole-row mapping, `DbRow.as(Customer.class)` returns the mapped instance directly, but requires a `DbMapper` registered through a `DbMapperProvider` service-loader entry. Prefer explicit column reads for a small number of simple repositories, and introduce a `DbMapper` when the same row shape is mapped in several places.
259
- **Migrations:** Use a database migration tool for schema changes rather than automatic destructive schema updates.
260
- **Entity Separation:** Do not expose database entities directly as API contracts.
261
262
### Helidon SE Example
263
264
Use Helidon DB Client with parameterized statements. Map database rows into application models inside the repository.
265
266
```java
267
import io.helidon.dbclient.DbClient;
268
269
public final class DbCustomerRepository implements CustomerRepository {
270
271
private static final String FIND_BY_ID =
272
"SELECT id, name FROM customers WHERE id = :id";
273
274
private static final String INSERT =
275
"INSERT INTO customers (id, name) VALUES (:id, :name)";
276
277
private final DbClient dbClient;
278
279
public DbCustomerRepository(DbClient dbClient) {
280
this.dbClient = dbClient;
281
}
282
283
@Override
284
public Optional<Customer> findById(String id) {
285
return dbClient.execute()
286
.createGet(FIND_BY_ID)
287
.addParam("id", id)
288
.execute()
289
.map(row -> new Customer(
290
row.column("id").getString(),
291
row.column("name").getString()
292
));
293
}
294
295
@Override
296
public void save(Customer customer) {
297
dbClient.execute()
298
.createInsert(INSERT)
299
.addParam("id", customer.id())
300
.addParam("name", customer.name())
301
.execute();
302
}
303
}
304
```
305
306
Named statements can also be stored in configuration instead of embedding SQL in Java:
307
308
```yaml
309
db:
310
source: "jdbc"
311
connection:
312
url: "jdbc:postgresql://localhost:5432/customers"
313
username: ${DB_USERNAME}
314
password: ${DB_PASSWORD}
315
statements:
316
find-customer-by-id: >
317
SELECT id, name
318
FROM customers
319
WHERE id = :id
320
```
321
322
Reference the named statement by name instead of passing SQL text:
323
324
```java
325
return dbClient.execute()
326
.createNamedGet("find-customer-by-id")
327
.addParam("id", id)
328
.execute()
329
.map(row -> new Customer(
330
row.column("id").getString(),
331
row.column("name").getString()
332
));
333
```
334
335
### Helidon MP Example
336
337
Use Jakarta Persistence in a CDI-managed repository. Keep transaction boundaries in the service layer. The repository works in entities; the service maps them to API models.
338
339
```java
340
import jakarta.enterprise.context.ApplicationScoped;
341
import jakarta.persistence.EntityManager;
342
import jakarta.persistence.PersistenceContext;
343
344
@ApplicationScoped
345
public class JpaCustomerRepository {
346
347
@PersistenceContext
348
private EntityManager entityManager;
349
350
public Optional<CustomerEntity> findById(String id) {
351
return Optional.ofNullable(entityManager.find(CustomerEntity.class, id));
352
}
353
354
public void save(CustomerEntity customer) {
355
entityManager.persist(customer);
356
}
357
}
358
```
359
360
Define the persistence entity separately from the public API model:
361
362
```java
363
import jakarta.persistence.Column;
364
import jakarta.persistence.Entity;
365
import jakarta.persistence.Id;
366
import jakarta.persistence.Table;
367
368
@Entity
369
@Table(name = "customers")
370
public class CustomerEntity {
371
372
@Id
373
private String id;
374
375
@Column(nullable = false)
376
private String name;
377
378
protected CustomerEntity() {
379
}
380
381
public CustomerEntity(String id, String name) {
382
this.id = id;
383
this.name = name;
384
}
385
386
public String id() {
387
return id;
388
}
389
390
public String name() {
391
return name;
392
}
393
}
394
```
395
396
The API model stays free of persistence annotations and owns the mapping:
397
398
```java
399
public record Customer(String id, String name) {
400
401
public static Customer fromEntity(CustomerEntity entity) {
402
return new Customer(entity.id(), entity.name());
403
}
404
}
405
```
406
407
## Observability
408
409
- **Health:** Use Helidon Health in SE or MicroProfile Health in MP for liveness and readiness checks.
410
- **Metrics:** Use Helidon Metrics or MicroProfile Metrics for operational and business measurements.
411
- **Tracing:** Propagate tracing context across inbound and outbound service calls.
412
- **Cardinality:** Avoid user IDs, request IDs, email addresses, and raw URLs as metric tags.
413
414
## Logging
415
416
- **Logging API:** Use the logging API and implementation configured by the project.
417
- **Sensitive Information:** Never log passwords, access tokens, authorization headers, cookies, or complete sensitive request bodies. Do not place secrets or personal information in metrics or trace attributes either.
418
419
## Testing
420
421
- **Unit Tests:** Write unit tests for business services using JUnit 5.
422
- **Helidon SE Tests:** Use `helidon-webserver-testing-junit5` with `@ServerTest` for full server tests and `@RoutingTest` for routing-only tests. These start the server on a dynamically selected port and inject a `Http1Client` bound to it. Never hardcode a port.
423
- **Helidon MP Tests:** Use `helidon-microprofile-testing-junit5` with `@HelidonTest`, which starts the CDI container and server for the test class. Confirm the artifact coordinates against the Helidon version in use, since this module was renamed across 4.x releases.
424
- **Testcontainers:** Consider Testcontainers for integration tests using real databases, message brokers, or other infrastructure.
425
- **Failure Paths:** Test validation failures, missing resources, external-service failures, and authorization failures.
426
427
## Security
428
429
- **Helidon Security:** Use Helidon Security or supported Jakarta and MicroProfile security APIs for authentication and authorization.
430
- **Authorization:** Enforce permissions at a clear application boundary and deny protected operations by default.
431
- **JWT and OIDC:** Validate token signatures, issuers, audiences, and expiration times.
432
- **TLS:** Use TLS for production traffic and verify certificates for outbound connections.
433
- **CORS:** Configure allowed origins explicitly. Do not combine wildcard origins with credentials.
434
- **Secrets:** Store secrets in protected environment configuration or a dedicated secret-management system.
435
- **Outbound Requests:** Validate outbound destinations to reduce server-side request forgery risks.
436