Class BaseEntityService<I extends Comparable<I> & Serializable,E extends BaseEntity<I>>
- java.lang.Object
-
- org.omnifaces.persistence.service.BaseEntityService<I,E>
-
- Type Parameters:
I
- The generic ID type.E
- The generic base entity type.
public abstract class BaseEntityService<I extends Comparable<I> & Serializable,E extends BaseEntity<I>> extends Object
Base entity service. Let your
Stateless
service classes extend from this. Ideally, you would not anymore have the need to inject theEntityManager
in your service class and it would suffice to just delegate all persistence actions to methods of this abstract class.You only need to let your entities extend from one of the following mapped super classes:
BaseEntity
TimestampedBaseEntity
VersionedBaseEntity
GeneratedIdEntity
TimestampedEntity
VersionedEntity
Logging
BaseEntityService
uses JULILogger
for logging.Level.FINER
will log thegetPage(Page, boolean)
arguments, the set parameter values and the full query result.Level.FINE
will log computed type mapping (the actual values ofI
andE
type paramters), and whether the ID is generated, and whether the entity isSoftDeletable
, and any discoveredElementCollection
,ManyToOne
,OneToOne
andOneToMany
mappings of the entity. This is internally used in order to be able to build proper queries to perform a search inside those fields.Level.WARNING
will log unparseable or illegal criteria values. TheBaseEntityService
will skip them and continue.Level.SEVERE
will log constraint violations wrapped in anyConstraintViolationException
duringpersist(BaseEntity)
andupdate(BaseEntity)
. Due to technical limitations, it will duringupdate()
only happen whenjakarta.persistence.validation.mode
property inpersistence.xml
is explicitly set toCALLBACK
(and thus not to its default ofAUTO
).
- See Also:
BaseEntity
,Page
,Criteria
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected static interface
BaseEntityService.CriteriaQueryBuilder<E>
Functional interface to fine-grain a JPA criteria query for any oflist(CriteriaQueryBuilder, Consumer)
orfind(CriteriaQueryBuilder, Consumer)
methods.protected static interface
BaseEntityService.MappedQueryBuilder<T>
Functional interface to fine-grain a JPA criteria query for any ofgetPage(Page, boolean)
methods taking a specific result type, such as an entity subclass (DTO).protected static interface
BaseEntityService.QueryBuilder<E>
Functional interface to fine-grain a JPA criteria query for any ofgetPage(Page, boolean)
methods.
-
Constructor Summary
Constructors Constructor Description BaseEntityService()
The constructor initializes the type mapping.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description protected Consumer<EntityManager>
afterPage()
Here you can in yourBaseEntityService
subclass define the callback method which needs to be invoked after any ofgetPage(Page, boolean)
methods is called.protected Consumer<EntityManager>
beforePage()
Here you can in yourBaseEntityService
subclass define the callback method which needs to be invoked before any ofgetPage(Page, boolean)
methods is called.protected long
countForeignKeyReferencesTo(E entity)
Returns count of all foreign key references to given entity.protected TypedQuery<Long>
createLongQuery(String jpql)
Create an instance ofTypedQuery
for executing the given Java Persistence Query Language statement which returns aLong
, usually a SELECT e.id or SELECT COUNT(e).protected Query
createNamedQuery(String name)
Create an instance ofQuery
for executing a Java Persistence Query Language statement identified by the given name, usually to perform an INSERT, UPDATE or DELETE.protected TypedQuery<E>
createNamedTypedQuery(String name)
Create an instance ofTypedQuery
for executing a Java Persistence Query Language statement identified by the given name, usually to perform a SELECT e.protected Query
createQuery(String jpql)
Create an instance ofQuery
for executing the given Java Persistence Query Language statement, usually to perform an INSERT, UPDATE or DELETE.protected TypedQuery<E>
createTypedQuery(String jpql)
Create an instance ofTypedQuery
for executing the given Java Persistence Query Language statement which returns aE
, usually to perform a SELECT e.protected <T> TypedQuery<T>
createTypedQuery(String jpql, Class<T> resultType)
Create an instance ofTypedQuery
for executing the given Java Persistence Query Language statement which returns the specifiedT
, usually to perform a SELECT t.void
delete(E entity)
Delete given entity.void
delete(Iterable<E> entities)
Delete given entities.protected boolean
exists(E entity)
Check whether given entity exists.protected E
fetchLazyBlobs(E entity)
Fetch all lazy blobs of given entity.protected Optional<E>
fetchLazyBlobs(Optional<E> entity)
Fetch all lazy blobs of given optional entity.protected E
fetchLazyCollections(E entity, Function<E,Collection<?>>... getters)
Fetch lazy collections of given entity on given getters.protected Optional<E>
fetchLazyCollections(Optional<E> entity, Function<E,Collection<?>>... getters)
Fetch lazy collections of given optional entity on given getters.protected E
fetchLazyMaps(E entity, Function<E,Map<?,?>>... getters)
Fetch lazy maps of given entity on given getters.protected Optional<E>
fetchLazyMaps(Optional<E> entity, Function<E,Map<?,?>>... getters)
Fetch lazy maps of given optional entity on given getters.protected Optional<E>
find(String jpql, Object... parameters)
Find entity by the given query and positional parameters, if any.protected Optional<E>
find(String jpql, Consumer<Map<String,Object>> parameters)
Find entity by the given query and mapped parameters, if any.protected Optional<E>
find(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder, Consumer<Map<String,Object>> parameters)
Find entity byBaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.Optional<E>
findById(I id)
Find entity by the given ID.protected Optional<E>
findById(I id, boolean includeSoftDeleted)
Find entity by the given ID and set whether it may return a soft deleted one.protected Optional<E>
findFirst(String jpql, Object... parameters)
Find first entity by the given query and positional parameters, if any.protected Optional<E>
findFirst(String jpql, Consumer<Map<String,Object>> parameters)
Find first entity by the given query and mapped parameters, if any.protected Optional<E>
findFirst(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder, Consumer<Map<String,Object>> parameters)
Find first entity byBaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.Optional<E>
findSoftDeletedById(I id)
Find soft deleted entity by the given ID.E
getById(I id)
Get entity by the given ID.protected E
getById(I id, boolean includeSoftDeleted)
Get entity by the given ID and set whether it may return a soft deleted one.List<E>
getByIds(Iterable<I> ids)
Get entities by the given IDs.protected List<E>
getByIds(Iterable<I> ids, boolean includeSoftDeleted)
Get entities by the given IDs and set whether it may include soft deleted ones.E
getByIdWithLoadGraph(I id, String entityGraphName)
Get entity by the given ID and entity graph name.static BaseEntityService<?,?>
getCurrentInstance()
Returns the currently activeBaseEntityService
from theSessionContext
.Database
getDatabase()
Returns the SQL database being used.protected EntityManager
getEntityManager()
Returns the entity manager being used.protected Class<E>
getEntityType()
Returns the actual type of the generic base entity typeE
.protected Class<I>
getIdentifierType()
Returns the actual type of the generic ID typeI
.protected EntityType<E>
getMetamodel()
Returns the metamodel of current base entity.<I extends Comparable<I> & Serializable,E extends BaseEntity<I>>
EntityType<E>getMetamodel(E entity)
Returns the metamodel of given base entity.org.omnifaces.utils.collection.PartialResultList<E>
getPage(Page page, boolean count)
Returns a partial result list based on givenPage
.protected <T extends E>
org.omnifaces.utils.collection.PartialResultList<T>getPage(Page page, boolean count, boolean cacheable, Class<T> resultType, BaseEntityService.MappedQueryBuilder<T> queryBuilder)
Returns a partial result list based on givenPage
, entity type andBaseEntityService.QueryBuilder
with the option whether to cache the results or not.protected org.omnifaces.utils.collection.PartialResultList<E>
getPage(Page page, boolean count, boolean cacheable, String... fetchFields)
Returns a partial result list based on givenPage
with the option whether to cache the results or not.protected org.omnifaces.utils.collection.PartialResultList<E>
getPage(Page page, boolean count, boolean cacheable, BaseEntityService.QueryBuilder<E> queryBuilder)
Returns a partial result list based on givenPage
, entity type andBaseEntityService.QueryBuilder
with the option whether to cache the results or not.protected <T extends E>
org.omnifaces.utils.collection.PartialResultList<T>getPage(Page page, boolean count, Class<T> resultType, BaseEntityService.MappedQueryBuilder<T> mappedQueryBuilder)
Returns a partial result list based on givenPage
, result type andBaseEntityService.MappedQueryBuilder
.protected org.omnifaces.utils.collection.PartialResultList<E>
getPage(Page page, boolean count, String... fetchFields)
Returns a partial result list based on givenPage
and fetch fields.protected org.omnifaces.utils.collection.PartialResultList<E>
getPage(Page page, boolean count, BaseEntityService.QueryBuilder<E> queryBuilder)
Returns a partial result list based on givenPage
andBaseEntityService.QueryBuilder
.Provider
getProvider()
Returns the JPA provider being used.E
getSoftDeletedById(I id)
Get soft deleted entity by the given ID.protected boolean
isGeneratedId()
Returns whether the ID is generated.List<E>
list()
List all entities.protected List<E>
list(boolean includeSoftDeleted)
List all entities and set whether it may include soft deleted ones.protected List<E>
list(String jpql, Object... parameters)
List entities matching the given query and positional parameters, if any.protected List<E>
list(String jpql, Consumer<Map<String,Object>> parameters)
List entities matching the given query and mapped parameters, if any.protected List<E>
list(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder, Consumer<Map<String,Object>> parameters)
List entities matching theBaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.List<E>
listSoftDeleted()
List all entities that have been soft deleted.protected E
manage(E entity)
Make given entity managed.protected <E> E
manageIfNecessary(E entity)
Make any given entity managed if necessary.protected <T extends E>
Consumer<TypedQuery<?>>onPage(Class<T> resultType, boolean cacheable)
Here you can in yourBaseEntityService
subclass define the callback method which needs to be invoked when any query involved ingetPage(Page, boolean)
is about to be executed.I
persist(E entity)
Persist given entity and immediately perform a flush.void
reset(E entity)
Reset given entity.E
save(E entity)
Save given entity.protected E
saveAndFlush(E entity)
Save given entity viasave(BaseEntity)
and immediately perform a flush so that all changes in managed entities so far in the current transaction are persisted.void
softDelete(E entity)
Soft delete given entity.void
softDelete(Iterable<E> entities)
Soft delete given entities.void
softUndelete(E entity)
Soft undelete given entity.void
softUndelete(Iterable<E> entities)
Soft undelete given entities.E
update(E entity)
Update given entity.List<E>
update(Iterable<E> entities)
Update given entities.protected int
update(String jpql, Object... parameters)
Update or delete all entities matching the given query and positional parameters, if any.protected int
update(String jpql, Consumer<Map<String,Object>> parameters)
Update or delete all entities matching the given query and mapped parameters, if any.protected E
updateAndFlush(E entity)
Update given entity viaupdate(BaseEntity)
and immediately perform a flush so that all changes in managed entities so far in the current transaction are persisted.
-
-
-
Method Detail
-
getProvider
public Provider getProvider()
Returns the JPA provider being used. This is immutable (you can't override the method to change the internally used value).- Returns:
- The JPA provider being used.
-
getDatabase
public Database getDatabase()
Returns the SQL database being used. This is immutable (you can't override the method to change the internally used value).- Returns:
- The SQL database being used.
-
getIdentifierType
protected Class<I> getIdentifierType()
Returns the actual type of the generic ID typeI
. This is immutable (you can't override the method to change the internally used value).- Returns:
- The actual type of the generic ID type
I
.
-
getEntityType
protected Class<E> getEntityType()
Returns the actual type of the generic base entity typeE
. This is immutable (you can't override the method to change the internally used value).- Returns:
- The actual type of the generic base entity type
E
.
-
isGeneratedId
protected boolean isGeneratedId()
Returns whether the ID is generated. This is immutable (you can't override the method to change the internally used value).- Returns:
- Whether the ID is generated.
-
getEntityManager
protected EntityManager getEntityManager()
Returns the entity manager being used. When you have only one persistence unit, then you don't need to override this. When you have multiple persistence units, then you need to extend theBaseEntityService
like below wherein you supply the persistence unit specific entity manager and then let all your service classes extend from it instead.public abstract class YourBaseEntityService<E extends BaseEntity<Long>> extends BaseEntityService<Long, E> { @PersistenceContext(unitName = "yourPersistenceUnitName") private EntityManager entityManager; @Override public EntityManager getEntityManager() { return entityManager; } }
- Returns:
- The entity manager being used.
-
getMetamodel
protected EntityType<E> getMetamodel()
Returns the metamodel of current base entity.- Returns:
- The metamodel of current base entity.
-
getMetamodel
public <I extends Comparable<I> & Serializable,E extends BaseEntity<I>> EntityType<E> getMetamodel(E entity)
Returns the metamodel of given base entity.- Type Parameters:
I
- The generic ID type of the given base entity.E
- The generic base entity type of the given base entity.- Parameters:
entity
- Base entity to obtain metamodel for.- Returns:
- The metamodel of given base entity.
-
createNamedTypedQuery
protected TypedQuery<E> createNamedTypedQuery(String name)
Create an instance ofTypedQuery
for executing a Java Persistence Query Language statement identified by the given name, usually to perform a SELECT e.- Parameters:
name
- The name of the Java Persistence Query Language statement defined in metadata, which can be either aNamedQuery
or a<persistence-unit><mapping-file>
.- Returns:
- An instance of
TypedQuery
for executing a Java Persistence Query Language statement identified by the given name, usually to perform a SELECT e.
-
createNamedQuery
protected Query createNamedQuery(String name)
Create an instance ofQuery
for executing a Java Persistence Query Language statement identified by the given name, usually to perform an INSERT, UPDATE or DELETE.- Parameters:
name
- The name of the Java Persistence Query Language statement defined in metadata, which can be either aNamedQuery
or a<persistence-unit><mapping-file>
.- Returns:
- An instance of
Query
for executing a Java Persistence Query Language statement identified by the given name, usually to perform an INSERT, UPDATE or DELETE.
-
createTypedQuery
protected <T> TypedQuery<T> createTypedQuery(String jpql, Class<T> resultType)
Create an instance ofTypedQuery
for executing the given Java Persistence Query Language statement which returns the specifiedT
, usually to perform a SELECT t.- Type Parameters:
T
- The generic result type.- Parameters:
jpql
- The Java Persistence Query Language statement.resultType
- The result type.- Returns:
- An instance of
TypedQuery
for executing the given Java Persistence Query Language statement which returns the specifiedT
, usually to perform a SELECT t.
-
createTypedQuery
protected TypedQuery<E> createTypedQuery(String jpql)
Create an instance ofTypedQuery
for executing the given Java Persistence Query Language statement which returns aE
, usually to perform a SELECT e.- Parameters:
jpql
- The Java Persistence Query Language statement.- Returns:
- An instance of
TypedQuery
for executing the given Java Persistence Query Language statement which returns aE
, usually to perform a SELECT e.
-
createLongQuery
protected TypedQuery<Long> createLongQuery(String jpql)
Create an instance ofTypedQuery
for executing the given Java Persistence Query Language statement which returns aLong
, usually a SELECT e.id or SELECT COUNT(e).- Parameters:
jpql
- The Java Persistence Query Language statement.- Returns:
- An instance of
TypedQuery
for executing the given Java Persistence Query Language statement which returns aLong
, usually a SELECT e.id or SELECT COUNT(e).
-
createQuery
protected Query createQuery(String jpql)
Create an instance ofQuery
for executing the given Java Persistence Query Language statement, usually to perform an INSERT, UPDATE or DELETE.- Parameters:
jpql
- The Java Persistence Query Language statement.- Returns:
- An instance of
Query
for executing the given Java Persistence Query Language statement, usually to perform an INSERT, UPDATE or DELETE.
-
find
protected Optional<E> find(String jpql, Object... parameters)
Find entity by the given query and positional parameters, if any.Usage example:
Optional<Foo> foo = find("SELECT f FROM Foo f WHERE f.bar = ?1 AND f.baz = ?2", bar, baz);
Short jpql is also supported:
Optional<Foo> foo = find("WHERE bar = ?1 AND baz = ?2", bar, baz);
- Parameters:
jpql
- The Java Persistence Query Language statement.parameters
- The positional query parameters, if any.- Returns:
- Found entity matching the given query and positional parameters, if any.
- Throws:
NonUniqueResultException
- When more than one entity is found matching the given query and positional parameters.
-
find
protected Optional<E> find(String jpql, Consumer<Map<String,Object>> parameters)
Find entity by the given query and mapped parameters, if any.Usage example:
Optional<Foo> foo = find("SELECT f FROM Foo f WHERE f.bar = :bar AND f.baz = :baz", params -> { params.put("bar", bar); params.put("baz", baz); });
Short jpql is also supported:
Optional<Foo> foo = find("WHERE bar = :bar AND baz = :baz", params -> { params.put("bar", bar); params.put("baz", baz); });
- Parameters:
jpql
- The Java Persistence Query Language statement.parameters
- To put the mapped query parameters in.- Returns:
- Found entity matching the given query and mapped parameters, if any.
- Throws:
NonUniqueResultException
- When more than one entity is found matching the given query and mapped parameters.
-
find
protected Optional<E> find(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder, Consumer<Map<String,Object>> parameters)
Find entity byBaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.Usage example:
Optional<Foo> foo = find( (criteriaBuilder, query, root) -> { query.where(criteriaBuilder.equal(root.get("type"), criteriaBuilder.parameter(Type.class, "foo")); }, params -> { params.put("foo", Type.FOO); } );
- Parameters:
queryBuilder
- This creates the JPA criteria query.parameters
- To put the mapped query parameters in.- Returns:
- Found entity matching
BaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any. - Throws:
NonUniqueResultException
- When more than one entity is found matching given query and mapped parameters.
-
findFirst
protected Optional<E> findFirst(String jpql, Object... parameters)
Find first entity by the given query and positional parameters, if any. The difference withfind(String, Object...)
is that it doesn't throwNonUniqueResultException
when there are multiple matches.Usage example:
Optional<Foo> foo = findFirst("SELECT f FROM Foo f WHERE f.bar = ?1 AND f.baz = ?2", bar, baz);
Short jpql is also supported:
Optional<Foo> foo = findFirst("WHERE bar = ?1 AND baz = ?2", bar, baz);
- Parameters:
jpql
- The Java Persistence Query Language statement.parameters
- The positional query parameters, if any.- Returns:
- Found entity matching the given query and positional parameters, if any.
-
findFirst
protected Optional<E> findFirst(String jpql, Consumer<Map<String,Object>> parameters)
Find first entity by the given query and mapped parameters, if any. The difference withfind(String, Consumer)
is that it doesn't throwNonUniqueResultException
when there are multiple matches.Usage example:
Optional<Foo> foo = findFirst("SELECT f FROM Foo f WHERE f.bar = :bar AND f.baz = :baz", params -> { params.put("bar", bar); params.put("baz", baz); });
Short jpql is also supported:
Optional<Foo> foo = findFirst("WHERE bar = :bar AND baz = :baz", params -> { params.put("bar", bar); params.put("baz", baz); });
- Parameters:
jpql
- The Java Persistence Query Language statement.parameters
- To put the mapped query parameters in.- Returns:
- Found entity matching the given query and mapped parameters, if any.
-
findFirst
protected Optional<E> findFirst(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder, Consumer<Map<String,Object>> parameters)
Find first entity byBaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any. The difference withfind(CriteriaQueryBuilder, Consumer)
is that it doesn't throwNonUniqueResultException
when there are multiple matches.Usage example:
Optional<Foo> foo = findFirst( (criteriaBuilder, query, root) -> { query.where(criteriaBuilder.equal(root.get("type"), criteriaBuilder.parameter(Type.class, "foo")); }, params -> { params.put("foo", Type.FOO); } );
- Parameters:
queryBuilder
- This creates the JPA criteria query.parameters
- To put the mapped query parameters in.- Returns:
- Found entity matching
BaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.
-
findById
public Optional<E> findById(I id)
Find entity by the given ID. This does not include soft deleted one.- Parameters:
id
- Entity ID to find entity for.- Returns:
- Found entity, if any.
-
findById
protected Optional<E> findById(I id, boolean includeSoftDeleted)
Find entity by the given ID and set whether it may return a soft deleted one.- Parameters:
id
- Entity ID to find entity for.includeSoftDeleted
- Whether to include soft deleted ones in the search.- Returns:
- Found entity, if any.
-
findSoftDeletedById
public Optional<E> findSoftDeletedById(I id)
Find soft deleted entity by the given ID.- Parameters:
id
- Entity ID to find soft deleted entity for.- Returns:
- Found soft deleted entity, if any.
- Throws:
NonSoftDeletableEntityException
- When entity doesn't haveSoftDeletable
annotation set on any of its fields.
-
getById
public E getById(I id)
Get entity by the given ID. This does not include soft deleted one.- Parameters:
id
- Entity ID to get entity by.- Returns:
- Found entity, or
null
if there is none.
-
getById
protected E getById(I id, boolean includeSoftDeleted)
Get entity by the given ID and set whether it may return a soft deleted one.- Parameters:
id
- Entity ID to get entity by.includeSoftDeleted
- Whether to include soft deleted ones in the search.- Returns:
- Found entity, or
null
if there is none.
-
getByIdWithLoadGraph
public E getByIdWithLoadGraph(I id, String entityGraphName)
Get entity by the given ID and entity graph name.- Parameters:
id
- Entity ID to get entity by.entityGraphName
- Entity graph name.- Returns:
- Found entity, or
null
if there is none.
-
getSoftDeletedById
public E getSoftDeletedById(I id)
Get soft deleted entity by the given ID.- Parameters:
id
- Entity ID to get soft deleted entity by.- Returns:
- Found soft deleted entity, or
null
if there is none. - Throws:
NonSoftDeletableEntityException
- When entity doesn't haveSoftDeletable
annotation set on any of its fields.
-
getByIds
public List<E> getByIds(Iterable<I> ids)
Get entities by the given IDs. The default ordering is by ID, descending. This does not include soft deleted ones.- Parameters:
ids
- Entity IDs to get entities by.- Returns:
- Found entities, or an empty set if there is none.
-
getByIds
protected List<E> getByIds(Iterable<I> ids, boolean includeSoftDeleted)
Get entities by the given IDs and set whether it may include soft deleted ones. The default ordering is by ID, descending.- Parameters:
ids
- Entity IDs to get entities by.includeSoftDeleted
- Whether to include soft deleted ones in the search.- Returns:
- Found entities, optionally including soft deleted ones, or an empty set if there is none.
- Throws:
NonSoftDeletableEntityException
- When entity doesn't haveSoftDeletable
annotation set on any of its fields.
-
exists
protected boolean exists(E entity)
Check whether given entity exists. This method supports proxied entities.- Parameters:
entity
- Entity to check.- Returns:
- Whether entity with given entity exists.
-
list
public List<E> list()
List all entities. The default ordering is by ID, descending. This does not include soft deleted entities.- Returns:
- List of all entities.
-
list
protected List<E> list(boolean includeSoftDeleted)
List all entities and set whether it may include soft deleted ones. The default ordering is by ID, descending.- Parameters:
includeSoftDeleted
- Whether to include soft deleted ones in the search.- Returns:
- List of all entities, optionally including soft deleted ones.
- Throws:
NonSoftDeletableEntityException
- When entity doesn't haveSoftDeletable
annotation set on any of its fields.
-
listSoftDeleted
public List<E> listSoftDeleted()
List all entities that have been soft deleted. The default ordering is by ID, descending.- Returns:
- List of all soft deleted entities.
- Throws:
NonSoftDeletableEntityException
- When entity doesn't haveSoftDeletable
annotation set on any of its fields.
-
list
protected List<E> list(String jpql, Object... parameters)
List entities matching the given query and positional parameters, if any.Usage example:
List<Foo> foos = list("SELECT f FROM Foo f WHERE f.bar = ?1 AND f.baz = ?2", bar, baz);
Short jpql is also supported:
List<Foo> foos = list("WHERE bar = ?1 AND baz = ?2", bar, baz);
- Parameters:
jpql
- The Java Persistence Query Language statement.parameters
- The positional query parameters, if any.- Returns:
- List of entities matching the given query and positional parameters, if any.
-
list
protected List<E> list(String jpql, Consumer<Map<String,Object>> parameters)
List entities matching the given query and mapped parameters, if any.Usage example:
List<Foo> foos = list("SELECT f FROM Foo f WHERE f.bar = :bar AND f.baz = :baz", params -> { params.put("bar", bar); params.put("baz", baz); });
Short jpql is also supported:
List<Foo> foos = list("WHERE bar = :bar AND baz = :baz", params -> { params.put("bar", bar); params.put("baz", baz); });
- Parameters:
jpql
- The Java Persistence Query Language statement.parameters
- To put the mapped query parameters in.- Returns:
- List of entities matching the given query and mapped parameters, if any.
-
list
protected List<E> list(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder, Consumer<Map<String,Object>> parameters)
List entities matching theBaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.Usage example:
List<Foo> foo = list( (criteriaBuilder, query, root) -> { query.where(criteriaBuilder.equal(root.get("type"), criteriaBuilder.parameter(Type.class, "foo")); }, params -> { params.put("foo", Type.FOO); } );
- Parameters:
queryBuilder
- This creates the JPA criteria query.parameters
- To put the mapped query parameters in.- Returns:
- List of entities matching the
BaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.
-
persist
public I persist(E entity)
Persist given entity and immediately perform a flush. Any bean validation constraint violation will be logged separately.- Parameters:
entity
- Entity to persist.- Returns:
- Entity ID.
- Throws:
IllegalEntityStateException
- When entity is already persisted or its ID is not generated.
-
update
public E update(E entity)
Update given entity. Ifjakarta.persistence.validation.mode
property inpersistence.xml
is explicitly set toCALLBACK
(and thus not to its default ofAUTO
), then any bean validation constraint violation will be logged separately. Due to technical limitations, this effectively means that bean validation is invoked twice. First in this method in order to be able to obtain the constraint violations and then once more while JTA is committing the transaction, but is executed beyond the scope of this method.- Parameters:
entity
- Entity to update.- Returns:
- Updated entity.
- Throws:
IllegalEntityStateException
- When entity is not persisted or its ID is not generated.
-
updateAndFlush
protected E updateAndFlush(E entity)
Update given entity viaupdate(BaseEntity)
and immediately perform a flush so that all changes in managed entities so far in the current transaction are persisted. This is particularly useful when you intend to process the given entity further in an asynchronous service method.- Parameters:
entity
- Entity to update.- Returns:
- Updated entity.
- Throws:
IllegalEntityStateException
- When entity is not persisted or its ID is not generated.
-
update
public List<E> update(Iterable<E> entities)
Update given entities.- Parameters:
entities
- Entities to update.- Returns:
- Updated entities.
- Throws:
IllegalEntityStateException
- When at least one entity has no ID.
-
update
protected int update(String jpql, Object... parameters)
Update or delete all entities matching the given query and positional parameters, if any.Usage example:
int affectedRows = update("UPDATE Foo f SET f.bar = ?1 WHERE f.baz = ?2", bar, baz);
Short jpql is also supported:
int affectedRows = update("SET bar = ?1 WHERE baz = ?2", bar, baz);
- Parameters:
jpql
- The Java Persistence Query Language statement.parameters
- The positional query parameters, if any.- Returns:
- The number of entities updated or deleted.
- See Also:
Query.executeUpdate()
-
update
protected int update(String jpql, Consumer<Map<String,Object>> parameters)
Update or delete all entities matching the given query and mapped parameters, if any.Usage example:
int affectedRows = update("UPDATE Foo f SET f.bar = :bar WHERE f.baz = :baz", params -> { params.put("bar", bar); params.put("baz", baz); });
Short jpql is also supported:
int affectedRows = update("SET bar = :bar WHERE baz = :baz", params -> { params.put("bar", bar); params.put("baz", baz); });
- Parameters:
jpql
- The Java Persistence Query Language statement.parameters
- To put the mapped query parameters in, if any.- Returns:
- The number of entities updated or deleted.
- See Also:
Query.executeUpdate()
-
save
public E save(E entity)
Save given entity. This will automatically determine based on the presence of generated entity ID, or existence of an entity in the data store whether topersist(BaseEntity)
or toupdate(BaseEntity)
.- Parameters:
entity
- Entity to save.- Returns:
- Saved entity.
-
saveAndFlush
protected E saveAndFlush(E entity)
Save given entity viasave(BaseEntity)
and immediately perform a flush so that all changes in managed entities so far in the current transaction are persisted. This is particularly useful when you intend to process the given entity further in an asynchronous service method.- Parameters:
entity
- Entity to save.- Returns:
- Saved entity.
-
delete
public void delete(E entity)
Delete given entity.- Parameters:
entity
- Entity to delete.- Throws:
NonDeletableEntityException
- When entity hasNonDeletable
annotation set.IllegalEntityStateException
- When entity has no ID.EntityNotFoundException
- When entity has in meanwhile been deleted.
-
softDelete
public void softDelete(E entity)
Soft delete given entity.- Parameters:
entity
- Entity to soft delete.- Throws:
NonSoftDeletableEntityException
- When entity doesn't haveSoftDeletable
annotation set on any of its fields.IllegalEntityStateException
- When entity has no ID.EntityNotFoundException
- When entity has in meanwhile been hard deleted.
-
softUndelete
public void softUndelete(E entity)
Soft undelete given entity.- Parameters:
entity
- Entity to soft undelete.- Throws:
NonSoftDeletableEntityException
- When entity doesn't haveSoftDeletable
annotation set on any of its fields.IllegalEntityStateException
- When entity has no ID.EntityNotFoundException
- When entity has in meanwhile been hard deleted.
-
delete
public void delete(Iterable<E> entities)
Delete given entities.- Parameters:
entities
- Entities to delete.- Throws:
NonDeletableEntityException
- When at least one entity hasNonDeletable
annotation set.IllegalEntityStateException
- When at least one entity has no ID.EntityNotFoundException
- When at least one entity has in meanwhile been deleted.
-
softDelete
public void softDelete(Iterable<E> entities)
Soft delete given entities.- Parameters:
entities
- Entities to soft delete.- Throws:
NonSoftDeletableEntityException
- When entity doesn't haveSoftDeletable
annotation set on any of its fields.IllegalEntityStateException
- When at least one entity has no ID.EntityNotFoundException
- When at least one entity has in meanwhile been hard deleted.
-
softUndelete
public void softUndelete(Iterable<E> entities)
Soft undelete given entities.- Parameters:
entities
- Entities to soft undelete.- Throws:
NonSoftDeletableEntityException
- When entity doesn't haveSoftDeletable
annotation set on any of its fields.IllegalEntityStateException
- When at least one entity has no ID.EntityNotFoundException
- When at least one entity has in meanwhile been hard deleted.
-
manage
protected E manage(E entity)
Make given entity managed. NOTE: This will discard any unmanaged changes in the given entity! This is particularly useful in case you intend to make sure that you have the most recent version at hands. This method also supports proxied entities as well as DTOs.- Parameters:
entity
- Entity to manage.- Returns:
- The managed entity.
- Throws:
NullPointerException
- When given entity isnull
.IllegalEntityStateException
- When entity has no ID.EntityNotFoundException
- When entity has in meanwhile been deleted.
-
manageIfNecessary
protected <E> E manageIfNecessary(E entity)
Make any given entity managed if necessary. NOTE: This will discard any unmanaged changes in the given entity! This is particularly useful in case you intend to make sure that you have the most recent version at hands. This method also supportsnull
entities as well as proxied entities as well as DTOs.- Type Parameters:
E
- The generic entity type.- Parameters:
entity
- Entity to manage, may benull
.- Returns:
- The managed entity, or
null
whennull
was supplied. It leniently returns the very same argument if the entity has no ID or has been deleted in the meanwhile. - Throws:
IllegalArgumentException
- When the given entity is actually not an instance ofBaseEntity
.
-
reset
public void reset(E entity)
Reset given entity. This will discard any changes in given entity. The given entity must be unmanaged/detached. The actual intent of this method is to have the opportunity to completely reset the state of a given entity which might have been edited in the client, without changing the reference. This is generally useful when the entity is in turn held in some collection and you'd rather not manually remove and reinsert it in the collection. This method supports proxied entities.- Parameters:
entity
- Entity to reset.- Throws:
IllegalEntityStateException
- When entity is already managed, or has no ID.EntityNotFoundException
- When entity has in meanwhile been deleted.
-
countForeignKeyReferencesTo
protected long countForeignKeyReferencesTo(E entity)
Returns count of all foreign key references to given entity. This is particularly useful in case you intend to check if the given entity is still referenced elsewhere in database.- Parameters:
entity
- Entity to count all foreign key references for.- Returns:
- Count of all foreign key references to given entity.
-
fetchLazyCollections
protected E fetchLazyCollections(E entity, Function<E,Collection<?>>... getters)
Fetch lazy collections of given entity on given getters. If no getters are supplied, then it will fetch every singlePluralAttribute
not of typePluralAttribute.CollectionType.MAP
. Note that the implementation does for simplicitly not check if those are actually lazy or eager.Usage example:
Foo fooWithBarsAndBazs = fetchLazyCollections(getById(fooId), Foo::getBars, Foo::getBazs);
- Parameters:
entity
- Entity instance to fetch lazy collections on.getters
- Getters of those lazy collections.- Returns:
- The same entity, useful if you want to continue using it immediately.
-
fetchLazyCollections
protected Optional<E> fetchLazyCollections(Optional<E> entity, Function<E,Collection<?>>... getters)
Fetch lazy collections of given optional entity on given getters. If no getters are supplied, then it will fetch every singlePluralAttribute
not of typePluralAttribute.CollectionType.MAP
. Note that the implementation does for simplicitly not check if those are actually lazy or eager.Usage example:
Optional<Foo> fooWithBarsAndBazs = fetchLazyCollections(findById(fooId), Foo::getBars, Foo::getBazs);
- Parameters:
entity
- Optional entity instance to fetch lazy collections on.getters
- Getters of those lazy collections.- Returns:
- The same optional entity, useful if you want to continue using it immediately.
-
fetchLazyMaps
protected E fetchLazyMaps(E entity, Function<E,Map<?,?>>... getters)
Fetch lazy maps of given entity on given getters. If no getters are supplied, then it will fetch every singlePluralAttribute
of typePluralAttribute.CollectionType.MAP
. Note that the implementation does for simplicitly not check if those are actually lazy or eager.Usage example:
Foo fooWithBarsAndBazs = fetchLazyCollections(getById(fooId), Foo::getBars, Foo::getBazs);
- Parameters:
entity
- Entity instance to fetch lazy maps on.getters
- Getters of those lazy collections.- Returns:
- The same entity, useful if you want to continue using it immediately.
-
fetchLazyMaps
protected Optional<E> fetchLazyMaps(Optional<E> entity, Function<E,Map<?,?>>... getters)
Fetch lazy maps of given optional entity on given getters. If no getters are supplied, then it will fetch every singlePluralAttribute
of typePluralAttribute.CollectionType.MAP
. Note that the implementation does for simplicitly not check if those are actually lazy or eager.Usage example:
Optional<Foo> fooWithBarsAndBazs = fetchLazyCollections(findById(fooId), Foo::getBars, Foo::getBazs);
- Parameters:
entity
- Optional entity instance to fetch lazy maps on.getters
- Getters of those lazy collections.- Returns:
- The same optional entity, useful if you want to continue using it immediately.
-
fetchLazyBlobs
protected E fetchLazyBlobs(E entity)
Fetch all lazy blobs of given entity. Note that the implementation does for simplicitly not check if those are actually lazy or eager.- Parameters:
entity
- Entity instance to fetch all blobs on.- Returns:
- The same entity, useful if you want to continue using it immediately.
-
fetchLazyBlobs
protected Optional<E> fetchLazyBlobs(Optional<E> entity)
Fetch all lazy blobs of given optional entity. Note that the implementation does for simplicitly not check if those are actually lazy or eager.- Parameters:
entity
- Optional entity instance to fetch all blobs on.- Returns:
- The same optional entity, useful if you want to continue using it immediately.
-
beforePage
protected Consumer<EntityManager> beforePage()
Here you can in yourBaseEntityService
subclass define the callback method which needs to be invoked before any ofgetPage(Page, boolean)
methods is called. For example, to set a vendor specificEntityManager
hint. The default implementation returns a no-op callback.- Returns:
- The callback method which is invoked before any of
getPage(Page, boolean)
methods is called.
-
onPage
protected <T extends E> Consumer<TypedQuery<?>> onPage(Class<T> resultType, boolean cacheable)
Here you can in yourBaseEntityService
subclass define the callback method which needs to be invoked when any query involved ingetPage(Page, boolean)
is about to be executed. For example, to set a vendor specificQuery
hint. The default implementation sets Hibernate, EclipseLink and JPA 2.0 cache-related hints. Whencacheable
argument istrue
, then it reads from cache where applicable, else it will read from DB and force a refresh of cache. Note that this is not supported by OpenJPA.- Type Parameters:
T
- The generic type of the entity or a DTO subclass thereof.- Parameters:
resultType
- The result type which can be the entity type itself or a DTO subclass thereof.cacheable
- Whether the results should be cacheable.- Returns:
- The callback method which is invoked when any query involved in
getPage(Page, boolean)
is about to be executed.
-
afterPage
protected Consumer<EntityManager> afterPage()
Here you can in yourBaseEntityService
subclass define the callback method which needs to be invoked after any ofgetPage(Page, boolean)
methods is called. For example, to remove a vendor specificEntityManager
hint. The default implementation returns a no-op callback.- Returns:
- The callback method which is invoked after any of
getPage(Page, boolean)
methods is called.
-
getPage
public org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count)
Returns a partial result list based on givenPage
. This will by default cache the results.Usage examples:
Page first10Records = Page.of(0, 10); PartialResultList<Foo> foos = getPage(first10Records, true);
Map<String, Object> criteria = new HashMap<>(); criteria.put("bar", bar); // Exact match. criteria.put("baz", IgnoreCase.value(baz)); // Case insensitive match. criteria.put("faz", Like.contains(faz)); // Case insensitive LIKE match. criteria.put("kaz", Order.greaterThan(kaz)); // Greater than match. Page first10RecordsMatchingCriteriaOrderedByBar = Page.with().allMatch(criteria).orderBy("bar", true).range(0, 10); PartialResultList<Foo> foos = getPage(first10RecordsMatchingCriteriaOrderedByBar, true);
- Parameters:
page
- The page to return a partial result list for.count
- Whether to run theCOUNT(id)
query to estimate total number of results. This will be available byPartialResultList.getEstimatedTotalNumberOfResults()
.- Returns:
- A partial result list based on given
Page
. - See Also:
Page
,Criteria
-
getPage
protected org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, String... fetchFields)
Returns a partial result list based on givenPage
and fetch fields. This will by default cache the results.Usage examples:
Page first10Records = Page.of(0, 10); PartialResultList<Foo> foosWithBars = getPage(first10Records, true, "bar");
Map<String, Object> criteria = new HashMap<>(); criteria.put("bar", bar); // Exact match. criteria.put("baz", IgnoreCase.value(baz)); // Case insensitive match. criteria.put("faz", Like.contains(faz)); // Case insensitive LIKE match. criteria.put("kaz", Order.greaterThan(kaz)); // Greater than match. Page first10RecordsMatchingCriteriaOrderedByBar = Page.with().allMatch(criteria).orderBy("bar", true).range(0, 10); PartialResultList<Foo> foosWithBars = getPage(first10RecordsMatchingCriteriaOrderedByBar, true, "bar");
- Parameters:
page
- The page to return a partial result list for.count
- Whether to run theCOUNT(id)
query to estimate total number of results. This will be available byPartialResultList.getEstimatedTotalNumberOfResults()
.fetchFields
- Optionally, all (lazy loaded) fields to be explicitly fetched during the query. Each field can represent a JavaBean path, like as you would do in EL, such asparent.child.subchild
.- Returns:
- A partial result list based on given
Page
. - See Also:
Page
,Criteria
-
getPage
protected org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, boolean cacheable, String... fetchFields)
Returns a partial result list based on givenPage
with the option whether to cache the results or not.Usage example: see
getPage(Page, boolean)
andgetPage(Page, boolean, String...)
.- Parameters:
page
- The page to return a partial result list for.count
- Whether to run theCOUNT(id)
query to estimate total number of results. This will be available byPartialResultList.getEstimatedTotalNumberOfResults()
.cacheable
- Whether the results should be cacheable.fetchFields
- Optionally, all (lazy loaded) fields to be explicitly fetched during the query. Each field can represent a JavaBean path, like as you would do in EL, such asparent.child.subchild
.- Returns:
- A partial result list based on given
Page
. - See Also:
Page
,Criteria
-
getPage
protected org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, BaseEntityService.QueryBuilder<E> queryBuilder)
Returns a partial result list based on givenPage
andBaseEntityService.QueryBuilder
. This will by default cache the results.Usage example: see
BaseEntityService.QueryBuilder
.- Parameters:
page
- The page to return a partial result list for.count
- Whether to run theCOUNT(id)
query to estimate total number of results. This will be available byPartialResultList.getEstimatedTotalNumberOfResults()
.queryBuilder
- This allows fine-graining the JPA criteria query.- Returns:
- A partial result list based on given
Page
andBaseEntityService.QueryBuilder
. - See Also:
Page
,Criteria
-
getPage
protected org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, boolean cacheable, BaseEntityService.QueryBuilder<E> queryBuilder)
Returns a partial result list based on givenPage
, entity type andBaseEntityService.QueryBuilder
with the option whether to cache the results or not.Usage example: see
BaseEntityService.QueryBuilder
.- Parameters:
page
- The page to return a partial result list for.count
- Whether to run theCOUNT(id)
query to estimate total number of results. This will be available byPartialResultList.getEstimatedTotalNumberOfResults()
.cacheable
- Whether the results should be cacheable.queryBuilder
- This allows fine-graining the JPA criteria query.- Returns:
- A partial result list based on given
Page
andBaseEntityService.QueryBuilder
. - See Also:
Page
,Criteria
-
getPage
protected <T extends E> org.omnifaces.utils.collection.PartialResultList<T> getPage(Page page, boolean count, Class<T> resultType, BaseEntityService.MappedQueryBuilder<T> mappedQueryBuilder)
Returns a partial result list based on givenPage
, result type andBaseEntityService.MappedQueryBuilder
. This will by default cache the results.Usage example: see
BaseEntityService.MappedQueryBuilder
.- Type Parameters:
T
- The generic type of the entity or a DTO subclass thereof.- Parameters:
page
- The page to return a partial result list for.count
- Whether to run theCOUNT(id)
query to estimate total number of results. This will be available byPartialResultList.getEstimatedTotalNumberOfResults()
.resultType
- The result type which can be the entity type itself or a DTO subclass thereof.mappedQueryBuilder
- This allows fine-graining the JPA criteria query and must return a mapping of getters-paths.- Returns:
- A partial result list based on given
Page
andBaseEntityService.MappedQueryBuilder
. - Throws:
IllegalArgumentException
- When the result type does not equal entity type and mapping is empty.- See Also:
Page
,Criteria
-
getPage
protected <T extends E> org.omnifaces.utils.collection.PartialResultList<T> getPage(Page page, boolean count, boolean cacheable, Class<T> resultType, BaseEntityService.MappedQueryBuilder<T> queryBuilder)
Returns a partial result list based on givenPage
, entity type andBaseEntityService.QueryBuilder
with the option whether to cache the results or not.Usage example: see
BaseEntityService.MappedQueryBuilder
.- Type Parameters:
T
- The generic type of the entity or a DTO subclass thereof.- Parameters:
page
- The page to return a partial result list for.count
- Whether to run theCOUNT(id)
query to estimate total number of results. This will be available byPartialResultList.getEstimatedTotalNumberOfResults()
.cacheable
- Whether the results should be cacheable.resultType
- The result type which can be the entity type itself or a DTO subclass thereof.queryBuilder
- This allows fine-graining the JPA criteria query and must return a mapping of getters-paths when result type does not equal entity type.- Returns:
- A partial result list based on given
Page
andBaseEntityService.MappedQueryBuilder
. - Throws:
IllegalArgumentException
- When the result type does not equal entity type and mapping is empty.- See Also:
Page
,Criteria
-
getCurrentInstance
public static BaseEntityService<?,?> getCurrentInstance()
Returns the currently activeBaseEntityService
from theSessionContext
.- Returns:
- The currently active
BaseEntityService
from theSessionContext
. - Throws:
IllegalStateException
- if there is none, which can happen if this method is called outside EJB context, or when currently invoked EJB service is not an instance ofBaseEntityService
.
-
-