### Example Repository Usage Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/datarepository Demonstrates how to inject and use the 'DriverLicenses' repository to register a license and check its existence. ```java @Inject DriverLicenses licenses; ... DriverLicense license = ... license = licenses.register(license); boolean isValid = licenses.existsByLicenseNumAndExpiryGreaterThan(license.licenseNum, LocalDate.now()); ``` -------------------------------- ### Example Repository Usage Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/basicrepository Demonstrates how to inject and use the Employees repository for saving, deleting, and querying entities. ```java @Inject Employees employees; ... Employee emp = ...; emp = employees.save(emp); boolean deleted = employees.deleteByBadgeNumber(emp.badgeNum); PageRequest pageRequest = PageRequest.ofSize(25); Order sorts = Order.by(Sort.asc("name")); Page page = people.findAll(pageRequest, sorts); ``` -------------------------------- ### JavaDoc Search Examples Source: https://jakarta.ee/specifications/data/1.0/apidocs/help-doc Examples demonstrating how to use camelCase abbreviations and partial names to search for Java API elements. ```text j.l.obj ``` ```text InpStr ``` ```text HM.cK ``` -------------------------------- ### Example Entity Class Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 An example entity class named Product with persistent fields. ```java import jakarta.persistence.Entity; @Entity public class Product { public long id; public String name; public float price; } ``` -------------------------------- ### Example Repository Definition Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/basicrepository Defines a repository interface 'Employees' that extends BasicRepository for Employee entities. ```java @Repository public interface Employees extends BasicRepository { boolean deleteByBadgeNumber(int badgeNum); ... } ``` -------------------------------- ### Example Repository Interface Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/datarepository Defines a 'DriverLicenses' repository interface extending DataRepository, with custom methods for querying and manipulation. ```java @Repository public interface DriverLicenses extends DataRepository { boolean existsByLicenseNumAndExpiryGreaterThan(String num, LocalDate minExpiry); @Insert DriverLicense register(DriverLicense l); @Update boolean renew(DriverLicense l); ... } ``` -------------------------------- ### Insert Lifecycle Method Example Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Example of an @Insert lifecycle method for inserting a Book entity. ```java @Insert void insertBook(Book book); ``` -------------------------------- ### Example Usage of Metamodel for Sorting Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates using the static metamodel (_Product) to specify sorting criteria in a query. ```java import java.util.List; // Assuming 'products' is an instance of a repository or data access object // List found = products.findByNameLike(searchPattern, // _Product.price.desc(), // _Product.name.asc(), // _Product.id.asc()); ``` -------------------------------- ### Example Repository Method Returning a Page Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/page/page Demonstrates how a repository method can return a Page of data, accepting a PageRequest and Order for sorting. ```java @Find Page search(@By("make") String make, @By("model") String model, @By("year") int designYear, PageRequest pageRequest, Order order); ``` -------------------------------- ### Limit.startAt() Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/limit Retrieves the offset at which to start returning query results. ```APIDOC ## startAt() ### Description Returns the offset at which to start when returning query results. The first query result is position 1. ### Returns * **long** - offset of the first result. ``` -------------------------------- ### Example Repository Usage Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/crudrepository Demonstrates how to inject and use the 'Cars' repository to insert a car entity and find cars by make and model with sorting. ```java @Inject Cars cars; ... Car car1 = ... car1 = cars.insert(car1); List found = findByMakeAndModel(car1.make, car1.model, Sort.desc("year"), Sort.asc("vin")); ``` -------------------------------- ### Example Entity Definition Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/basicrepository Defines a sample entity class 'Employee' with basic fields and annotations. ```java @Entity public class Employee { @Id public int badgeNumber; public String firstName; public String lastName; ... } ``` -------------------------------- ### Offset Pagination Example Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates fetching a page of entities using offset pagination. Requires a repository interface extending BasicRepository and a PageRequest object. ```Java public class Person { private Long id; private String name; } @Repository public interface People extends BasicRepository { } ``` ```Java @Inject People people; Page page = people.findAll(PageRequest.ofPage(1).size(2), Order.by(Sort.asc("id"))); ``` -------------------------------- ### Example Metamodel Class for Product Entity Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 A static metamodel class for the Product entity, demonstrating type-safe attribute access. ```java import jakarta.data.metamodel.SortableAttribute; import jakarta.data.metamodel.TextAttribute; import jakarta.data.metamodel.StaticMetamodel; import jakarta.data.metamodel.impl.SortableAttributeRecord; import jakarta.data.metamodel.impl.TextAttributeRecord; @StaticMetamodel(Product.class) public class _Product { public static final String ID = "id"; public static final String NAME = "name"; public static final String PRICE = "price"; public static final SortableAttribute id = new SortableAttributeRecord<>("id"); public static final TextAttribute name = new TextAttributeRecord<>("name"); public static final SortableAttribute price = new SortableAttributeRecord<>("price"); } ``` -------------------------------- ### Example Repository with Query by Method Name Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-addendum-1.0 Demonstrates how to define queries by naming methods in a Java repository interface. This approach is limited to identifier characters and does not support whitespace or operators. ```java @Repository public interface ProductRepository extends BasicRepository { List findByName(String name); @OrderBy("price") List findByNameLike(String namePattern); List findByNameLikeAndPriceLessThanOrderByPriceDesc(String namePattern, float priceBelow); } ``` -------------------------------- ### Merge Lifecycle Method Example Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Example of a custom @Merge lifecycle method. Such methods are not portable between Jakarta Data providers. ```java @Merge Book mergeBook(Book book); ``` -------------------------------- ### Example Entity Definition Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/datarepository Defines an example entity class 'DriverLicense' with an @Id field for unique identification. ```java @Entity public class DriverLicense { @Id public String licenseNum; public LocalDate expiry; ... } ``` -------------------------------- ### Car Repository Interface Example Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Defines a CarRepository interface extending BasicRepository, demonstrating integration with CDI via the @Repository annotation. ```java @Repository public interface CarRepository extends BasicRepository { ``` -------------------------------- ### Get Next Page of Products Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Retrieves the next page of products based on a pattern and page request, ordering by price midpoint. ```java CursoredPage moreExpensive = products.findByNameLike(pattern, pageRequest, order); ``` -------------------------------- ### Example Repository Interface with @Find Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/find Demonstrates how to use the @Find annotation on a repository method to retrieve a list of entities based on a parameter. The method name is arbitrary and does not affect the query. ```java @Repository interface Garage { @Find List getCarsWithModel(@By("model") String model); } ``` -------------------------------- ### Entity Name Example with Jakarta Persistence Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates how an entity name can be explicitly specified using the `name` member of the `@Entity` annotation in Jakarta Persistence. ```Java @Entity(name = "Customer") public class Customer { // ... } ``` -------------------------------- ### Entity Definition Example Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/metamodel/staticmetamodel Defines a sample entity 'Person' with embedded 'Name' to illustrate static metamodel usage. ```java @Entity public class Person { @Id public long ssn; @Embedded public Name name; public int yearOfBirth; } @Embeddable public class Name { public String first; public String last; } ``` -------------------------------- ### Get Previous Page of Products Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Determines the page request for the previous 10 products or before a specific cursor if no previous page exists. ```java pageRequest = moreExpensive.hasContent() && moreExpensive.hasPrevious() ? moreExpensive.previousPageRequest() : pageRequest.beforeCursor(Cursor.forKey(priceMidpoint, 1L)); CursoredPage lessExpensive = products.findByNameLike(pattern, pageRequest, order); ``` -------------------------------- ### Find Entities by Name Pattern Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/metamodel/package-summary Shows a typical repository method call to find entities based on a name pattern, utilizing pagination. This example assumes a `Products` repository and a `namePattern` variable are available. ```java page1 = products.findByNameLike(namePattern, pageRequest); ``` -------------------------------- ### JDQL with Positional Parameters Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/query Example of a repository method using JDQL with positional parameters. The query selects persons based on first and last names provided as positional arguments. ```java @Repository public interface People extends CrudRepository { // JDQL with positional parameters @Query("where firstName = ?1 and lastName = ?2") List byName(String first, String last); // JDQL with a named parameter @Query("where firstName || ' ' || lastName like :pattern") List byName(String pattern); // JPQL using a positional parameter @Query("from Person where extract(year from birthdate) = ?1") List bornIn(int year); // JPQL using named parameters @Query("select distinct name from Person " + "where length(name) >= :min and length(name) <= :max") Page namesOfLength(@Param("min") int minLength, @Param("max") int maxLength, PageRequest pageRequest, Order order); ... } ``` -------------------------------- ### Example Repository Interface with @Save Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/save Demonstrates how to use the @Save annotation on a repository method to park a Car entity. The operation will either insert or update the car based on its existing state in the database. ```java @Repository interface Garage { @Save Car park(Car car); } ``` -------------------------------- ### Example Entity Class Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/crudrepository Defines a sample entity class 'Cars' with fields like vin, make, model, and year. This serves as a model for data persistence. ```java @Entity public class Cars { @Id public long vin; public String make; public String model; public int year; ... } ``` -------------------------------- ### Entity with Basic Fields Example Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates an entity class with various basic fields, including ID, name, SSN, birthdate, and photo. Fields are marked with appropriate types for persistence. ```java @Entity public class Person { @Id private UUID id; private String name; private long ssn; private LocalDate birthdate; private byte[] photo; } ``` -------------------------------- ### Java Repository Method with Limit Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/limit Example of a repository method that accepts a Limit parameter to control query results. It also demonstrates how to use the Limit.of() and Limit.range() static methods. ```java Product[] findByNameLike(String namePattern, Limit limit, Sort... sorts); ... mostExpensive50 = products.findByNameLike(pattern, Limit.of(50), Sort.desc("price")); ... secondMostExpensive50 = products.findByNameLike(pattern, Limit.range(51, 100), Sort.desc("price")); ``` -------------------------------- ### CarRepository Interface Example Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Defines custom find methods by extending BasicRepository. The @Repository annotation triggers implementation generation and CDI bean availability. ```java import jakarta.data.repository.BasicRepository; import jakarta.data.repository.Repository; import java.util.List; import java.util.Optional; @Repository interface CarRepository extends BasicRepository { List findByType(CarType type); Optional findByName(String name); } ``` -------------------------------- ### Named Parameter Example in JDQL Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates the use of a named parameter in a JDQL query. The parameter ':titlePattern' is mapped to the 'titlePattern' method argument. ```java @Query("where title like :titlePattern") List booksMatchingTitle(String titlePattern); ``` -------------------------------- ### Book Repository Query Methods Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Examples of repository methods annotated with @Find for retrieving book data based on various criteria. These methods are portable between Jakarta Data providers. ```java @Find Book bookByIsbn(String isbn); ``` ```java @Find List booksByYear(Year year, Sort order, Limit limit); ``` ```java @Find Page find(@By("year") Year publishedIn, @By("genre") Category type, Order sortBy, PageRequest pageRequest); ``` -------------------------------- ### Cursor-based Pagination with @Query and @OrderBy Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/page/cursoredpage Example of a method signature for cursor-based pagination. It uses @Query to specify a base WHERE clause and multiple @OrderBy annotations to define sorting criteria. The method returns a CursoredPage of Customer entities. ```java @Query("WHERE ordersPlaced >= ?1 OR totalSpent >= ?2") @OrderBy("zipcode") @OrderBy("birthYear") @OrderBy("id") CursoredPage getTopBuyers(int minOrders, float minSpent, PageRequest pageRequest); ``` -------------------------------- ### Define Repository Interface with Custom Query Methods Source: https://jakarta.ee/specifications/data/1.0 Define a repository interface extending BasicRepository to add custom query methods. This example shows how to find cars by type and by name. ```java @Repository public interface Garage extends BasicRepository { List findByType(CarType type); Optional findByName(String name); } ``` -------------------------------- ### Example Repository Interface Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/crudrepository Defines a repository interface 'Cars' that extends CrudRepository for Car entities. It includes a custom query method to find cars by make and model. ```java @Repository public interface Cars extends CrudRepository findByMakeAndModel(String make, String model, Sort... sorts); ... } ``` -------------------------------- ### Repository Method with @Query and @OrderBy Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Example of a repository method using a @Query annotation with a WHERE clause and an @OrderBy annotation for static sorting. Dynamic sorting criteria are provided via the 'sorts' parameter to break ties. ```java @Query("WHERE u.age > ?1") @OrderBy(_User.AGE) Page findByNamePrefix(String namePrefix, PageRequest pagination, Order sorts); ``` -------------------------------- ### Repository Method with @Query and @OrderBy for List Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Similar to the Pageable example, this shows a repository method returning a List, using @Query and @OrderBy for static sorting, with dynamic sorting criteria applied via the 'sorts' parameter. ```java @Query("WHERE u.age > ?1") @OrderBy(_User.AGE) List findByNamePrefix(String namePrefix, Sort... sorts); ``` -------------------------------- ### Obtaining Next Products with Before/After Cursor Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Illustrates how to obtain the next set of products based on a cursor, specifically fetching 10 products that cost $50.00 or more. It sets up the sort order and page request parameters. ```Java float priceMidpoint = 50.0f; Order order = Order.by(_Product.price.asc(), _Product.id.asc()); PageRequest pageRequest = PageRequest.ofPage(5) .size(10) ``` -------------------------------- ### jakarta.data.Limit.of(int) Source: https://jakarta.ee/specifications/data/1.0/apidocs/index-all Creates a limit that caps the number of results at the specified maximum, starting from the first result. ```APIDOC ## jakarta.data.Limit.of(int) ### Description Creates a limit that caps the number of results at the specified maximum, starting from the first result. ### Method Static method ### Parameters #### Path Parameters - **limit** (int) - Required - The maximum number of results. ### Response #### Success Response (200) - **Limit** (jakarta.data.Limit) - A Limit object representing the specified maximum results. ``` -------------------------------- ### Inject and Use Products Repository Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/module-summary Demonstrates how to inject a repository interface into an application and use its methods for data operations. Ensure the repository implementation is provided by the container. ```java @Inject Products products; ... products.create(newProduct); found = products.findByNameIgnoreCaseLikeAndPriceLessThan("%cell%phone%", 900.0f); numDiscounted = products.discountOldInventory(0.15f, Year.now().getValue() - 1); ``` -------------------------------- ### Inject and Use a Repository Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/repository Demonstrates how to inject a repository interface into an application using @Inject and then call its methods. ```java @Inject Products products; ... found = products.findByNameLike("%Printer%"); numUpdated = products.putOnSale(0.15f, 20.0f); ``` -------------------------------- ### Person Entity for Pagination Scenario Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Defines the Person entity with basic fields for use in a Jakarta Data pagination example. ```java package jakarta.data.example; import jakarta.data.annotation.Column; import jakarta.data.annotation.Id; public class Person { @Id private long id; @Column(nullable = false) private String name; private int age; public Person() { } public Person(long id, String name, int age) { this.id = id; this.name = name; this.age = age; } public long getId() { return id; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Person{id=" + id + ", name='" + name + "'" + ", age=" + age + '}' ; } } ``` -------------------------------- ### Using PageRequest and Order for product search Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Illustrates how to construct a PageRequest for a specific page and size, and an Order object using the static metamodel for sorting query results. This is used to fetch the first 20 products matching a name, sorted by price and ID. ```java PageRequest pageRequest = PageRequest.ofPage(1).size(20); List first20 = products.findByName(name, pageRequest, Order.by(_Product.price.desc(), _Product.id.asc())); ``` -------------------------------- ### Annotated Query with Positional Parameters Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Example of an annotated query method using positional parameters to delete a book by its ISBN. ```java @Query("delete from Book where isbn = ?1") void deleteBook(String isbn); ``` -------------------------------- ### Annotated Query with Named Parameters Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Example of an annotated query method using named parameters for filtering and sorting books. ```java @Query("where title like :title order by title asc, id asc") Page booksByTitle(String title, PageRequest pageRequest); ``` -------------------------------- ### Injecting People Repository Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates how to inject the People repository for use in application logic. ```java @Inject People people; ``` -------------------------------- ### JDQL Query with Ordinal Parameters Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/module-summary Execute a JDQL query using ordinal (positional) parameters. The parameter index starts from 1. ```java // example using an ordinal parameter @Query("where ssn = ?1 and deceased = false") Optional person(String ssn); ``` -------------------------------- ### jakarta.data.page.PageRequest.ofSize(int) Source: https://jakarta.ee/specifications/data/1.0/apidocs/index-all Creates a new page request for requesting pages of the specified size, starting with the first page number, which is 1. ```APIDOC ## jakarta.data.page.PageRequest.ofSize(int) ### Description Creates a new page request for requesting pages of the specified size, starting with the first page number, which is 1. ### Method Static method ### Parameters #### Path Parameters - **pageSize** (int) - Required - The desired number of items per page. ### Response #### Success Response (200) - **PageRequest** (jakarta.data.page.PageRequest) - A PageRequest object configured with the specified page size. ``` -------------------------------- ### Limit Record Constructor Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/limit Constructor for the Limit record, used to define the maximum number of results and the starting position for query results. ```java Limit(int maxResults, long startAt) ``` -------------------------------- ### Compare Query by Method Name and Parameter-Based Methods Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/module-summary Illustrates the equivalent functionality between a Query by Method Name and a parameter-based automatic query method for searching vehicles. ```java // Query by Method Name Vehicle[] findByMakeAndModelAndYear(String makerName, String model, int year, Sort... sorts); // parameter-based conditions @Find Vehicle[] searchFor(String make, String model, int year, Sort... sorts); ``` -------------------------------- ### Create a Limit for Maximum Results Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/limit Static factory method to create a Limit object that caps the number of results, starting from the first result. ```java static Limit of(int maxResults) ``` -------------------------------- ### Dynamic Sorting with Sort Parameters Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/sort Demonstrates how to use a variable number of Sort criteria as method parameters in a repository query. This allows for flexible, runtime-defined sorting. ```java Employee[] findByYearHired(int yearHired, Limit maxResults, Sort... sortBy); ... highestPaidNewHires = employees.findByYearHired(Year.now().getValue(), Limit.of(10), Sort.desc("salary"), Sort.asc("lastName"), Sort.asc("firstName")); ``` -------------------------------- ### Query by Method Name with Multiple Conditions Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-addendum-1.0 Demonstrates how multiple query conditions are mapped to repository method parameters. The order of parameters corresponds to the order of conditions in the method name. ```Java List findByNameLikeAndYearMadeBetweenAndPriceLessThan(String namePattern, int minYear, int maxYear, float maxPrice, Limit limit, Order sortBy) ``` -------------------------------- ### Initial Page Request for Cursor-based Pagination Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates obtaining the first page of results for cursor-based pagination using PageRequest.ofSize. ```Java PageRequest pageRequest = PageRequest.ofSize(50); Page page = customers.findByZipcode(55901, pageRequest); if (page.hasNext()) { pageRequest = page.nextPageRequest(); page = customers.findByZipcode(55901, pageRequest); ... ``` -------------------------------- ### Annotated Query with Explicit Parameter Mapping Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Example of an annotated query method using the @Param annotation to map a method parameter to a query parameter name. ```java @Query("where p.name = :prodname") Optional findByName(@Param("prodname") String name); ``` -------------------------------- ### Traversing Pages with Cursor-based Pagination Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates how to traverse pages of results using cursor-based pagination. It shows the initialization of sort orders and page requests, and the loop for fetching subsequent pages until no more pages are available. ```Java Order order = Order.by(_Customer.yearBorn.desc(), _Customer.name.asc(), _Customer.id.asc()); PageRequest pageRequest = PageRequest.ofSize(25); do { page = customers.withAveragePurchaseAbove(50.0f, pageRequest, order); ... if (page.hasNext()) { pageRequest = page.nextPageRequest(); } } while (page.hasNext()); ``` -------------------------------- ### Delete Entities by Parameter-Based Query Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/delete This example demonstrates using the @Delete annotation as a parameter-based automatic query method to delete entities matching specific criteria. ```APIDOC ## @Delete (Parameter-Based Query Deletion) ### Description Annotates a repository method to delete all entities satisfying parameter-based conditions. The entity type to be deleted is the primary entity type of the repository. ### Method Signature `void delete(...)` or `int delete(...)` or `long delete(...) ### Parameters * **Parameters** - Required - Every parameter of the annotated method must have exactly the same type and name as a persistent field or property of the entity class. Parameters of type `Sort`, `Order`, `Limit`, and `PageRequest` are prohibited. ### Return Value * **void**: No return value. * **int** or **long**: The number of deleted records. ### Notes An automatic query method annotated `Delete` removes every record which satisfies the parameter-based conditions from the database. If the method return type is `int` or `long`, the method must return the number of deleted records. ``` -------------------------------- ### Define Entity and Static Metamodel Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/metamodel/package-summary Illustrates how to define an entity class (`Product`) and its corresponding static metamodel (`_Product`). The metamodel provides type-safe access to entity attributes for use in operations like sorting and querying. ```java @Entity public class Product { @Id public long id; public String name; public float price; } @StaticMetamodel(Product.class) public interface _Product { String ID = "id"; String NAME = "name"; String PRICE = "price"; SortableAttribute id = new SortableAttributeRecord<>(ID); TextAttribute name = new TextAttributeRecord<>(NAME); SortableAttribute price = new SortableAttributeRecord<>(PRICE); } ``` -------------------------------- ### Delete Entity Instance Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/delete This example shows how to use the @Delete annotation to delete a specific entity instance. The method accepts a single parameter which is the entity to be deleted. ```APIDOC ## @Delete (Entity Instance Deletion) ### Description Marks a repository method to delete a given entity instance or instances from the database. ### Method Signature `void delete(E entity)` or `void delete(List entities)` or `void delete(E[] entities)` ### Parameters * **entity** (E) - Required - The entity instance or instances to be deleted. ### Notes Deletes are performed by matching the unique identifier of the entity. If the entity is versioned, the version is also checked for consistency. If no entity with a matching identifier is found, or if the version does not match, an `OptimisticLockingFailureException` must be raised. ``` -------------------------------- ### Query Annotation Usage Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/repository/query Demonstrates how to use the @Query annotation on repository methods with JDQL and JPQL, including examples with positional and named parameters, and various return types. ```APIDOC ## @Query Annotation ### Description Annotates a repository method to specify a custom query written in Jakarta Data Query Language (JDQL) or Jakarta Persistence Query Language (JPQL). This allows for flexible data retrieval and manipulation beyond basic CRUD operations. ### Usage Apply the `@Query` annotation to a repository interface method. The `value()` member of the annotation must contain the query string. ### Query Language Supports JDQL (Jakarta Data Query Language) and JPQL (Jakarta Persistence Query Language). ### Query Syntax - **JDQL**: Allows abbreviated syntax, including optional `from` and `select` clauses. - **JPQL**: Standard Jakarta Persistence Query Language. ### Parameters Queries can use: - **Named Parameters**: Form `:name`, where `name` is a legal Java identifier. - **Ordinal Parameters**: Form `?n`, where `n` are sequential positive integers starting from `1`. A query must not mix named and ordinal parameters. ### Method Parameters Method parameters can be associated with query parameters in the following ways: - **Named Parameter Match**: Method parameter name matches the named parameter in the query (requires `-parameters` compiler option). - **Ordinal Parameter Match**: Method parameter type and position match an ordinal parameter (e.g., the first method parameter corresponds to `?1`). - **Special Types**: Parameters can be of type `Limit`, `Order`, `PageRequest`, or `Sort`. The `@Param` annotation can be used to explicitly associate a method parameter with a named parameter. ### Return Types The return type of the annotated method must be consistent with the query result: - **Single Result**: `R` (throws `NonUniqueResultException` if multiple results, `EmptyResultException` if no results). - **At Most One Result**: `Optional`. - **Multiple Results**: `R[]`, `List`, `Stream`, `Page`, or `CursoredPage`. For `update` or `delete` statements, the return type must be `void`, `int`, or `long`. ### Example Repository Methods ```java @Repository public interface ExampleRepository extends CrudRepository { // JDQL with positional parameters @Query("where name = ?1") List findByName(String name); // JDQL with named parameter @Query("where status = :status") List findByStatus(@Param("status") String status); // JPQL using ordinal parameters @Query("from Entity where year(birthDate) = ?1") List findByBirthYear(int year); // JPQL using named parameters and Pageable @Query("select distinct name from Entity where length(name) >= :min and length(name) <= :max") Page findNamesOfLength(@Param("min") int minLength, @Param("max") int maxLength, PageRequest pageRequest); // Update statement @Query("update Entity e set e.status = :newStatus where e.id = :id") void updateStatus(@Param("id") Long id, @Param("newStatus") String newStatus); } ``` ### Restrictions - A method can have at most one query annotation (`@Find`, `@Query`, `@Insert`, `@Update`, `@Delete`, `@Save`). - JDQL query providers may have vendor-specific extensions not guaranteed to be portable. ``` -------------------------------- ### Query by Method Name: StartsWith Predicate Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/module-summary Use the 'StartsWith' keyword for strings to check if the beginning of the entity's attribute value matches the parameter value, which can be a pattern. ```java findByNameStartsWith(firstTwoLetters) ``` -------------------------------- ### Define a Custom Entity Annotation Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/spi/entitydefining Example of how a Jakarta Data provider can define a custom entity annotation using @EntityDefining. This annotation will be recognized by Jakarta Data components. ```java @EntityDefining @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface CustomEntity { } ``` -------------------------------- ### Create a Limit for a Range of Results Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/limit Static factory method to create a Limit object that restricts results to a specified range, defined by a start position and an end position. ```java static Limit range(long startAt, long endAt) ``` -------------------------------- ### Usage in Repository Methods Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/sort Demonstrates how to use Sort parameters in repository query methods for dynamic sorting. ```APIDOC ## Usage Example A query method of a repository may have a parameter or parameters of type `Sort` if its return type indicates that it may return multiple entities. Parameters of type `Sort` must occur after the method parameters representing regular parameters of the query itself. The parameter type `Sort...` allows a variable number of generic `Sort` criteria. ```java Employee[] findByYearHired(int yearHired, Limit maxResults, Sort... sortBy); ``` Example invocation: ```java highestPaidNewHires = employees.findByYearHired( Year.now().getValue(), Limit.of(10), Sort.desc("salary"), Sort.asc("lastName"), Sort.asc("firstName") ); ``` When multiple sorting criteria are provided, sorting is lexicographic, with the precedence of a criterion depending on its position with the list of criteria. Static sorting criteria (e.g., using `@OrderBy`) are applied first, followed by dynamic sorting criteria specified by instances of `Sort`. ``` -------------------------------- ### Sort Constructor and Static Factory Methods Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/sort This section covers the constructor for creating Sort instances and various static factory methods for defining different sorting orders (ascending, descending, case-insensitive). ```APIDOC ## Sort Class ### Description Defines sort criteria for an entity property. ### Constructor #### Sort(String property, boolean isAscending, boolean ignoreCase) Creates a `Sort` instance with specified property, direction, and case sensitivity. Parameters: - `property` (String) - The name of the property to order by. - `isAscending` (boolean) - `true` for ascending order, `false` for descending. - `ignoreCase` (boolean) - `true` to request case-insensitive ordering. ### Static Factory Methods #### static Sort of(String property, Direction direction, boolean ignoreCase) Creates a `Sort` instance with specified property, direction, and case sensitivity. Parameters: - `property` (String) - The property name to order by. - `direction` (Direction) - The direction of sorting (ascending or descending). - `ignoreCase` (boolean) - Whether to request case-insensitive ordering. Returns: A `Sort` instance. Never `null`. Throws: - `NullPointerException` - If any parameter is null. #### static Sort asc(String property) Creates a `Sort` instance with ascending direction and case-sensitive ordering. Parameters: - `property` (String) - The property name to order by. Returns: A `Sort` instance. Never `null`. Throws: - `NullPointerException` - If the property is null. #### static Sort ascIgnoreCase(String property) Creates a `Sort` instance with ascending direction and case-insensitive ordering. Parameters: - `property` (String) - The property name to order by. Returns: A `Sort` instance. Never `null`. Throws: - `NullPointerException` - If the property is null. #### static Sort desc(String property) Creates a `Sort` instance with descending direction and case-sensitive ordering. Parameters: - `property` (String) - The property name to order by. Returns: A `Sort` instance. Never `null`. Throws: - `NullPointerException` - If the property is null. #### static Sort descIgnoreCase(String property) Creates a `Sort` instance with descending direction and case-insensitive ordering. Parameters: - `property` (String) - The property name to order by. Returns: A `Sort` instance. Never `null`. Throws: - `NullPointerException` - If the property is null. ``` -------------------------------- ### Jakarta Validation Example Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/module-summary Demonstrates method and cascading validation using Jakarta Validation annotations on repository methods and entity fields. Ensure Jakarta Validation is present in your classpath. ```java import jakarta.validation.Valid; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; ... @Repository public interface AddressBook extends DataRepository { List findByEmailIn(@NotEmpty Set emails); @Save void save(@Valid Contact c); } @Entity public class Contact { @Email @NotNull public String email; @Id public long id; ... } ``` -------------------------------- ### Creating a Sort instance using static metamodel Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates a typesafe way to obtain a Sort instance using the static metamodel for ascending order by the 'name' field. ```java Sort nameAscending = _Employee.name.asc(); ``` -------------------------------- ### Paginate Data with Cursors Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates fetching a page of data using cursor-based pagination with sorting. ```java Order order = Order.by(Sort.asc("name"), Sort.asc("id"); PageRequest firstPageRequest = PageRequest.ofSize(4); CursoredPage page = people.findAll(firstPageRequest, order); ``` -------------------------------- ### Initial Page Request with PageRequest.ofSize Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/page/cursoredpage Request the initial page of results using PageRequest.ofSize to specify the page size. ```java page = employees.findByHoursWorkedGreaterThan(1500, PageRequest.ofSize(50)); ``` -------------------------------- ### Repository method with special parameters for sorting and pagination Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Demonstrates using special parameters like PageRequest and Order for advanced querying. The method returns a Page of products, sorted by price descending and ID ascending, with a specific name filter. ```java @Repository public interface ProductRepository extends BasicRepository { @Find Page findByName(String name, PageRequest pageRequest, Order order); @Query("where name like :pattern") List findByNameLike(String pattern, Limit max, Sort... sorts); } ``` -------------------------------- ### Use a Custom Entity Annotation Source: https://jakarta.ee/specifications/data/1.0/apidocs/jakarta.data/jakarta/data/spi/entitydefining Example of how an application can use a custom entity annotation, like @CustomEntity, which was defined by a provider. Jakarta Data will recognize classes annotated with @CustomEntity as entities. ```java @CustomEntity public class Book { // Implementation details here } ``` -------------------------------- ### Repository Method for Cursor-based Pagination with Before/After Cursor Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Defines a repository method to find products by name pattern using cursor-based pagination. It accepts a name pattern, page request, and sort criteria, returning a CursoredPage. ```Java @Repository public interface Products extends CrudRepository { @Query("where name like ?1") CursoredPage findByNameLike(String namePattern, PageRequest pageRequest, Order sorts); } ``` -------------------------------- ### Product Repository Extending BasicRepository Source: https://jakarta.ee/specifications/data/1.0/jakarta-data-1.0 Defines a repository for the Product entity by extending the BasicRepository interface, specifying Product as the entity type and Long as the ID type. ```java @Repository public interface ProductRepository extends BasicRepository { } ```