Skip to content
javahacks.dev
Jakarta EE

Jakarta Data Repository Interfaces and Queries Explained

Learn Jakarta Data 1.0: repository interfaces, CrudRepository, Find and Query annotations, pagination and how it compares with Spring Data.

5 min read
Summarize in AI
Flat illustration of a request passing through a servlet container, with the Hibernate, Docker, Apache Tomcat and NGINX logos.

Every data access layer reinvents the same repository: an interface with find, save and delete methods plus a few queries for the entity. Spring Data made the pattern common, and Jakarta Data 1.0, part of Jakarta EE 11, standardises it for the platform. This guide shows a repository interface with the main annotations, how it is injected and used, the method-name style, pagination, the providers that implement it and how it compares with Spring Data. The code is illustrative of the specification, so check the details of your provider's release before relying on a feature.

A repository

java
@Repository
public interface Orders extends CrudRepository<Order, Long> {

    @Find
    List<Order> byCustomer(String customer);

    @Find
    Optional<Order> byReference(@By("reference") String ref);

    @Query("where status = :status order by createdAt desc")
    List<Order> withStatus(Status status);

    @Delete
    void remove(Order order);
}

CrudRepository supplies insert, update, save, deleteById, findById and findAll. The annotation @Find derives a query from the parameter names, matched to entity attributes, and @By states the attribute explicitly when the parameter name differs. @Query takes a statement in Jakarta Data Query Language, a subset of Jakarta Persistence Query Language that can drop the select and from clauses when they are implied by the return type. The implementation is generated by the provider at build time with an annotation processor, which means no reflection and no runtime proxies, and it shows errors in a bad query at compile time.

Injection and use

java
@ApplicationScoped
class OrderService {

    @Inject Orders orders;

    @Transactional
    void place(Order o) { orders.insert(o); }
}

Repositories are CDI beans, injected like any other. Transactions follow the Jakarta Transactions rules in the usual way, so a repository method called inside a transactional method joins that transaction. Because the interface is the only thing the service knows about, a unit test can replace it with a fake that holds a list, with no database.

Method names

Jakarta Data also supports queries derived from method names, for simple cases:

java
List<Order> findByCustomerAndStatusOrderByCreatedAtDesc(String customer, Status status);

The keywords are findBy, deleteBy, countBy and existsBy, with operators such as And, Or, Between, LessThan and Like. Long names are hard to read and break when an attribute is renamed in ways the compiler cannot always check, so the specification prefers the annotations, a deliberate difference from Spring Data, where the method-name form is central. Use the name form for a one-condition lookup, and an annotation as soon as a second condition or a sort appears.

Pagination

java
@Find
Page<Order> byStatus(Status status, PageRequest page, Order<Order> sort);

Page<Order> first = orders.byStatus(Status.OPEN, PageRequest.ofSize(20), Order.by(Sort.desc("createdAt")));

Page offers offset-based paging with a total count if requested. CursoredPage offers keyset paging with a cursor, which keeps constant cost on large tables and stays stable while rows are inserted; the technique is described in cursor pagination. Passing the sort as a parameter keeps the repository method generic, while a fixed sort belongs in the annotation. Always bound the page size on public endpoints.

Providers

Hibernate ORM includes a Jakarta Data implementation, called Hibernate Data Repositories, that works with Jakarta Persistence entities and with Hibernate's stateless session for high-volume operations; its coverage depends on the Hibernate release, so read the documentation of the version you run. Other providers target NoSQL stores, and a repository interface can then be backed by a document or key-value database. In Quarkus, the Panache extensions remain the main path for data access, with Jakarta Data support evolving. An application server such as WildFly or Open Liberty can supply an implementation through its Jakarta EE 11 support.

Compared with Spring Data

AspectSpring DataJakarta Data
StandardSpring projectJakarta EE specification
Query by method nameCentralSupported, annotations preferred
Custom queries@Query with JPQL@Query with JDQL
ImplementationProxies at runtime (AOT possible)Generated at build time
StoresMany modulesProviders per store

The practical effect is similar: an interface, a few annotated methods and an implementation you never write. If your application already uses Spring, there is no reason to switch. Jakarta Data matters for teams on application servers and for libraries that want a portable repository abstraction. The role of repositories in design, including whether to wrap them, is discussed in Spring Data versus the repository pattern.

Testing repositories

Test a repository against a real database of the same type as production, with Testcontainers or the server's test support, because derived queries and the query language dialect differ between stores. One test per custom query is enough: insert a few rows, call the method and assert on the result and the order. Test pagination with more rows than a page, and check the last page and an empty page. Do not mock the repository to test a query, since a mock proves nothing about it.

Lifecycle methods and stateless operations

Repository methods can carry lifecycle annotations: @Insert, @Update, @Save and @Delete operate on entities or on collections of them, and a batch insert of a list is one call. Providers can use a stateless session underneath, which skips the persistence context and dirty checking, trading convenience for speed on bulk writes. The consequence is that entities are not managed after the call: changes you make to an instance afterwards are not saved automatically, and lazy associations are not loaded for you. Choose this mode for imports and batch jobs, and the managed mode for ordinary request handling.

Return types and errors

A method returning Optional<T> or a single T expresses an expected single result, and a method returning a List or a Stream expresses many. Jakarta Data defines exceptions for the common failures, such as an entity that already exists on insert and an optimistic lock failure on update, so service code can handle them without provider-specific types. Catch the specification's exceptions at the service boundary and translate them into your own domain errors, so the repository's technology does not leak into the API.

Choosing between repositories and queries in code

A repository interface suits CRUD operations and named queries. For a query assembled at run time from many optional filters, use the persistence API's criteria support or a stateless session in a small custom class, and keep the repository for the common cases. Mixing both keeps the interface short and puts the complex query where it can be tested in isolation.

If the same filter logic appears in several repositories, move it to a method on the entity or to a shared specification, so a business rule has one definition.

When Jakarta Data is not enough

Complex reporting queries, native features and deep entity graphs still need Jakarta Persistence or SQL directly. The entity model underneath is the one described in the Hibernate guide. The references are the Jakarta Data specification and Hibernate's Jakarta Data documentation, which describes the provider.

Also inHibernate
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.