Jakarta NoSQL
Standardized NoSQL persistence for Java, from portable operations to native database capabilities.
Jakarta NoSQL standardizes object mapping and persistence operations for NoSQL databases. Eclipse JNoSQL implements it and adds database-model and provider-specific capabilities: the specification covers Key-Value, Document, and Wide-Column, and JNoSQL extends it with Graph, Time Series, and Vector support.
Get Started in Three Steps
You need a configured JNoSQL database provider, a CDI environment, and compatible Java and JNoSQL versions; see the Minimum Requirements and the guide for your database model (Key-Value, Wide-Column, Document, Graph, Time Series, or Vector). The examples use the same Product entity as Jakarta Data and omit the java.* imports.
- 01 Map your entity Create a Java class using persistence annotations.
- 02 Inject a template Inject the appropriate template using CDI.
- 03 Persist and query Insert, find, update and delete 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 @Entity, @Id and @Column. A Java record keeps the mapping to its attributes. See Object Mapping and the Mapping Annotations reference.
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.nosql.Template;
@ApplicationScoped
public class ProductService {
@Inject
Template template;
}
Entities, templates and repositories are discovered and injected through CDI, so a CDI-managed class injects jakarta.nosql.Template, which provides the standard persistence operations.
Product keyboard = new Product("p-1", "Keyboard", new BigDecimal("49.90"),
25, 5, "peripherals", LocalDate.of(2030, 1, 1));
template.insert(keyboard);
Optional<Product> found = template.find(Product.class, "p-1");
template.update(new Product("p-1", "Keyboard", new BigDecimal("44.90"),
25, 5, "peripherals", LocalDate.of(2030, 1, 1)));
template.delete(Product.class, "p-1");
Inside ProductService, insert, find, update and delete use the Template methods. Querying beyond lookup by identifier is covered by the Fluent API and the Query API. Which operations succeed depends on the database; Key-Value databases, for example, primarily support identifier-based operations.
Key Features
- Object Mapping Entities, identifiers, columns and converters.
- Standard Template Common Jakarta NoSQL persistence operations.
- Fluent API Programmatic queries and conditions.
- Query API Textual queries and parameter binding.Since Jakarta NoSQL 1.1
- Projections Retrieve selected attributes using @Projection.Since Jakarta NoSQL 1.1
- Database Model Templates Specialized operations for the six NoSQL database models.JNoSQL Specialization
- Provider-Specific Templates Native queries and vendor-specific capabilities.JNoSQL Specialization
Template Specialization Levels
- Standard Template Jakarta NoSQL
Standardized persistence operations
- Insert
- Update
- Find
- Delete
- Query
- Database Model Templates Eclipse JNoSQL
Operations tailored to each database model.
- Provider-Specific Templates Eclipse JNoSQL
Native capabilities of individual database technologies.
Object Mapping
Jakarta NoSQL defines its own mapping semantics for NoSQL databases. Entities are plain Java classes described with a small set of annotations, as in Step 1. This abstraction lets the same entity be persisted across supported database implementations, subject to provider capabilities and the differences between data models.
| Annotation | Purpose | Origin |
|---|---|---|
@Entity | Declare a persistent entity | Jakarta NoSQL |
@Id | Identify an entity | Jakarta NoSQL |
@Column | Map an attribute | Jakarta NoSQL |
@MappedSuperclass | Reuse persistent attributes in subclasses | Jakarta NoSQL |
@Embeddable | Represent a value object stored with its owner | Jakarta NoSQL |
@Convert | Apply an AttributeConverter to an attribute | Jakarta NoSQL |
@Database | Select the database model and provider of an injected template | Eclipse JNoSQL (CDI qualifier) |
The Jakarta NoSQL annotations are in the jakarta.nosql package. @Database is not a mapping annotation but an Eclipse JNoSQL CDI qualifier. Inheritance, discriminators, converters and @Projection are covered in Mapping Annotations.
Basic entity mapping
The Product entity from Step 1 is the basic case: @Entity, @Id and @Column are enough. By default the entity is stored under its simple class name and each attribute under its own name.
Different stored names
Give @Entity or @Column a value to choose the stored name:
@Entity("products")
public class Product {
@Id
private String id;
@Column("unit_price")
private BigDecimal price;
// other attributes omitted
}
Queries still refer to the Java attribute name (price), which the implementation maps to unit_price.
Embedded value objects
@Embeddable describes a value object without identity. Its @Column attributes are stored with the owning entity:
@Embeddable
public class ProductDetails {
@Column
private String manufacturer;
@Column
private String warranty;
}
@Entity
public class Product {
@Id
private String id;
@Column
private ProductDetails details;
}
Attribute converters
An AttributeConverter<X, Y> converts an attribute of type X to a storable type Y. Declare it with @Converter and select it with @Convert:
import jakarta.nosql.AttributeConverter;
import jakarta.nosql.Converter;
public record Sku(String value) {
}
@Converter
public class SkuConverter implements AttributeConverter<Sku, String> {
@Override
public String convertToDatabaseColumn(Sku attribute) {
return attribute == null ? null : attribute.value();
}
@Override
public Sku convertToEntityAttribute(String dbData) {
return dbData == null ? null : new Sku(dbData);
}
}
@Entity
public class Product {
@Id
private String id;
@Column
@Convert(SkuConverter.class)
private Sku sku;
}
Embedding strategies, @MappedSuperclass and inheritance are described in Mapping Annotations.
Standard Template
jakarta.nosql.Template provides common persistence operations without a repository interface. Inject it in any CDI-managed class:
import jakarta.inject.Inject;
import jakarta.nosql.Template;
@Inject
Template template;
Everything in this section belongs to the standard Template interface unless it is marked as an Eclipse JNoSQL specialization.
| Operation | Purpose | Returns |
|---|---|---|
insert(entity) | Persist a new entity | The inserted entity |
insert(entities) | Persist several entities |
Iterable of inserted entities |
insert(entity, ttl) | Persist an entity with a time to live | The inserted entity |
insert(entities, ttl) | Persist several entities with a time to live |
Iterable of inserted entities |
update(entity) | Modify an existing entity | The updated entity |
update(entities) | Modify several existing entities |
Iterable of updated entities |
find(type, id) | Retrieve an entity by identifier |
Optional of the entity |
delete(entity) | Delete an entity | void |
delete(entities) | Delete several entities | void |
delete(type, id) | Delete an entity by identifier | void |
select(type), delete(type), update(type)
| Start a fluent query | See Fluent API |
query(text), typedQuery(text, type)
| Run a textual query | See Query API |
Insert
Product keyboard = new Product("p-1", "Keyboard", new BigDecimal("49.90"),
25, 5, "peripherals", LocalDate.of(2030, 1, 1));
Product saved = template.insert(keyboard);
Continue with the returned instance, because it contains any generated or incremented values. What happens when the identifier already exists depends on the database: it may reject the insert, overwrite, or upsert.
Update
Product updated = template.update(
new Product("p-1", "Keyboard", new BigDecimal("44.90"),
25, 5, "peripherals", LocalDate.of(2030, 1, 1)));
update modifies an entity that already exists; it is not an upsert. Databases that distinguish updates from inserts ignore non-matching entities instead of raising an error.
Find
Optional<Product> found = template.find(Product.class, "p-1");
Product product = template.find(Product.class, "p-1")
.orElseThrow(() -> new IllegalStateException("Product p-1 not found"));
find returns Optional.empty() when no entity has the identifier.
Delete
template.delete(Product.class, "p-1");
template.delete(product);
delete(type, id) removes the entity with the given identifier, and delete(entity) removes the given instance.
Multiple entities
insert, update and delete also accept an Iterable:
List<Product> products = List.of(
new Product("p-2", "Mouse", new BigDecimal("19.90"),
40, 10, "peripherals", LocalDate.of(2030, 1, 1)),
new Product("p-3", "Monitor", new BigDecimal("199.00"),
10, 2, "displays", LocalDate.of(2030, 1, 1)));
Iterable<Product> saved = template.insert(products);
Iterable<Product> updated = template.update(saved);
template.delete(products);
The returned Iterable keeps the order of the input. A bulk call is a convenience, not a transaction: the API does not require it to be atomic, and partial effects depend on the database.
Time to live
The standard insert overloads accept a Duration after which the database may expire the entity:
template.insert(keyboard, Duration.ofMinutes(10));
template.insert(products, Duration.ofHours(1));
Expiration is useful for caches and temporary data, but it is optional. A provider may throw UnsupportedOperationException when it has no per-entity expiration, may round the duration to a coarser unit, or may not apply it, so check the provider documentation. This is a Jakarta NoSQL operation. As an Eclipse JNoSQL specialization, KeyValueTemplate also offers put(entity, ttl); see the Key-Value guide.
Fluent API
The Fluent API builds queries from Java method chains instead of query strings or database-specific query objects. Its entry points, select, delete and update, are part of the standard jakarta.nosql.Template, so no specialized template is needed:
@Inject
Template template;
You query mapped entities and receive mapped instances, with no manual conversion. The API is portable in style, not in capability: it does not make every NoSQL query language interchangeable, and what a database can execute is described in Database limitations. Specialized templates add model-specific fluent operations, such as the Eclipse JNoSQL vector search.
Selecting entities
List<Product> products = template.select(Product.class).result();
List<Product> keyboards = template.select(Product.class)
.where("name").eq("Keyboard")
.result();
select(Product.class) selects Product entities and where adds a condition. Attribute names are the Java attribute names (such as price), which the implementation maps to the stored names. id always refers to the identifier. result() is generic, so assign it to a typed variable.
Conditions
where(attribute) and the connectors and(attribute) and or(attribute) return a condition with these methods:
| Method | Meaning |
|---|---|
eq(value) | Equal to |
gt(value) | Greater than |
gte(value) | Greater than or equal to |
lt(value) | Less than |
lte(value) | Less than or equal to |
between(a, b) | Between two values |
in(values) | Equal to any value of an Iterable
|
like(text) | Matches a text pattern |
contains(text) | Contains the text |
startsWith(text) | Starts with the text |
endsWith(text) | Ends with the text |
not() | Negates the next condition |
template.select(Product.class).where("name").eq("Keyboard").result();
template.select(Product.class).where("stock").gt(0).result();
template.select(Product.class).where("stock").gte(5).result();
template.select(Product.class).where("stock").lt(5).result();
template.select(Product.class).where("price").lte(new BigDecimal("10.00")).result();
template.select(Product.class)
.where("price")
.between(new BigDecimal("10.00"), new BigDecimal("50.00"))
.result();
template.select(Product.class)
.where("category").in(List.of("peripherals", "audio")).result();
template.select(Product.class).where("name").like("Key%").result();
template.select(Product.class).where("name").contains("board").result();
template.select(Product.class).where("name").startsWith("Key").result();
template.select(Product.class).where("name").endsWith("board").result();
template.select(Product.class).where("category").not().eq("legacy").result();
There is no separate not-equal method; use not().eq(value). The fluent API has no null-check methods.
Combining conditions
Chain conditions with and and or, and negate one with not():
List<Product> available = template.select(Product.class)
.where("category").eq("peripherals")
.and("stock").gt(0)
.result();
List<Product> candidates = template.select(Product.class)
.where("category").eq("audio")
.or("category").eq("peripherals")
.result();
List<Product> current = template.select(Product.class)
.where("category").not().eq("legacy")
.and("name").like("Key%")
.result();
Conditions are added one after another; the fluent API has no grouping for nested conditions, so use the Query API for expressions that need them.
Sorting and limits
List<Product> cheapestFirst = template.select(Product.class)
.where("stock").gt(0)
.orderBy("price").asc()
.orderBy("id").asc()
.result();
List<Product> mostExpensive = template.select(Product.class)
.orderBy("price").desc()
.limit(5)
.result();
List<Product> thirdPage = template.select(Product.class)
.orderBy("name").asc()
.skip(20)
.limit(10)
.result();
orderBy can be repeated for several attributes, skip is the offset and limit is the maximum number of results; both take a long. This API does not use the Jakarta Data Sort or Limit types. Without a total order, the same query may return rows in a different order between calls, so finish with a unique attribute such as id when paging.
Query execution
| Method | Returns | Empty result |
|---|---|---|
result() | List | Empty list |
singleResult() | Optional | Optional.empty() |
stream() | Stream | Empty stream |
count() | long | 0 |
List<Product> list = template.select(Product.class).where("stock").eq(0).result();
Optional<Product> one = template.select(Product.class).where("id").eq("p-1").singleResult();
long outOfStock = template.select(Product.class).where("stock").eq(0).count();
try (Stream<Product> stream = template.select(Product.class).where("stock").gt(0).stream()) {
stream.map(Product::name).forEach(System.out::println);
}
singleResult() throws jakarta.data.exceptions.NonUniqueResultException when more than one entity matches. Close a stream when you finish with it.
Deleting entities
template.delete(Product.class)
.where("stock").eq(0)
.and("category").eq("legacy")
.execute();
Use a restrictive predicate: without where, the delete targets every entity of the type. Support for conditional deletion, and its semantics, depend on the database.
Updating entities
template.update(Product.class)
.set("stock").to(0)
.where("category").eq("legacy")
.execute();
Update semantics depend on the database; a Key-Value database that supports only key-based updates throws UnsupportedOperationException.
Relationship with Jakarta Data
Jakarta Data repositories and the Fluent API are complementary; neither universally replaces the other.
Jakarta Data repository, ideal for declaring common operations on an interface:
List<Product> findByName(String name);
Jakarta NoSQL Fluent API, useful when the application needs explicit query construction:
template.select(Product.class)
.where("name").eq("Keyboard")
.result();
Repositories favor declarative persistence, while the Fluent API gives direct control over supported query construction. Templates also cover model-specific operations through specialized templates. See Jakarta Data.
Database limitations
The same template programming model does not guarantee identical query capabilities across databases. Applications express query intent in Java, and the implementation adapts the supported operations to the underlying database. A pure Key-Value database, for example, supports identifier-based access rather than arbitrary attribute filtering: its fluent API rejects and, or, not, text predicates, sorting, skip and limit with UnsupportedOperationException. See the Key-Value, Wide-Column, Document, Graph, Time Series and Vector guides, and the query capabilities reference for per-database support.
Specialized fluent operations
The fluent style also appears in specialized models. As an Eclipse JNoSQL specialization, VectorTemplate adds similarity-oriented operations that are not part of the standard Template:
List<Article> articles = vectorTemplate.search(Article.class)
.vector(queryVector)
.limit(Limit.of(10))
.result();
The common style keeps the API familiar while allowing model-specific capabilities. See the Vector guide for the Vector API.
The fluent APIs above are Jakarta NoSQL and Eclipse JNoSQL Java APIs, distinct from the query language described in Jakarta Query.
Query API
Since Jakarta NoSQL 1.1
The Query API executes textual queries, written in the Jakarta Common Query Language (JCQL), through a Template. Working with it has four steps: create the query with query or typedQuery, bind parameter values, execute it, and retrieve the results. Both types are in the jakarta.nosql package.
Version note: the Query API and
@Projectionbelong to Jakarta NoSQL 1.1, which is still published as milestones (1.1.0-M3,1.1.0-M4). Eclipse JNoSQL implements them in milestone builds such as1.2.0-M2and2.0.0-M1, or in a snapshot build. The final Eclipse JNoSQL1.2.0is built on Jakarta NoSQL 1.0 and does not include them. The specification version and the Eclipse JNoSQL version are different numbers.
| API | Purpose |
|---|---|
Template.query(String) | Creates a Query
|
Template.typedQuery(String, Class<T>) | Creates a TypedQuery<T> for an entity or a projection type |
Query | Binds parameters and executes a textual query |
TypedQuery<T> | A Query whose results have the declared Java type T
|
bind(String, Object) | Binds a named parameter; the name is written without the colon |
bind(int, Object) | Binds a positional parameter, starting at 1 |
result() | Returns all matches as a List
|
singleResult() | Returns one match as an Optional
|
stream() | Returns the matches as a Stream
|
executeUpdate() | Executes an UPDATE or DELETE query and returns nothing |
A Query is mutable and is not thread-safe: do not share one instance between threads.
SELECT queries
query returns a Query. The type of the result list is chosen by the caller:
List<Product> products = template
.query("FROM Product WHERE category = 'peripherals'")
.result();
typedQuery declares the result type up front and returns a TypedQuery<Product>:
List<Product> products = template
.typedQuery("FROM Product WHERE category = 'peripherals'", Product.class)
.result();
Prefer typedQuery whenever the result is an entity or a projection: the compiler checks the result type, and Eclipse JNoSQL rejects a query whose FROM entity does not match the declared type. For an entity type, the FROM clause is optional: typedQuery("WHERE stock = 0", Product.class) selects from Product.
Query parameters
Always bind values instead of concatenating user input into the query string. Bound values are never parsed as query text, which avoids injection and quoting errors, and leaves the query string constant.
Named parameters start with a colon in the query and are bound without it:
List<Product> products = template
.typedQuery("FROM Product WHERE category = :category AND price <= :maxPrice", Product.class)
.bind("category", "peripherals")
.bind("maxPrice", new BigDecimal("100.00"))
.result();
Positional parameters are written ?1, ?2, and so on, and the position passed to bind starts at 1. A position lower than 1 throws IllegalArgumentException:
List<Product> products = template
.typedQuery("FROM Product WHERE category = ?1 AND price <= ?2", Product.class)
.bind(1, "peripherals")
.bind(2, new BigDecimal("100.00"))
.result();
Use one style per query. Eclipse JNoSQL happens to accept both together, but the specification does not define it. Executing a query with an unbound parameter fails.
Separating the query text from its arguments lets the same definition run with different values. Create the query, bind, execute, and then rebind it from the same thread:
var query = template.typedQuery("FROM Product WHERE category = :category", Product.class);
List<Product> peripherals = query.bind("category", "peripherals").result();
List<Product> audio = query.bind("category", "audio").result();
This keeps the query definition in one place. The API makes no promise about statement caching or other database-side optimization.
Result retrieval
| Method | Returns | When there is no match |
|---|---|---|
result() | List<T> | An empty list |
singleResult() | Optional<T> | Optional.empty() |
stream() | Stream<T> | An empty stream |
Optional<Product> product = template
.typedQuery("FROM Product WHERE name = :name", Product.class)
.bind("name", "Keyboard")
.singleResult();
product.ifPresentOrElse(
found -> System.out.println(found.name()),
() -> System.out.println("No product named Keyboard"));
When more than one entity matches, the specification leaves singleResult() provider-specific. Eclipse JNoSQL throws jakarta.data.exceptions.NonUniqueResultException:
try {
template.typedQuery("FROM Product WHERE category = :category", Product.class)
.bind("category", "peripherals")
.singleResult();
} catch (NonUniqueResultException exception) {
// more than one product is in the category
}
A Stream may hold database resources, so close it:
try (Stream<Product> products = template
.typedQuery("FROM Product WHERE stock > 0", Product.class)
.stream()) {
long expensive = products.filter(p -> p.price().compareTo(BigDecimal.TEN) > 0).count();
}
result(), singleResult() and stream() are for SELECT queries only. They throw UnsupportedOperationException on an UPDATE or DELETE.
UPDATE and DELETE
Textual mutations run with executeUpdate(), which returns void and throws UnsupportedOperationException when called on a SELECT:
// Update a price
template.query("UPDATE Product SET price = :price WHERE id = :id")
.bind("price", new BigDecimal("89.90"))
.bind("id", "keyboard-1")
.executeUpdate();
// Decrease the stock (a calculated update)
template.query("UPDATE Product SET stock = stock - :quantity WHERE id = :id")
.bind("quantity", 2)
.bind("id", "keyboard-1")
.executeUpdate();
// Delete discontinued products
template.query("DELETE FROM Product WHERE category = :category")
.bind("category", "discontinued")
.executeUpdate();
The statement returns no count, and under eventual consistency the change may not be visible immediately. Calculated updates such as stock - :quantity depend on what the underlying database can express, and mutation and transaction semantics are not identical across providers.
Query expressions
JCQL goes beyond simple comparisons. A few representative expressions on Product:
// Attribute-to-attribute comparison
template.typedQuery("FROM Product WHERE stock < minimumStock", Product.class).result();
// Standard function
template.typedQuery("FROM Product WHERE UPPER(name) = :name", Product.class)
.bind("name", "KEYBOARD")
.result();
// Arithmetic expression
template.typedQuery("FROM Product WHERE price * stock > :minimum", Product.class)
.bind("minimum", new BigDecimal("1000"))
.result();
// Temporal expression
template.typedQuery("FROM Product WHERE expirationDate < LOCAL DATE", Product.class).result();
Expressions that a database cannot evaluate natively are not guaranteed to work, so check the capabilities of your database. The complete function list, grammar and capabilities are in Jakarta Query.
Not every database accepts dynamic queries. A provider that cannot run them throws UnsupportedOperationException, and a pure Key-Value store is generally limited to identifier-based access; see Database limitations.
Projections
Since Jakarta NoSQL 1.1
A projection retrieves selected attributes instead of requiring the whole entity, for example a product catalog that shows only the name and price. It is declared with @Projection on a Java record and read with typedQuery.
| API | Purpose |
|---|---|
@Projection | Marks a record as a read-only query result type |
@Projection(from = Product.class) | Names the entity, so the query may omit FROM
|
@Column("path") | Maps a record component to a differently named or nested attribute |
typedQuery(String, Class<T>) | Executes the query and maps each result to the projection |
Projection definition
import jakarta.nosql.Projection;
@Projection(from = Product.class)
public record ProductSummary(String name, BigDecimal price) {
}
Record components are matched to entity attributes by name. Without from, the query must state its FROM entity, as in FROM Product.
Selecting attributes
A single attribute uses a record with one component:
@Projection(from = Product.class)
public record ProductName(String name) {
}
List<ProductName> names = template
.typedQuery("SELECT name FROM Product", ProductName.class)
.result();
Several attributes map to the record, in the order they are selected:
List<ProductSummary> catalog = template
.typedQuery("SELECT name, price FROM Product", ProductSummary.class)
.result();
Projections accept parameters and conditions like any other query:
List<ProductSummary> affordable = template
.typedQuery("SELECT name, price FROM Product WHERE category = :category AND price <= :maxPrice",
ProductSummary.class)
.bind("category", "peripherals")
.bind("maxPrice", new BigDecimal("100.00"))
.result();
Projection limitations
- With an explicit
SELECTlist, the number of selected attributes must equal the number of record components; otherwise Eclipse JNoSQL throwsIllegalArgumentException. -
typedQueryaccepts only entities and@Projectionrecords; a type such asStringis rejected withIllegalArgumentException. - A projection is a read-only query result, not a persistent entity: it cannot be inserted, updated or deleted.
- Support for selecting individual attributes varies by database, and a provider may still retrieve the full entity internally, so a projection does not always reduce database I/O.
For repository methods that return projections, see Jakarta Data.
Template Specialization
Start with the standard Template, which gives every database the same programming model, and specialize only when the application needs more. The overview shows three levels:
| Level | Purpose |
|---|---|
| Standard Template | Common Jakarta NoSQL persistence operations |
| Database Model Templates | Operations specific to a NoSQL database model |
| Provider-Specific Templates | Operations specific to an individual database provider |
The levels describe increasing specialization. In the sources, each model template extends Template and each provider template extends the model template of its database, so a specialized template keeps the standard operations. Use the levels as a guide for choosing an API rather than as a required inheritance chain.
Database Model Templates
JNoSQL Specialization
Eclipse JNoSQL provides a template for each database model. They are Eclipse JNoSQL interfaces, not Jakarta NoSQL specifications:
| Model | Template | Main capabilities | Guide |
|---|---|---|---|
| Key-Value | KeyValueTemplate | Store and read by key, with optional expiration | Key-Value |
| Wide-Column | ColumnTemplate | Entry point for column databases, with the shared semi-structured operations | Wide-Column |
| Document | DocumentTemplate | Entry point for document databases, with the shared semi-structured operations | Document |
| Graph | GraphTemplate | Edges between vertices, with labels and properties | Graph |
| Time Series | TimeSeriesTemplate | Temporal operations: latest, earliest, since, until, last
| Time Series |
| Vector | VectorTemplate | Similarity search with a query vector | Vector |
Wide-Column, Document, Graph, Time Series and Vector templates share a common base, SemiStructuredTemplate, which adds operations such as count(Class), findAll(Class) and deleteAll(Class) to the standard Template. ColumnTemplate and DocumentTemplate declare no methods of their own: they select the database model to inject. KeyValueTemplate extends Template directly.
The examples below use a different entity where the model calls for it, and omit the imports of the entity types.
Key-Value
KeyValueTemplate reads and writes entities by key and, where the database supports it, expires them:
import jakarta.inject.Inject;
import org.eclipse.jnosql.mapping.keyvalue.KeyValueTemplate;
@Inject
KeyValueTemplate template;
template.put(product, Duration.ofMinutes(30));
Optional<Product> found = template.get("keyboard-1", Product.class);
Pure key-value databases generally do not filter by arbitrary attributes: access is by key. See the Key-Value guide.
Wide-Column
ColumnTemplate is the entry point for column databases. Its fluent queries use the same API as the standard Template:
import jakarta.inject.Inject;
import org.eclipse.jnosql.mapping.column.ColumnTemplate;
@Inject
ColumnTemplate template;
// category is the partition key of the table
List<Product> peripherals = template.select(Product.class)
.where("category").eq("peripherals")
.result();
Which queries work depends on the partitioning, clustering columns and indexes of the table. See the Wide-Column guide.
Document
DocumentTemplate is the entry point for document databases. It adds the shared semi-structured operations, such as counting and reading every entity of a type:
import jakarta.inject.Inject;
import org.eclipse.jnosql.mapping.document.DocumentTemplate;
@Inject
DocumentTemplate template;
long products = template.count(Product.class);
try (Stream<Product> all = template.findAll(Product.class)) {
all.forEach(System.out::println);
}
See the Document guide for nested documents and queries.
Graph
GraphTemplate adds edges, the relationships between entities. The example links two Person vertices:
import jakarta.inject.Inject;
import org.eclipse.jnosql.mapping.graph.Edge;
import org.eclipse.jnosql.mapping.graph.GraphTemplate;
@Inject
GraphTemplate template;
Edge<Person, Person> knows = Edge.source(ada)
.label("KNOWS")
.target(grace)
.property("since", 2020)
.build();
template.edge(knows);
The Person vertices are inserted with the standard insert first, as in the guide. See the Graph guide for traversal and the provider-specific graph templates.
Time Series
TimeSeriesTemplate adds temporal operations to the fluent query. They apply to the attribute annotated with @Id. This query returns the ten latest readings of one sensor in the last day:
import jakarta.inject.Inject;
import org.eclipse.jnosql.mapping.timeseries.TimeSeriesTemplate;
@Inject
TimeSeriesTemplate template;
List<SensorReading> readings = template.select(SensorReading.class)
.where("sensor").eq("sensor-1")
.last(Duration.ofHours(24))
.latest(10);
since, until and earliest work the same way. See the Time Series guide for the complete temporal API.
Vector
VectorTemplate searches by similarity to a query vector and returns the closest entities:
import jakarta.data.Limit;
import jakarta.inject.Inject;
import org.eclipse.jnosql.mapping.vector.DenseVector;
import org.eclipse.jnosql.mapping.vector.Vector;
import org.eclipse.jnosql.mapping.vector.VectorTemplate;
@Inject
VectorTemplate template;
Vector queryVector = DenseVector.of(0.10F, 0.42F, 0.80F);
List<Article> similar = template.search(Article.class)
.vector(queryVector)
.limit(Limit.of(5))
.result();
See the Vector guide for dense, sparse and multi-vector representations, thresholds and metadata filters.
Provider-Specific Templates
JNoSQL Specialization
Some database drivers add a template of their own, which exposes native queries and database-specific operations. These are specialized APIs of individual Eclipse JNoSQL integrations, not Jakarta NoSQL specifications. Each one extends the model template of its database, so the standard Template operations remain available. The interfaces below are the public templates in JNoSQL Databases, in the mapping package of each module:
| Database | Template | Native capabilities | Driver |
|---|---|---|---|
| ArangoDB | ArangoDBTemplate | AQL queries, with an optional result type | jnosql-arangodb |
| Cassandra | CassandraTemplate | CQL queries and a consistency level per operation | jnosql-cassandra |
| Couchbase | CouchbaseTemplate | N1QL queries | jnosql-couchbase |
| DynamoDB | DynamoDBTemplate | PartiQL queries | jnosql-dynamodb |
| Elasticsearch | ElasticsearchTemplate | Native search requests | jnosql-elasticsearch |
| Hazelcast | HazelcastTemplate | SQL queries and predicates | jnosql-hazelcast |
| MongoDB | MongoDBTemplate | Native filters and aggregation pipelines | jnosql-mongodb |
| Neo4j | Neo4JTemplate | Cypher queries and relationship traversal | jnosql-neo4j |
| Oracle NoSQL | OracleNoSQLTemplate | SQL queries | jnosql-oracle-nosql |
| OrientDB | OrientDBTemplate | SQL queries and live queries | jnosql-orientdb |
| ScyllaDB | ScyllaDBTemplate | CQL queries and a consistency level per operation | jnosql-scylladb |
| Solr | SolrTemplate | Solr queries | jnosql-solr |
| Apache TinkerPop | TinkerpopTemplate | Gremlin queries, edges and traversals | jnosql-tinkerpop |
ArangoDB extends both DocumentTemplate and GraphTemplate; Cassandra and ScyllaDB extend ColumnTemplate; Hazelcast extends KeyValueTemplate; Neo4j and TinkerPop extend GraphTemplate; the others extend DocumentTemplate. Drivers that are not listed, including the other Key-Value, Time Series and Vector integrations, expose no template of their own: use the model template.
Representative examples
The driver must be on the classpath, so add the dependency of your database. The artifact version is the Eclipse JNoSQL Databases version; MongoDB is shown as an example, and the other drivers use their own artifact id (see Supported Databases and the driver links above):
<dependency>
<groupId>org.eclipse.jnosql.databases</groupId>
<artifactId>jnosql-mongodb</artifactId>
<version>1.2.0</version>
</dependency>
MongoDB: native filters. MongoDBTemplate accepts the BSON filters of the MongoDB driver and maps the results to entities:
import com.mongodb.client.model.Filters;
import jakarta.inject.Inject;
import org.bson.conversions.Bson;
import org.eclipse.jnosql.databases.mongodb.mapping.MongoDBTemplate;
@Inject
MongoDBTemplate template;
Bson lowStock = Filters.and(Filters.eq("category", "peripherals"), Filters.lt("stock", 5));
try (Stream<Product> products = template.select(Product.class, lowStock)) {
products.forEach(System.out::println);
}
Cassandra: CQL and consistency. CassandraTemplate runs CQL and takes a consistency level for each write. CQL is native to Cassandra and distinct from Jakarta Query:
import com.datastax.oss.driver.api.core.ConsistencyLevel;
import jakarta.inject.Inject;
import org.eclipse.jnosql.databases.cassandra.mapping.CassandraTemplate;
@Inject
CassandraTemplate template;
Stream<Product> products = template.cql(
"SELECT * FROM product WHERE category = :category",
Map.of("category", "peripherals"));
template.save(product, ConsistencyLevel.QUORUM);
Elasticsearch: native search requests. ElasticsearchTemplate executes an Elasticsearch SearchRequest and maps the hits to entities:
import co.elastic.clients.elasticsearch.core.SearchRequest;
import jakarta.inject.Inject;
import org.eclipse.jnosql.databases.elasticsearch.mapping.ElasticsearchTemplate;
@Inject
ElasticsearchTemplate template;
SearchRequest request = new SearchRequest.Builder()
.index("product")
.query(query -> query.match(match -> match.field("name").query("keyboard")))
.build();
Stream<Product> products = template.search(request);
Neo4j: Cypher. Neo4JTemplate runs Cypher on top of the graph model:
import jakarta.inject.Inject;
import org.eclipse.jnosql.databases.neo4j.mapping.Neo4JTemplate;
@Inject
Neo4JTemplate template;
Stream<Person> friends = template.cypher(
"MATCH (:Person {name: $name})-[:KNOWS]->(friend:Person) RETURN friend",
Map.of("name", "Ada"));
The other templates work the same way. Each driver's documentation describes its native operations, and the Wide-Column, Graph and Key-Value guides show more of them. For native queries through repositories, see Provider-Specific Repositories.
Portability and limitations
Each level trades portability for capability:
- Standard Template operations provide a common programming model.
- Database Model Templates add model-specific operations.
- Provider-Specific Templates expose native database capabilities.
- The more specialized the API, the harder it is to change database, so keep native code in a small part of the application.
Operations that a database cannot execute may fail, for example with UnsupportedOperationException, so what a query can do depends on the database. See the Jakarta Query compatibility reference in JNoSQL Databases, and Database limitations above.