Eclipse JNoSQL

Jakarta Data

Repository-oriented persistence for enterprise Java, with a simple and productive programming model for NoSQL databases.

Jakarta Data standardizes repository-oriented persistence. You declare repository interfaces, and Eclipse JNoSQL provides their implementations, so common persistence code does not have to be written by hand. Which capabilities are available depends on the Jakarta Data and Eclipse JNoSQL versions you use and on the underlying database model and provider.

Get Started in Three Steps

The steps use a Product entity. You need a configured JNoSQL database provider and a CDI environment; see the Minimum Requirements and the guide for your database model (Key-Value, Wide-Column, Document, Graph, Time Series, or Vector) for the dependencies and configuration. Snippets omit the java.* imports (BigDecimal, LocalDate, List, Optional) for readability.

  1. 01 Map your entity Create a Java class using persistence annotations.
  2. 02 Create a repository Declare a repository interface with @Repository.
  3. 03 Inject and use Inject the repository and start persisting entities.
import jakarta.nosql.Column;
import jakarta.nosql.Entity;
import jakarta.nosql.Id;

@Entity
public record Product(
        @Id String id,
        @Column String name,
        @Column BigDecimal price,
        @Column int stock,
        @Column int minimumStock,
        @Column String category,
        @Column LocalDate expirationDate) {
}

Entities are mapped with the Jakarta NoSQL annotations @Entity, @Id and @Column. A Java record keeps the mapping to its attributes. See Jakarta NoSQL and the Mapping Annotations reference.

import jakarta.data.repository.BasicRepository;
import jakarta.data.repository.Repository;

@Repository
public interface ProductRepository
        extends BasicRepository<Product, String> {

    List<Product> findByCategory(String category);
}

Extending BasicRepository provides save, findById and other common operations, and a method such as findByCategory is a derived query built from its name. You do not write an implementation: Eclipse JNoSQL provides it automatically.

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

@ApplicationScoped
public class ProductService {

    @Inject
    ProductRepository repository;

    public void run() {
        Product keyboard = new Product("p-1", "Keyboard", new BigDecimal("49.90"),
                25, 5, "peripherals", LocalDate.of(2030, 1, 1));

        repository.save(keyboard);

        Optional<Product> byId = repository.findById("p-1");
        List<Product> peripherals = repository.findByCategory("peripherals");
    }
}

Inject the repository into a CDI-managed class. Support for queries beyond lookup by identifier depends on the capabilities of the database; see Database Capabilities.

Key Features

Explore the core Jakarta Data capabilities with Eclipse JNoSQL.

Database Capabilities

Jakarta Data provides a consistent model, but query capabilities vary by database type.

Repositories

A Jakarta Data repository is an interface annotated with @Repository. Eclipse JNoSQL provides its implementation, which removes most of the persistence boilerplate. What the repository exposes depends on what it extends:

Approach Declaration Use it when
BasicRepository extends BasicRepository<Product, String> You need to save, find, and delete entities.
CrudRepository extends CrudRepository<Product, String> You also need explicit insert and update operations.
Custom repository Extends nothing You want to expose only the operations your domain needs.
NoSQLRepository JNoSQL Extension extends NoSQLRepository<Product, String> You also need existsById, findByIdIn, deleteByIdIn, countBy or deleteAll.

Repositories are built on entities mapped with the Jakarta NoSQL annotations; see Jakarta NoSQL and the Mapping Annotations reference. The examples reuse the Product entity from Step 1. Which operations succeed also depends on the database model; see Database Capabilities.

BasicRepository

BasicRepository<T, K> provides the common operations for an entity T with identifier type K. Extend it and add your own query methods:

import jakarta.data.repository.BasicRepository;
import jakarta.data.repository.Repository;

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    List<Product> findByName(String name);

    List<Product> findByPriceLessThan(BigDecimal price);
}
Method Description
save(entity) / saveAll(entities) Inserts the entity, or updates it if one with the same identifier already exists.
findById(id) Returns an Optional with the entity, or an empty Optional.
findAll() Returns a Stream of all entities.
findAll(pageRequest, order) Returns a Page of entities; see Pagination.
deleteById(id) Deletes the entity with the identifier.
delete(entity) / deleteAll(entities) Deletes the given entities.
@Inject
ProductRepository repository;

Product keyboard = new Product("p-1", "Keyboard", new BigDecimal("49.90"),
        25, 5, "peripherals", LocalDate.of(2030, 1, 1));

Product saved = repository.save(keyboard);
Optional<Product> byId = repository.findById("p-1");
List<String> names = repository.findAll().map(Product::name).toList();
Page<Product> firstPage = repository.findAll(PageRequest.ofSize(10), Order.by(Sort.asc("name")));

repository.deleteById("p-1");

findAll() is not available on Key-Value and Wide-Column databases, which raise UnsupportedOperationException.

CrudRepository

CrudRepository<T, K> extends BasicRepository and adds explicit insert and update operations, in single and list forms:

import jakarta.data.repository.CrudRepository;
import jakarta.data.repository.Repository;

@Repository
public interface ProductRepository extends CrudRepository<Product, String> {
}

In the following snippet, keyboard and mouse are Product instances:

Product inserted = repository.insert(keyboard);
List<Product> insertedAll = repository.insertAll(List.of(keyboard, mouse));

Product updated = repository.update(keyboard);
List<Product> updatedAll = repository.updateAll(List.of(keyboard, mouse));

Product saved = repository.save(keyboard);

repository.deleteById("p-1");
List<Product> everything = repository.findAll().toList();

The three write operations differ in intent:

  • insert adds a new entity.
  • update modifies an entity that already exists.
  • save inserts the entity if its identifier is not in the database and updates it otherwise, so use it when you do not know which case applies.

The strictness of these operations depends on the database. On a database with ACID transactions, inserting an existing identifier raises EntityExistsException, and updating a missing entity raises OptimisticLockingFailureException. On databases that follow the BASE model or write by key, neither exception is raised and insert and update can behave the same. Do not assume identical upsert or transactional semantics across databases.

Custom repositories

A repository does not have to extend BasicRepository or CrudRepository. A custom repository declares only the methods the application needs, using the repository annotations. Eclipse JNoSQL infers the entity from the method signatures.

@Repository
public interface ProductCatalog {

    @Insert
    Product register(Product product);

    @Find
    Optional<Product> find(@By(By.ID) String id);

    @Find
    List<Product> inCategory(@By("category") String category);
}

ProductCatalog can register and look up products but has no delete or update operation, and it does not expose findAll. This keeps the persistence API aligned with the domain and prevents callers from performing operations the application does not intend to support.

NoSQLRepository

JNoSQL Extension

NoSQLRepository<T, K> (org.eclipse.jnosql.mapping.NoSQLRepository, module jnosql-mapping-api-core) is a general-purpose JNoSQL repository. It extends BasicRepository and CrudRepository with operations that are common to NoSQL databases and works with any JNoSQL database.

Method Purpose
boolean existsById(K id) Check whether an entity exists
Stream<T> findByIdIn(Iterable<K> ids) Retrieve entities by multiple identifiers
void deleteByIdIn(Iterable<K> ids) Delete entities by multiple identifiers
long countBy() Count entities
void deleteAll() Delete all entities

Key-Value and Wide-Column databases that cannot count or delete everything throw UnsupportedOperationException from countBy() and deleteAll().

import org.eclipse.jnosql.mapping.NoSQLRepository;

@Repository
public interface ProductRepository
        extends NoSQLRepository<Product, String> {
}
boolean exists = products.existsById("P-100");
Stream<Product> some = products.findByIdIn(List.of("P-100", "P-200"));
products.deleteByIdIn(List.of("P-100", "P-200"));
long count = products.countBy();
products.deleteAll();

To run native queries of a specific database, see Provider-Specific Repositories.

Repository Annotations

Annotations declare what a repository method does. Operation annotations (@Insert, @Update, @Save, @Delete, @Find, @Query) are mutually exclusive on a method; the other annotations refine the operation. The Since column is shown only for annotations introduced after Jakarta Data 1.0.

Annotation Purpose Since
@Repository Declare a repository  
@Find Retrieve entities  
@Insert Insert entities  
@Update Update existing entities  
@Save Persist entities (insert or update)  
@Delete Delete entities  
@Query Declare an explicit query  
@Param Bind a method parameter to a named query parameter  
@By Associate a parameter with an entity attribute  
@OrderBy Define static ordering  
@First Define a static result limit Jakarta Data 1.1
@Is Associate a parameter with a constraint Jakarta Data 1.1
@Select Define a projection Jakarta Data 1.1

Eclipse JNoSQL supports every annotation in the table; the examples below were checked against the Jakarta Data 1.1.0-M4 API and the JNoSQL repository tests. The 1.1 annotations require a JNoSQL release built on Jakarta Data 1.1. The one 1.1 option JNoSQL does not apply is nullOrdering on @OrderBy; do not rely on it.

Operation annotations

The examples use a custom ProductRepository that exposes only the operations it declares:

import jakarta.data.repository.By;
import jakarta.data.repository.Delete;
import jakarta.data.repository.Find;
import jakarta.data.repository.Insert;
import jakarta.data.repository.Repository;
import jakarta.data.repository.Save;
import jakarta.data.repository.Update;

@Repository
public interface ProductRepository {

    @Find
    List<Product> inCategory(@By("category") String category);

    @Insert
    Product insert(Product product);

    @Update
    Product update(Product product);

    @Save
    Product save(Product product);

    @Delete
    void delete(Product product);

    @Delete
    void deleteAll(List<Product> products);

    void deleteById(String id);

    long deleteByStock(int stock);
}
  • @Find retrieves entities that match the parameters. Each parameter maps to an entity attribute by name, or through @By. The method name is free. It may return the entity, Optional, an array, a List, a Stream, or a Page.
  • @Insert adds new entities. The method takes one entity, a List, or an array, and returns void or the same type it received. Which entity the repository manages is inferred from the signatures.
  • @Update modifies entities that already exist, matched by identifier, with the same parameter and return rules as @Insert.
  • @Save inserts or updates each entity depending on whether its identifier exists, with the same parameter and return rules.
  • @Delete removes the given entity or entities and returns void.

See insert, update, and save for how these behave across databases. deleteById and deleteByStock are not annotations but derived delete methods, the way to delete by identifier or another attribute value in a custom repository.

Query modifier annotations

These annotations refine @Find and @Query methods. They can be grouped in one repository:

import jakarta.data.constraint.AtMost;
import jakarta.data.constraint.GreaterThan;
import jakarta.data.constraint.Like;
import jakarta.data.repository.Is;
import jakarta.data.repository.First;
import jakarta.data.repository.OrderBy;
import jakarta.data.repository.Select;

@Repository
public interface ProductSearch {

    // @By: the parameter name does not have to match the attribute name
    @Find
    List<Product> inCategory(@By("category") String productCategory);

    // @OrderBy: repeatable, ascending unless descending = true
    @Find
    @OrderBy("category")
    @OrderBy(value = "price", descending = true)
    List<Product> catalog();

    // @First: a static limit of results
    @Find
    @First(10)
    @OrderBy(value = "price", descending = true)
    List<Product> tenMostExpensive();

    // @Select: returns a single attribute instead of the entity
    @Find(Product.class)
    @Select("name")
    List<String> names(@By("category") String category);

    // @Is: compare with a constraint instead of equality
    @Find
    List<Product> inStockAbove(@By("stock") @Is(GreaterThan.class) int minimum);

    @Find
    List<Product> pricedAtMost(@By("price") @Is(AtMost.class) BigDecimal maximum);

    @Find
    List<Product> search(@By("name") @Is(Like.class) String pattern);
}
  • @By maps a parameter to an entity attribute. Use @By(By.ID) to refer to the identifier regardless of its attribute name.
  • @OrderBy sorts results statically. Repeat it to sort by several attributes; earlier annotations take precedence.
  • @First returns at most the given number of results (default 1). tenMostExpensive combines it with @OrderBy to return the ten most expensive products. @First cannot be combined with a Limit or PageRequest parameter, or with the First keyword in a method name. Use the dynamic parameters described in Pagination and Special Parameters when the limit varies per call.
  • @Select returns one entity attribute, or several when the method returns a @Projection record. @Find(Product.class) names the entity when the return type does not identify it. See projections with @Query for a record example.
  • @Is compares an attribute with a Constraint such as GreaterThan, AtMost, or Like instead of equality, and works together with @By. See Constraints for the available constraints.

A projection record looks like this:

import jakarta.nosql.Projection;

@Projection
public record ProductSummary(String name, BigDecimal price) {
}

@Find(Product.class)
@Select("name")
@Select("price")
List<ProductSummary> summaries(@By("category") String category);

Not every database can filter by an arbitrary attribute or sort; see Database Capabilities.

Query Methods

Query methods retrieve entities by criteria. Jakarta Data offers two approaches: derived queries built from the method name, and explicit queries written with @Query. A third option, parameter-based @Find methods, is covered in Repository Annotations.

Support for queries beyond lookup by identifier depends on the capabilities of the underlying database model and provider; a Key-Value database, for instance, does not generally support querying by arbitrary attributes. See Database Capabilities.

Derived queries

Jakarta Data derives the query from the method name: a prefix such as findBy, the entity attributes, and keywords that describe the comparison. findByName and findByPriceLessThan are derived queries:

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    List<Product> findByName(String name);

    List<Product> findByPriceLessThan(BigDecimal price);

    List<Product> findByCategoryAndStockGreaterThan(String category, int stock);

    List<Product> findByPriceBetween(BigDecimal minimum, BigDecimal maximum);

    List<Product> findByCategoryIn(List<String> categories);

    List<Product> findByNameStartsWith(String prefix);

    List<Product> findByCategoryOrderByPriceDesc(String category);

    List<Product> findFirst10ByCategoryOrderByPriceDesc(String category);

    long countByCategory(String category);

    boolean existsByName(String name);

    void deleteByCategory(String category);
}
Pattern Keyword Example
Equality none, or Equals findByName(String name)
Not equal NotEquals findByNameNotEquals(String name)
Less than LessThan, LessThanEqual findByPriceLessThan(BigDecimal price)
Greater than GreaterThan, GreaterThanEqual findByStockGreaterThan(int stock)
Range Between findByPriceBetween(BigDecimal minimum, BigDecimal maximum)
Membership In findByCategoryIn(List<String> categories)
Text matching Like, Contains, StartsWith, EndsWith findByNameStartsWith(String prefix)
Combine conditions And, Or findByCategoryAndStockGreaterThan(String category, int stock)
Ordering OrderBy, with Asc or Desc findByCategoryOrderByPriceDesc(String category)
Limit results First, optionally with a number findFirst10ByCategoryOrderByPriceDesc(String category)
Count countBy countByCategory(String category)
Existence existsBy existsByName(String name)
Delete deleteBy deleteByCategory(String category)

Parameters are passed in the order the attributes appear in the method name, and Between takes two. Calling them is ordinary Java:

List<Product> cheap = repository.findByPriceLessThan(new BigDecimal("20.00"));
List<Product> restock = repository.findByCategoryAndStockGreaterThan("peripherals", 10);
List<Product> topTen = repository.findFirst10ByCategoryOrderByPriceDesc("peripherals");
long peripherals = repository.countByCategory("peripherals");
repository.deleteByCategory("discontinued");

Method names become hard to read as conditions are added. When a name grows long, switch to @Query or @Find, or build the criteria with Restrictions. A method name cannot be combined with @First: use the First keyword or the annotation.

Explicit queries with @Query

Annotate a method with @Query to write the query yourself. Use named parameters such as :category, bound with @Param, or ordinal parameters such as ?1; the two styles cannot be mixed in one query.

import jakarta.data.repository.Param;
import jakarta.data.repository.Query;

@Repository
public interface ProductQueries extends BasicRepository<Product, String> {

    // A simple WHERE query with a named parameter
    @Query("FROM Product WHERE category = :category")
    List<Product> inCategory(@Param("category") String category);

    // Multiple predicates
    @Query("FROM Product WHERE category = :category AND stock < :stock AND price <= :price")
    List<Product> lowStockInCategory(@Param("category") String category,
                                     @Param("stock") int stock,
                                     @Param("price") BigDecimal price);

    // Ordering, with an ordinal parameter
    @Query("FROM Product WHERE category = ?1 ORDER BY price DESC, name")
    List<Product> inCategoryByPrice(String category);

    // A projection of one attribute
    @Query("SELECT name FROM Product WHERE category = :category")
    List<String> names(@Param("category") String category);

    // A projection of several attributes into a record
    @Query("SELECT name, price FROM Product WHERE category = :category")
    List<ProductSummary> summaries(@Param("category") String category);

    // Update and delete statements
    @Query("UPDATE Product SET price = :price WHERE id = :id")
    void updatePrice(@Param("id") String id, @Param("price") BigDecimal price);

    @Query("DELETE FROM Product WHERE stock = 0")
    void removeOutOfStock();
}

ProductSummary is the @Projection record shown in Repository Annotations. A SELECT query returns the entity, a single attribute, or a record; update and delete queries return void. The FROM clause may be omitted when the entity is known from the repository, and @First can limit the results of a query; see Repository Annotations.

Jakarta Data 1.0 introduced the Jakarta Data Query Language (JDQL) for these strings. From Jakarta Data 1.1 the query language is the Jakarta Common Query Language (JCQL), defined by the Jakarta Query specification so that Jakarta Data and Jakarta NoSQL share one language. A provider is not required to support the entire language, and the database decides what it can execute. See Jakarta Query for the language and Database Capabilities for what each database model offers.

Pagination

A query that matches many products should not load them all into memory: it wastes memory and network bandwidth and makes the application slow. Pagination retrieves the result in small slices instead. Jakarta Data supports offset-based pagination, where a request selects a page, and cursor-based pagination, where a request continues after the key values of a known result.

Characteristic Offset pagination Cursor pagination
Navigation Page or offset-based Cursor-based
Random page access Generally available Generally sequential
Large datasets May become expensive for deep offsets Can be more efficient with suitable indexing
Ordering Recommended deterministic ordering Requires suitable deterministic ordering
Typical scenario Administrative screens Large feeds and continuous navigation

Actual performance depends on the database implementation, its indexes, the shape of the query and the capabilities of the provider. Cursor pagination is not always faster, and it does not provide snapshot isolation. See the database guides for provider behavior.

Offset pagination

  1. 7
  2. 8
  3. 9
  4. 10
  5. 11
  6. 12

The earlier results are skipped to reach the requested page.

Cursor pagination

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12

The query continues after the key values of a known position.

SkippedCursor positionReturned page

Offset pagination

A repository method that accepts a PageRequest and returns a Page retrieves one page of the result. The request carries the page number (starting at 1) and the maximum page size:

import jakarta.data.Order;
import jakarta.data.page.Page;
import jakarta.data.page.PageRequest;
import jakarta.data.repository.BasicRepository;
import jakarta.data.repository.Repository;

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    Page<Product> findByCategory(String category, PageRequest pageRequest, Order<Product> order);
}

The caller creates the first request with PageRequest.ofSize(20), or selects another page with PageRequest.ofPage(3, 20, false) (page number, page size, whether totals are requested). nextPageRequest() returns the request for the following page:

Order<Product> byPrice = Order.by(_Product.price.asc(), _Product.id.asc());

Page<Product> page = products.findByCategory("peripherals", PageRequest.ofSize(20), byPrice);

List<Product> content = page.content();
if (page.hasNext()) {
    Page<Product> second = products.findByCategory("peripherals", page.nextPageRequest(), byPrice);
}

_Product is the generated static metamodel. nextPageRequest() and previousPageRequest() throw NoSuchElementException when there is no such page, so check hasNext() and hasPrevious() first.

A Page provides the content through content(), hasContent(), stream() and numberOfElements(), and navigation through hasNext() and hasPrevious(). totalElements() and totalPages() are available only when the request asked for totals, which is the default for ofPage(long) and ofSize(int). Counting the total is an additional operation, so a request that does not need it should call withoutTotal(). Check hasTotals() before reading totals, because totalElements() throws IllegalStateException if they are unavailable:

Page<Product> feed = products.findByCategory("peripherals", PageRequest.ofSize(20).withoutTotal(), byPrice);
boolean totalsAvailable = feed.hasTotals(); // false: no count was requested

long total = page.hasTotals() ? page.totalElements() : -1; // 'page' was requested with totals

Without totals, Eclipse JNoSQL reports hasNext() as true when the page is full, so the last page can be followed by an empty one.

Cursor pagination

A cursor identifies a position in an ordered result by the values of its sort attributes, such as the price and identifier of the last product returned. The next page starts after that position, so the database does not have to skip earlier results. The method returns a CursoredPage, and the sort order must be deterministic, which is why the identifier acts as a tie-breaker for products with the same price:

import jakarta.data.page.CursoredPage;
import jakarta.data.repository.By;
import jakarta.data.repository.Find;
import jakarta.data.repository.OrderBy;

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    @Find
    @OrderBy(_Product.PRICE)
    @OrderBy(_Product.ID)
    CursoredPage<Product> inCategory(@By(_Product.CATEGORY) String category, PageRequest pageRequest);
}

The first request is created with PageRequest.ofSize(50). The page returns the request for the following page with nextPageRequest(), which already carries the cursor:

CursoredPage<Product> page = products.inCategory("peripherals", PageRequest.ofSize(50));

while (true) {
    // handle page.content()
    if (!page.hasNext()) {
        break;
    }
    page = products.inCategory("peripherals", page.nextPageRequest());
}

page.cursor(index) returns the cursor of one result. A request can also be built from known key values, which must match the sort attributes in number and order: PageRequest.ofSize(50).afterCursor(PageRequest.Cursor.forKey(new BigDecimal("49.90"), "P-100")). Use beforeCursor to navigate backwards.

Keep in mind:

  • The ordering must be deterministic. Without a unique tie-breaker, results that share the same sort values can be skipped or repeated between pages.
  • Sorting by price and identifier works efficiently only with a suitable index on those attributes.
  • Concurrent inserts, updates and deletes can change what later pages contain. Neither pagination style guarantees a consistent snapshot.
  • Eclipse JNoSQL disables cursor pagination with more than one sort attribute by default, because sorting by several attributes can be unstable in some NoSQL databases. A method such as inCategory fails with UnsupportedOperationException unless the org.eclipse.jnosql.pagination.cursor property is true, for example in META-INF/microprofile-config.properties:
org.eclipse.jnosql.pagination.cursor=true

A cursor method must receive a PageRequest; otherwise JNoSQL throws IllegalArgumentException.

Special Parameters

Special parameters are method arguments that control how a repository query executes. They are not query values: a repository method recognizes them by their type.

Parameter Purpose
Limit Restrict the number or range of returned results
Sort Specify dynamic sorting
Order Combine multiple sorting criteria
PageRequest Request paginated results
Restriction Since Jakarta Data 1.1 Supply dynamic filtering expressions

These are the special parameters of Jakarta Data 1.1; JNoSQL recognizes the same types. The examples use the Product repository.

Limit

Limit restricts the results at call time. Limit.of(10) returns at most ten results, and Limit.range(11, 20) returns the results from the 11th to the 20th (positions start at 1):

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    List<Product> findByCategory(String category, Limit limit);
}
List<Product> firstTen = products.findByCategory("peripherals", Limit.of(10));
List<Product> secondTen = products.findByCategory("peripherals", Limit.range(11, 20));

@First is the static, annotation-based counterpart; see Repository Annotations. Use @First when the number is fixed and Limit when the caller decides.

Sort

Sort<Product> chooses one ordering attribute without changing the method. Use the metamodel attributes, or the Sort.asc and Sort.desc factories with an attribute name:

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    List<Product> findByCategory(String category, Sort<Product> sort);
}
List<Product> cheapestFirst = products.findByCategory("peripherals", _Product.price.asc());
List<Product> expensiveFirst = products.findByCategory("peripherals", _Product.price.desc());
List<Product> byNameIgnoringCase = products.findByCategory("peripherals", _Product.name.ascIgnoreCase());
List<Product> byPriceAgain = products.findByCategory("peripherals", Sort.<Product>asc(_Product.PRICE));

Order

Order<Product> combines several Sort criteria, applied in sequence. Ordering by price and then by identifier makes the result deterministic, because the identifier breaks ties between products with the same price:

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    List<Product> findByCategory(String category, Order<Product> order);
}
List<Product> ordered = products.findByCategory("peripherals", Order.by(_Product.price.asc(), _Product.id.asc()));

Deterministic ordering matters for any repeatable result, and it is required for pagination.

PageRequest

PageRequest selects a page of the result. See Offset pagination and Cursor pagination for the complete examples.

Restriction

Since Jakarta Data 1.1

Restriction<Product> supplies a dynamic filter built at call time. A short example with the metamodel:

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    @Find
    List<Product> matching(Restriction<Product> restriction);
}
List<Product> affordable = products.matching(_Product.price.lessThan(new BigDecimal("100")));

See Restrictions for expressions and composition.

Combining special parameters

A method can combine filtering, sorting and pagination. Static ordering from @OrderBy or the method name applies first, followed by dynamic Sort and Order arguments:

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    @Find
    Page<Product> search(Restriction<Product> restriction, PageRequest pageRequest, Order<Product> order);
}
Combination Status
Sort with Order Allowed. The criteria are applied in the order they are declared. The database must be able to sort.
Restriction with Sort or Order Supported, as in the example above.
Restriction with offset pagination Supported (PageRequest and Page).
Restriction with cursor pagination Supported when the method declares the ordering, for example with @OrderBy.
Limit with PageRequest Not allowed by the specification.
@First with Limit, PageRequest or the First keyword Not allowed by the specification.
Two Limit arguments Not allowed by the specification.

Eclipse JNoSQL does not report the prohibited combinations as errors. It silently gives @First priority over Limit, and Limit priority over PageRequest. Do not rely on that behavior. Not every possible combination is supported, and a database that cannot perform an operation, such as sorting, may reject it.

Constraints

Since Jakarta Data 1.1

Constraints express a condition on a value or attribute with a typed Java object from jakarta.data.constraint, instead of a name-based keyword or a query string. A constraint describes only the condition; the attribute it applies to comes from the repository method or from a Restriction.

Constraint Meaning Java example
EqualTo Equal to a value EqualTo.value("Keyboard")
NotEqualTo Different from a value NotEqualTo.value("Keyboard")
GreaterThan Greater than a value GreaterThan.bound(BigDecimal.TEN)
LessThan Less than a value LessThan.bound(BigDecimal.TEN)
AtLeast Greater than or equal to a value AtLeast.min(new BigDecimal("50"))
AtMost Less than or equal to a value AtMost.max(new BigDecimal("200"))
Between Within a range Between.bounds(new BigDecimal("50"), new BigDecimal("200"))
NotBetween Outside a range NotBetween.bounds(BigDecimal.ONE, BigDecimal.TEN)
In Included in a collection In.values("peripherals", "audio")
NotIn Not included in a collection NotIn.values("legacy", "discontinued")
Like Matches a pattern Like.pattern("%board%"), Like.prefix("Key")
NotLike Does not match a pattern NotLike.suffix("old")
Null Is null Null.instance(), or expirationDate.isNull()
NotNull Is not null NotNull.instance(), or expirationDate.notNull()

Each constraint is an interface with static factory methods, and a metamodel attribute also provides the equivalent expression methods used with Restrictions. Like patterns use % for any string and _ for any single character by default; Like.pattern(pattern, charWildcard, stringWildcard, escape) changes them.

Constraint parameters

A repository method can accept a constraint as an argument, which lets the caller choose the condition. The parameter is bound to an attribute with @By:

import jakarta.data.constraint.AtLeast;
import jakarta.data.constraint.AtMost;
import jakarta.data.constraint.Between;
import jakarta.data.constraint.In;
import jakarta.data.constraint.Like;

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    @Find
    List<Product> priceAtLeast(@By(_Product.PRICE) AtLeast<BigDecimal> price);

    @Find
    List<Product> priceAtMost(@By(_Product.PRICE) AtMost<BigDecimal> price);

    @Find
    List<Product> priceBetween(@By(_Product.PRICE) Between<BigDecimal> price);

    @Find
    List<Product> inCategories(@By(_Product.CATEGORY) In<String> categories);

    @Find
    List<Product> nameLike(@By(_Product.NAME) Like name);
}

The caller constructs the constraints:

products.priceAtLeast(AtLeast.min(new BigDecimal("50")));
products.priceAtMost(AtMost.max(new BigDecimal("200")));
products.priceBetween(Between.bounds(new BigDecimal("50"), new BigDecimal("200")));
products.inCategories(In.values("peripherals", "audio"));
products.nameLike(Like.pattern("%board%"));

Eclipse JNoSQL supports EqualTo, NotEqualTo, GreaterThan, LessThan, AtLeast, AtMost, Between, NotBetween, In, NotIn, Like and NotLike as @By parameters, with literal values only. Null and NotNull are not accepted as parameters; use isNull() and notNull() in a Restriction instead.

The @Is annotation

@Is is a parameter annotation that states which constraint a parameter represents, so that the parameter keeps its ordinary Java type. Without it, a parameter means equality. This method finds products priced at or above the given value:

import jakarta.data.constraint.AtLeast;
import jakarta.data.constraint.In;
import jakarta.data.repository.Is;

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    @Find
    List<Product> priceFrom(@By(_Product.PRICE) @Is(AtLeast.class) BigDecimal minimum);

    @Find
    List<Product> inNames(@By(_Product.NAME) @Is(In.class) List<String> names);
}
List<Product> products = repository.priceFrom(new BigDecimal("50"));

JNoSQL applies @Is on @Find methods for the same twelve constraints as constraint parameters. It is not available for Null and NotNull. See Repository Annotations for the other parameter annotations.

Restrictions

Since Jakarta Data 1.1

A Restriction<Product> is a dynamic, composable query predicate. It associates an expression, such as an attribute of the static metamodel, with a condition, and several restrictions can be combined with AND, OR and negation. Constraints and restrictions differ in what they carry:

  • A constraint describes a condition, such as "at least 50", and has no attribute of its own.
  • A restriction applies a condition to an expression, such as price at least 50, and can be composed with other restrictions.

Restrictions suit search forms, optional filters and business rules that change at runtime: the repository method stays the same, and the caller decides which conditions apply. A repository accepts a restriction as a special parameter.

Constraints, restrictions, @Is and @First belong to Jakarta Data 1.1, so they need an Eclipse JNoSQL release built on Jakarta Data 1.1. The 1.2.0 release used elsewhere in this documentation is built on Jakarta Data 1.0, and the advanced expressions below are available only in builds that include them.

Generating the static metamodel

Type-safe restrictions use the static metamodel: a generated class with one typed attribute for each entity field. Eclipse JNoSQL generates it with an annotation processor. Add the processor to the project:

<dependency>
    <groupId>org.eclipse.jnosql.metamodel</groupId>
    <artifactId>mapping-metamodel-processor</artifactId>
    <version>${jnosql.version}</version>
    <scope>provided</scope>
</dependency>

jnosql.version is a property of your build that names an Eclipse JNoSQL release built on Jakarta Data 1.1 (such as 2.0.0-M1, the first release that generates Jakarta Data 1.1 attributes). The processor reads the classes annotated with @Entity or @MappedSuperclass and declares Java 21 as its supported source version. A normal Maven build runs it:

mvn compile

The generated sources are written to target/generated-sources/annotations. For Product, the processor generates the interface _Product in the same package (the entity name with an underscore prefix):

@StaticMetamodel(Product.class)
public interface _Product {

    String ID = "_id";
    String NAME = "name";
    String PRICE = "price";
    String STOCK = "stock";
    String MINIMUMSTOCK = "minimumStock";
    String CATEGORY = "category";
    String EXPIRATIONDATE = "expirationDate";

    TextAttribute<Product> id = TextAttribute.of(Product.class, ID);
    TextAttribute<Product> name = TextAttribute.of(Product.class, NAME);
    NumericAttribute<Product, BigDecimal> price = NumericAttribute.of(Product.class, PRICE, BigDecimal.class);
    NumericAttribute<Product, Integer> stock = NumericAttribute.of(Product.class, STOCK, int.class);
    NumericAttribute<Product, Integer> minimumStock = NumericAttribute.of(Product.class, MINIMUMSTOCK, int.class);
    TextAttribute<Product> category = TextAttribute.of(Product.class, CATEGORY);
    TemporalAttribute<Product, LocalDate> expirationDate =
            TemporalAttribute.of(Product.class, EXPIRATIONDATE, LocalDate.class);
}

The String constants name the attributes, for example in @By(_Product.CATEGORY), and the typed fields build restrictions and sorting, as in _Product.price.lessThan(...). Import the generated class from the entity package and use its members directly. Do not edit generated classes by hand or commit them: they are regenerated on every build.

The processor available when this page was written generates a _Product that does not compile for java.time fields such as expirationDate (it references NavigableAttribute without importing it). If you hit this, verify against the current processor release, or declare the metamodel by hand, because a @StaticMetamodel interface has the shape shown above. See the JNoSQL static metamodel documentation for further setup details.

Basic restrictions

A restriction is built from a metamodel attribute and a condition. These examples use the matching method from Special Parameters:

import jakarta.data.restrict.Restriction;

Restriction<Product> keyboards = _Product.name.equalTo("Keyboard");
Restriction<Product> cheap = _Product.price.lessThan(new BigDecimal("100"));
Restriction<Product> inStock = _Product.stock.greaterThan(0);
Restriction<Product> sold = _Product.category.in("peripherals", "audio");
Restriction<Product> noExpiration = _Product.expirationDate.isNull();

List<Product> products = repository.matching(cheap);

The other conditions of the constraint table are available with the same style:

_Product.name.notEqualTo("Keyboard");
_Product.price.greaterThanEqual(new BigDecimal("10"));   // AtLeast
_Product.price.lessThanEqual(new BigDecimal("10"));      // AtMost
_Product.price.between(BigDecimal.TEN, BigDecimal.valueOf(50));
_Product.price.notBetween(BigDecimal.TEN, BigDecimal.valueOf(50));
_Product.category.notIn("legacy", "discontinued");
_Product.name.like("Key%");
_Product.name.notLike("Key%");
_Product.expirationDate.notNull();
_Product.price.satisfies(AtLeast.min(BigDecimal.TEN));   // any Constraint

TextExpression also provides contains, startsWith and endsWith. A repository accepts a Restriction as a parameter. A standard repository method needs @Find; a custom @Query method can combine its own conditions with the restriction:

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    @Find
    List<Product> matching(Restriction<Product> restriction);

    @Find
    List<Product> withName(@By(_Product.NAME) String name, Restriction<Product> restriction);

    @Query("WHERE name = :name")
    List<Product> byName(@Param("name") String name, Restriction<Product> restriction);
}

The restriction is combined with the other conditions of the method using AND. A @Delete method can also accept a Restriction, but the provider must implement it; by default Eclipse JNoSQL throws UnsupportedOperationException for it.

Composite restrictions

Restrict combines restrictions. Restrict.all is AND, Restrict.any is OR, and Restrict.not (or negate()) negates. This search finds products in a category that cost less than a maximum and are in stock:

import jakarta.data.restrict.Restrict;

Restriction<Product> search = Restrict.all(
        _Product.category.equalTo(category),
        _Product.price.lessThan(maxPrice),
        _Product.stock.greaterThan(0));

Restriction<Product> audioOrVideo = Restrict.any(
        _Product.category.equalTo("audio"),
        _Product.category.equalTo("video"));

Restriction<Product> notLegacy = Restrict.not(_Product.category.equalTo("legacy"));
Restriction<Product> sameThing = _Product.category.equalTo("legacy").negate();

Restriction<Product> nested = Restrict.all(
        _Product.stock.greaterThan(0),
        Restrict.any(_Product.category.equalTo("audio"), _Product.price.lessThan(BigDecimal.TEN)));

For optional filters, collect only the restrictions the caller supplied. Restrict.all rejects an empty list, so use Restrict.unrestricted() when no filter applies:

List<Restriction<Product>> filters = new ArrayList<>();
if (nameFilter != null) {
    filters.add(_Product.name.contains(nameFilter));
}
if (maxPrice != null) {
    filters.add(_Product.price.lessThanEqual(maxPrice));
}

Restriction<Product> restriction = filters.isEmpty() ? Restrict.unrestricted() : Restrict.all(filters);
List<Product> found = repository.matching(restriction);

Advanced expressions

Eclipse JNoSQL converts restrictions that use expressions: functions, arithmetic, and comparisons between attributes. Expressions can appear on both sides of a comparison.

Feature Example meaning
Attribute comparison Stock is below minimum stock
ABS Absolute numeric value
LENGTH Product name length
LOWER Lowercase product name
UPPER Uppercase product name
LEFT First characters of a name
RIGHT Last characters of a name
Addition Add a value to an attribute
Subtraction Calculate the difference between attributes
Multiplication Calculate a scaled or combined value
Division Calculate a numeric ratio
Numeric negation Negate a numeric expression
CONCAT Combine strings
Temporal expressions Compare a date with the current date
LIKE ESCAPE Match literal wildcard characters
// Attribute comparison: stock < minimumStock
_Product.stock.lessThan(_Product.minimumStock);

// ABS(stock - minimumStock) > 10
_Product.stock.minus(_Product.minimumStock).abs().greaterThan(10);

// Functions on text
_Product.name.upper().equalTo("KEYBOARD");
_Product.name.lower().equalTo("keyboard");
_Product.name.length().greaterThan(10);
_Product.name.left(3).equalTo("Key");
_Product.name.right(3).equalTo("oard");

// Arithmetic
_Product.stock.plus(5).greaterThan(_Product.minimumStock);
_Product.stock.minus(_Product.minimumStock).lessThan(0);
_Product.price.times(new BigDecimal("1.2")).lessThan(new BigDecimal("100"));
_Product.stock.times(_Product.minimumStock).greaterThan(100);
_Product.price.dividedBy(new BigDecimal("2")).greaterThan(BigDecimal.TEN);
_Product.stock.negated().lessThan(0);

// CONCAT: append and prepend
_Product.name.append(" Pro").equalTo("Keyboard Pro");
_Product.category.prepend("cat-").equalTo("cat-audio");

// expirationDate < current date
_Product.expirationDate.lessThan(TemporalExpression.localDate());

// LIKE with an escape character: names starting with "100%"
_Product.name.like("100!%%", '%', '_', '!');

Operands of an arithmetic method must have the attribute's Java type: price is a BigDecimal, so it is multiplied by a BigDecimal or another BigDecimal expression, and stock and minimumStock are both Integer. Combining attributes of different numeric types needs a numeric cast (asBigDecimal() and the like), which Eclipse JNoSQL does not support. Result types follow the operands: abs(), plus and minus keep the type of the attribute. Use the TemporalExpression factories localDate(), localDateTime() and localTime() for the current date and time. The expressions are not translated from JCQL text: each one is a method of the Jakarta Data expression API.

Restrictions with special parameters

A restriction combines with sorting and offset pagination in one method. The caller supplies all three. See Special Parameters and Offset pagination:

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    @Find
    Page<Product> search(Restriction<Product> restriction, PageRequest pageRequest, Order<Product> order);
}
Page<Product> page = repository.search(
        Restrict.all(_Product.category.equalTo("peripherals"), _Product.stock.greaterThan(0)),
        PageRequest.ofPage(1, 20, false),
        Order.by(_Product.price.asc(), _Product.id.asc()));

With cursor pagination the method declares its ordering and returns a CursoredPage. See Cursor pagination, including its note about the org.eclipse.jnosql.pagination.cursor property:

@Find
@OrderBy(_Product.PRICE)
@OrderBy(_Product.ID)
CursoredPage<Product> searchCursor(Restriction<Product> restriction, PageRequest pageRequest);
CursoredPage<Product> page = repository.searchCursor(
        _Product.stock.greaterThan(0), PageRequest.ofSize(20));
if (page.hasNext()) {
    page = repository.searchCursor(_Product.stock.greaterThan(0), page.nextPageRequest());
}

Use the same restriction for every page of a cursor sequence.

Database capabilities and limitations

Restriction expressions run through the query capabilities of Eclipse JNoSQL. An expression that does not depend on stored attributes, such as "abc".upper(), is evaluated by JNoSQL. An expression that does, such as UPPER(name), needs native support from the database. A database without that operation rejects the restriction with UnsupportedOperationException. Check the Jakarta Query compatibility reference for the operations each database supports.

Further restrictions that matter to applications:

  • Numeric casts (asLong(), asDouble(), asBigInteger(), asBigDecimal()) are not supported.
  • A temporal expression can be compared with an attribute, as in the example above, but it cannot be used as the argument of a function.
  • A LIKE pattern must be a value that does not depend on stored attributes, and wildcard handling depends on the database.
  • The left side of a comparison must be a stored attribute or a native function. A condition made only of independent values, or an IN test on an independent value, is rejected.
  • Nested attribute paths work only where the entity mapping and the database support them.

Restrictions and Jakarta Query

The typed API and the declarative query language express the same conditions. Choose whichever suits the code. Both repositories below return the products whose stock is below the minimum; the second pair uses a nested arithmetic expression:

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    @Find
    List<Product> matching(Restriction<Product> restriction);

    @Query("WHERE stock < minimumStock")
    List<Product> belowMinimum();

    @Query("WHERE ABS(stock - minimumStock) > 10")
    List<Product> farFromMinimum();
}
repository.matching(_Product.stock.lessThan(_Product.minimumStock));                       // = belowMinimum()
repository.matching(_Product.stock.minus(_Product.minimumStock).abs().greaterThan(10));   // = farFromMinimum()

See Jakarta Query for the language.

Provider-Specific Repositories

JNoSQL Extension

Eclipse JNoSQL provides repository interfaces for databases with their own query languages. Extend the appropriate interface and use the provider's native query annotation when a standard Jakarta Query expression is insufficient.

These repositories preserve the familiar Jakarta Data programming model while allowing access to database-specific query capabilities. They are different from NoSQLRepository, which is a general-purpose repository that works with any JNoSQL database.

Database Repository Native annotation Module
ArangoDB ArangoDBRepository @AQL jnosql-arangodb
Cassandra CassandraRepository @CQL jnosql-cassandra
Couchbase CouchbaseRepository @N1QL jnosql-couchbase
DynamoDB DynamoDBRepository @PartiQL jnosql-dynamodb
Neo4j Neo4JRepository @Cypher jnosql-neo4j
Oracle NoSQL OracleNoSQLRepository @SQL jnosql-oracle-nosql
OrientDB OrientDBCrudRepository @SQL jnosql-orientdb
ScyllaDB ScyllaDBRepository @CQL jnosql-scylladb
Solr SolrRepository @Solr jnosql-solr
Apache TinkerPop TinkerPopRepository @Gremlin jnosql-tinkerpop

Each interface adds no methods of its own: it enables the provider's native query annotation on its repository methods. The modules belong to JNoSQL Databases (group org.eclipse.jnosql.databases); the packages appear in the imports of the examples below.

How to use them

  1. Add the database driver dependency. The artifact changes with the provider; use the module from the table above. For Cassandra:

     <dependency>
         <groupId>org.eclipse.jnosql.databases</groupId>
         <artifactId>jnosql-cassandra</artifactId>
         <version>1.2.0</version>
     </dependency>
    
  2. Extend the provider-specific repository instead of BasicRepository.
  3. Declare a native query with the provider's annotation and bind parameters with @Param, using the parameter syntax of that query language.

Configure the database as described in its guide: Document, Wide-Column or Graph. The examples follow the driver sources and tests. Each provider has its own annotation package, so import the annotation that matches your driver.

ArangoDB

Query language: AQL, with @name parameters. See the Document guide.

import jakarta.data.repository.Param;
import jakarta.data.repository.Repository;
import org.eclipse.jnosql.databases.arangodb.mapping.AQL;
import org.eclipse.jnosql.databases.arangodb.mapping.ArangoDBRepository;

@Repository
public interface ArangoProducts extends ArangoDBRepository<Product, String> {

    @AQL("FOR p IN Product FILTER p.category == @category RETURN p")
    List<Product> inCategory(@Param("category") String category);
}

Cassandra

Query language: CQL, with :name parameters, using the BankTransaction entity of the Wide-Column guide.

import jakarta.data.repository.Param;
import jakarta.data.repository.Repository;
import org.eclipse.jnosql.databases.cassandra.mapping.CQL;
import org.eclipse.jnosql.databases.cassandra.mapping.CassandraRepository;

@Repository
public interface TransactionsByAccount
        extends CassandraRepository<BankTransaction, String> {

    @CQL("select * from bank_transaction where account_id = :accountId")
    List<BankTransaction> ofAccount(
            @Param("accountId") String accountId);
}

Couchbase

Query language: N1QL, with $name parameters. See the Document guide.

import jakarta.data.repository.Param;
import jakarta.data.repository.Repository;
import org.eclipse.jnosql.databases.couchbase.mapping.CouchbaseRepository;
import org.eclipse.jnosql.databases.couchbase.mapping.N1QL;

@Repository
public interface CouchbaseProducts extends CouchbaseRepository<Product, String> {

    @N1QL("select * from Product where category = $category")
    List<Product> inCategory(@Param("category") String category);
}

DynamoDB

Query language: PartiQL, with positional ? parameters bound with @Param(""). The driver supports only a subset of PartiQL. See the Document guide.

import jakarta.data.repository.Param;
import jakarta.data.repository.Repository;
import org.eclipse.jnosql.databases.dynamodb.mapping.DynamoDBRepository;
import org.eclipse.jnosql.databases.dynamodb.mapping.PartiQL;

@Repository
public interface DynamoProducts extends DynamoDBRepository<Product, String> {

    @PartiQL("select * from Product where category = ?")
    List<Product> inCategory(@Param("") String category);
}

Neo4j

Query language: Cypher, with $name parameters, using a small Person entity. See the Graph guide.

import jakarta.data.repository.Param;
import jakarta.data.repository.Repository;
import org.eclipse.jnosql.databases.neo4j.mapping.Cypher;
import org.eclipse.jnosql.databases.neo4j.mapping.Neo4JRepository;

@Repository
public interface Contacts extends Neo4JRepository<Person, String> {

    @Cypher("MATCH (p:Person) WHERE p.name = $name RETURN p")
    List<Person> named(@Param("name") String name);
}

Oracle NoSQL

Query language: SQL, with positional ? parameters bound with @Param(""). See the Document guide.

import jakarta.data.repository.Param;
import jakarta.data.repository.Repository;
import org.eclipse.jnosql.databases.oracle.mapping.OracleNoSQLRepository;
import org.eclipse.jnosql.databases.oracle.mapping.SQL;

@Repository
public interface OracleProducts extends OracleNoSQLRepository<Product, String> {

    @SQL("select * from Product where category = ?")
    List<Product> inCategory(@Param("") String category);
}

OrientDB

Query language: SQL, with :name parameters. This @SQL annotation is a different type from the Oracle NoSQL one. See the Document guide.

import jakarta.data.repository.Param;
import jakarta.data.repository.Repository;
import org.eclipse.jnosql.databases.orientdb.mapping.OrientDBCrudRepository;
import org.eclipse.jnosql.databases.orientdb.mapping.SQL;

@Repository
public interface OrientProducts extends OrientDBCrudRepository<Product, String> {

    @SQL("select * from Product where category = :category")
    List<Product> inCategory(@Param("category") String category);
}

ScyllaDB

Query language: CQL, with :name parameters. The @CQL annotation is in the ScyllaDB package, not the Cassandra one. See the Wide-Column guide.

import jakarta.data.repository.Param;
import jakarta.data.repository.Repository;
import org.eclipse.jnosql.databases.scylladb.mapping.CQL;
import org.eclipse.jnosql.databases.scylladb.mapping.ScyllaDBRepository;

@Repository
public interface ScyllaTransactions
        extends ScyllaDBRepository<BankTransaction, String> {

    @CQL("select * from bank_transaction where account_id = :accountId")
    List<BankTransaction> ofAccount(
            @Param("accountId") String accountId);
}

Solr

Query language: Solr query syntax, with @name parameters. SolrRepository uses its own Param annotation instead of the Jakarta Data one. See the Document guide.

import jakarta.data.repository.Repository;
import org.eclipse.jnosql.databases.solr.mapping.Param;
import org.eclipse.jnosql.databases.solr.mapping.Solr;
import org.eclipse.jnosql.databases.solr.mapping.SolrRepository;

@Repository
public interface SolrProducts extends SolrRepository<Product, String> {

    @Solr("category:@category AND _entity:Product")
    List<Product> inCategory(@Param("category") String category);
}

Apache TinkerPop

Query language: Gremlin, with @name parameters, using the Person entity. See the Graph guide.

import jakarta.data.repository.Param;
import jakarta.data.repository.Repository;
import org.eclipse.jnosql.databases.tinkerpop.mapping.Gremlin;
import org.eclipse.jnosql.databases.tinkerpop.mapping.TinkerPopRepository;

@Repository
public interface People extends TinkerPopRepository<Person, String> {

    @Gremlin("g.V().hasLabel('Person').has('name', @name)")
    List<Person> named(@Param("name") String name);
}

The caller invokes these methods like any other repository method:

List<Product> peripherals = couchbaseProducts.inCategory("peripherals");
List<BankTransaction> transactions = transactionsByAccount.ofAccount("account-123");
List<Person> matches = contacts.named("Ada");

Portability

  • Standard Jakarta Data repositories provide a portable programming model.
  • Provider-specific repositories enable native queries.
  • Native queries are tied to the selected database and its query language.
  • Vector search, temporal operations and other template-specific capabilities are not repository methods; see Capabilities by database model.

For the standardized query capabilities of each database, see the Jakarta Query compatibility reference.

Capabilities by Database Model

A standardized repository API does not mean every database offers the same capabilities. The repository interface stays the same, but whether a method succeeds, and how efficiently, depends on the database model and provider. Jakarta Data query capabilities depend on the underlying database, and the Jakarta Query compatibility reference in JNoSQL Databases lists what each database supports. It also applies to the equivalent Restriction expressions. This page does not repeat its tables.

Key-Value

Key-Value databases are built around identifier-based persistence and efficient retrieval by key. Pure key-value drivers generally cannot filter by arbitrary attributes, so derived queries on other attributes are generally unavailable. Use save, findById and deleteById:

@Repository
public interface UserSessionRepository extends BasicRepository<UserSession, String> {
}
repository.save(new UserSession("s-1", "alice", Instant.now()));
Optional<UserSession> session = repository.findById("s-1");

See the Key-Value guide.

Wide-Column

Wide-Column data is modeled around queries. A table is organized by a partition key and optional clustering columns, and a query that does not follow that design may be rejected or inefficient. Filtering on other columns may require a secondary index or another provider-specific indexing mechanism, and the databases differ in their indexing models. Sorting, range predicates and aggregation are restricted, too.

With the BankTransaction mapping of the Wide-Column guide, a lookup by account relies on the index created in that guide. In a table whose partition key is account_id, the same method is a partition lookup:

@Repository
public interface BankTransactionRepository extends BasicRepository<BankTransaction, String> {

    List<BankTransaction> findByAccountId(String accountId);
}

For a native alternative, see CassandraRepository in Provider-Specific Repositories. See the Wide-Column guide.

Document

Document databases usually filter by several attributes, query nested documents where the provider supports them, and offer the richest expression capabilities, which still vary by database. Indexes on the filtered and sorted attributes matter for performance:

@Repository
public interface ProductRepository extends BasicRepository<Product, String> {

    List<Product> findByCategoryAndPriceLessThan(String category, BigDecimal price);
}
List<Product> products = repository.findByCategoryAndPriceLessThan("peripherals", new BigDecimal("100"));

See the Document guide.

Graph

Graph databases store entities as vertices and relationships as edges. A repository filters entities by property and persists them, while traversing relationships needs the graph API and, for some providers, native languages such as Cypher or Gremlin. Providers differ in what they offer: see Neo4JRepository and TinkerPopRepository in Provider-Specific Repositories. Ordinary Jakarta Data queries are not graph traversals.

@Repository
public interface CustomerRepository extends BasicRepository<Customer, String> {
}
repository.save(new Customer("c-1", "Ada"));
Optional<Customer> customer = repository.findById("c-1");

See the Graph guide.

Time Series

Time Series data is modeled around the timestamp, which Eclipse JNoSQL expects as the @Id. A repository saves and finds observations and supports derived queries such as findBySensor. The temporal operations (since, until, last, latest and earliest) are part of TimeSeriesTemplate, not of the repository. Ingestion, ordering and the treatment of updates and deletes depend on the provider; many time-series stores are append-oriented.

@Repository
public interface SensorReadingRepository extends BasicRepository<SensorReading, Instant> {

    List<SensorReading> findBySensor(String sensor);
}
List<SensorReading> readings = repository.findBySensor("sensor-1");

List<SensorReading> lastDay = template.select(SensorReading.class)
        .where("sensor").eq("sensor-1")
        .last(Duration.ofHours(24))
        .result();

See the Time Series guide.

Vector

Vector databases store vector representations (embeddings) and retrieve entities by similarity. Metadata filtering and the search options are provider-specific. A repository persists and retrieves vector entities like any other, but similarity search is not a derived query: there is no repository method name that expresses it, and it uses VectorTemplate:

@Repository
public interface ArticleRepository extends BasicRepository<Article, String> {
}
List<Article> similar = template.search(Article.class)
        .vector(queryVector)
        .where("author").eq("Example Author")
        .limit(Limit.of(10))
        .result();

See the Vector guide.

References