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 the EntityManager
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
BaseEntityService
uses JULI Logger
for logging.
Level.FINER
will log the getPage(Page, boolean)
arguments, the set parameter values and the full query result.
Level.FINE
will log computed type mapping (the actual values of I
and E
type paramters), and
whether the ID is generated, and whether the entity is SoftDeletable
, and whether any EnumMapping
is modified, and
any discovered ElementCollection
, ManyToOne
, OneToOne
and OneToMany
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.INFO
will log both successful and unsuccessful attempts to modify enum representations basing on EnumMapping
.
Level.WARNING
will log unparseable or illegal criteria values. The BaseEntityService
will skip them and continue.
Level.SEVERE
will log constraint violations wrapped in any ConstraintViolationException
during
persist(BaseEntity)
and update(BaseEntity)
. Due to technical limitations, it will during update()
only
happen when javax.persistence.validation.mode
property in persistence.xml
is explicitly set to
CALLBACK
(and thus not to its default of AUTO
).
BaseEntity
,
Page
,
Criteria
,
EnumMappingTableService
Modifier and Type | Class and Description |
---|---|
protected static interface |
BaseEntityService.CriteriaQueryBuilder<E>
Functional interface to fine-grain a JPA criteria query for any of
list(CriteriaQueryBuilder, Consumer) or find(CriteriaQueryBuilder, Consumer) methods. |
protected static interface |
BaseEntityService.MappedQueryBuilder<T>
Functional interface to fine-grain a JPA criteria query for any of
getPage(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 of
getPage(Page, boolean) methods. |
Constructor and Description |
---|
BaseEntityService()
The constructor initializes the type mapping.
|
Modifier and Type | Method and Description |
---|---|
protected Consumer<EntityManager> |
afterPage()
Here you can in your
BaseEntityService subclass define the callback method which needs to be invoked after any of
getPage(Page, boolean) methods is called. |
protected Consumer<EntityManager> |
beforePage()
Here you can in your
BaseEntityService subclass define the callback method which needs to be invoked before any of
getPage(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 of
TypedQuery for executing the given Java Persistence Query Language statement which
returns a Long , usually a SELECT e.id or SELECT COUNT(e). |
protected Query |
createNamedQuery(String name)
Create 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. |
protected TypedQuery<E> |
createNamedTypedQuery(String name)
Create an instance of
TypedQuery 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 of
Query 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 of
TypedQuery for executing the given Java Persistence Query Language statement which
returns a E , usually to perform a SELECT e. |
protected <T> TypedQuery<T> |
createTypedQuery(String jpql,
Class<T> resultType)
Create an instance of
TypedQuery for executing the given Java Persistence Query Language statement which
returns the specified T , 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(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder,
Consumer<Map<String,Object>> parameters)
Find entity by
BaseEntityService.CriteriaQueryBuilder and mapped 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(String jpql,
Object... parameters)
Find entity by the given query and positional 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(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder,
Consumer<Map<String,Object>> parameters)
Find first entity by
BaseEntityService.CriteriaQueryBuilder and mapped 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(String jpql,
Object... parameters)
Find first entity by the given query and positional 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 active
BaseEntityService from the SessionContext . |
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 type
E . |
protected Class<I> |
getIdentifierType()
Returns the actual type of the generic ID type
I . |
protected EntityType<E> |
getMetamodel()
Returns the metamodel of current base entity.
|
<I extends Comparable<I> & Serializable,E extends BaseEntity<I>> |
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 given
Page . |
protected org.omnifaces.utils.collection.PartialResultList<E> |
getPage(Page page,
boolean count,
BaseEntityService.QueryBuilder<E> queryBuilder)
Returns a partial result list based on given
Page and BaseEntityService.QueryBuilder . |
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 given
Page , entity type and BaseEntityService.QueryBuilder with the option
whether to cache the results or not. |
protected <T extends E> |
getPage(Page page,
boolean count,
boolean cacheable,
Class<T> resultType,
BaseEntityService.MappedQueryBuilder<T> queryBuilder)
Returns a partial result list based on given
Page , entity type and BaseEntityService.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 given
Page with the option whether to cache the results or not. |
protected <T extends E> |
getPage(Page page,
boolean count,
Class<T> resultType,
BaseEntityService.MappedQueryBuilder<T> mappedQueryBuilder)
Returns a partial result list based on given
Page , result type and BaseEntityService.MappedQueryBuilder . |
protected org.omnifaces.utils.collection.PartialResultList<E> |
getPage(Page page,
boolean count,
String... fetchFields)
Returns a partial result list based on given
Page and fetch fields. |
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(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder,
Consumer<Map<String,Object>> parameters)
List entities matching the
BaseEntityService.CriteriaQueryBuilder and mapped parameters, if any. |
protected List<E> |
list(boolean includeSoftDeleted)
List all entities and set whether it may include soft deleted ones.
|
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(String jpql,
Object... parameters)
List entities matching the given query and positional 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> |
onPage(Class<T> resultType,
boolean cacheable)
Here you can in your
BaseEntityService subclass define the callback method which needs to be invoked when any query involved in
getPage(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 via
save(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,
Consumer<Map<String,Object>> parameters)
Update or delete all entities matching the given query and mapped parameters, if any.
|
protected int |
update(String jpql,
Object... parameters)
Update or delete all entities matching the given query and positional parameters, if any.
|
protected E |
updateAndFlush(E entity)
Update given entity via
update(BaseEntity) and immediately perform a flush so that all changes in
managed entities so far in the current transaction are persisted. |
public BaseEntityService()
I
and E
will be resolved to a concrete Class<?>
.public Provider getProvider()
public Database getDatabase()
protected Class<I> getIdentifierType()
I
. This is immutable (you can't override the method to change the internally used value).I
.protected Class<E> getEntityType()
E
. This is immutable (you can't override the method to change the internally used value).E
.protected boolean isGeneratedId()
protected EntityManager getEntityManager()
BaseEntityService
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; } }
protected EntityType<E> getMetamodel()
public <I extends Comparable<I> & Serializable,E extends BaseEntity<I>> EntityType<E> getMetamodel(E entity)
I
- The generic ID type of the given base entity.E
- The generic base entity type of the given base entity.entity
- Base entity to obtain metamodel for.protected TypedQuery<E> createNamedTypedQuery(String name)
TypedQuery
for executing a Java Persistence Query Language statement identified
by the given name, usually to perform a SELECT e.name
- The name of the Java Persistence Query Language statement defined in metadata, which can be either
a NamedQuery
or a <persistence-unit><mapping-file>
.TypedQuery
for executing a Java Persistence Query Language statement identified
by the given name, usually to perform a SELECT e.protected Query createNamedQuery(String name)
Query
for executing a Java Persistence Query Language statement identified
by the given name, usually to perform an INSERT, UPDATE or DELETE.name
- The name of the Java Persistence Query Language statement defined in metadata, which can be either
a NamedQuery
or a <persistence-unit><mapping-file>
.Query
for executing a Java Persistence Query Language statement identified
by the given name, usually to perform an INSERT, UPDATE or DELETE.protected <T> TypedQuery<T> createTypedQuery(String jpql, Class<T> resultType)
TypedQuery
for executing the given Java Persistence Query Language statement which
returns the specified T
, usually to perform a SELECT t.T
- The generic result type.jpql
- The Java Persistence Query Language statement.resultType
- The result type.TypedQuery
for executing the given Java Persistence Query Language statement which
returns the specified T
, usually to perform a SELECT t.protected TypedQuery<E> createTypedQuery(String jpql)
TypedQuery
for executing the given Java Persistence Query Language statement which
returns a E
, usually to perform a SELECT e.jpql
- The Java Persistence Query Language statement.TypedQuery
for executing the given Java Persistence Query Language statement which
returns a E
, usually to perform a SELECT e.protected TypedQuery<Long> createLongQuery(String jpql)
TypedQuery
for executing the given Java Persistence Query Language statement which
returns a Long
, usually a SELECT e.id or SELECT COUNT(e).jpql
- The Java Persistence Query Language statement.TypedQuery
for executing the given Java Persistence Query Language statement which
returns a Long
, usually a SELECT e.id or SELECT COUNT(e).protected Query createQuery(String jpql)
Query
for executing the given Java Persistence Query Language statement,
usually to perform an INSERT, UPDATE or DELETE.jpql
- The Java Persistence Query Language statement.Query
for executing the given Java Persistence Query Language statement,
usually to perform an INSERT, UPDATE or DELETE.protected Optional<E> find(String jpql, Object... parameters)
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);
jpql
- The Java Persistence Query Language statement.parameters
- The positional query parameters, if any.NonUniqueResultException
- When more than one entity is found matching the given query and positional parameters.protected Optional<E> find(String jpql, Consumer<Map<String,Object>> parameters)
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); });
jpql
- The Java Persistence Query Language statement.parameters
- To put the mapped query parameters in.NonUniqueResultException
- When more than one entity is found matching the given query and mapped parameters.protected Optional<E> find(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder, Consumer<Map<String,Object>> parameters)
BaseEntityService.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); } );
queryBuilder
- This creates the JPA criteria query.parameters
- To put the mapped query parameters in.BaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.NonUniqueResultException
- When more than one entity is found matching given query and mapped parameters.protected Optional<E> findFirst(String jpql, Object... parameters)
find(String, Object...)
is that it doesn't throw NonUniqueResultException
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);
jpql
- The Java Persistence Query Language statement.parameters
- The positional query parameters, if any.protected Optional<E> findFirst(String jpql, Consumer<Map<String,Object>> parameters)
find(String, Consumer)
is that it doesn't throw NonUniqueResultException
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); });
jpql
- The Java Persistence Query Language statement.parameters
- To put the mapped query parameters in.protected Optional<E> findFirst(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder, Consumer<Map<String,Object>> parameters)
BaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.
The difference with find(CriteriaQueryBuilder, Consumer)
is that it doesn't throw NonUniqueResultException
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); } );
queryBuilder
- This creates the JPA criteria query.parameters
- To put the mapped query parameters in.BaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.public Optional<E> findById(I id)
id
- Entity ID to find entity for.protected Optional<E> findById(I id, boolean includeSoftDeleted)
id
- Entity ID to find entity for.includeSoftDeleted
- Whether to include soft deleted ones in the search.public Optional<E> findSoftDeletedById(I id)
id
- Entity ID to find soft deleted entity for.NonSoftDeletableEntityException
- When entity doesn't have SoftDeletable
annotation set on any of its fields.public E getById(I id)
id
- Entity ID to get entity by.null
if there is none.protected E getById(I id, boolean includeSoftDeleted)
id
- Entity ID to get entity by.includeSoftDeleted
- Whether to include soft deleted ones in the search.null
if there is none.public E getByIdWithLoadGraph(I id, String entityGraphName)
id
- Entity ID to get entity by.entityGraphName
- Entity graph name.null
if there is none.public E getSoftDeletedById(I id)
id
- Entity ID to get soft deleted entity by.null
if there is none.NonSoftDeletableEntityException
- When entity doesn't have SoftDeletable
annotation set on any of its fields.public List<E> getByIds(Iterable<I> ids)
ids
- Entity IDs to get entities by.protected List<E> getByIds(Iterable<I> ids, boolean includeSoftDeleted)
ids
- Entity IDs to get entities by.includeSoftDeleted
- Whether to include soft deleted ones in the search.NonSoftDeletableEntityException
- When entity doesn't have SoftDeletable
annotation set on any of its fields.protected boolean exists(E entity)
entity
- Entity to check.public List<E> list()
protected List<E> list(boolean includeSoftDeleted)
includeSoftDeleted
- Whether to include soft deleted ones in the search.NonSoftDeletableEntityException
- When entity doesn't have SoftDeletable
annotation set on any of its fields.public List<E> listSoftDeleted()
NonSoftDeletableEntityException
- When entity doesn't have SoftDeletable
annotation set on any of its fields.protected List<E> list(String jpql, Object... parameters)
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);
jpql
- The Java Persistence Query Language statement.parameters
- The positional query parameters, if any.protected List<E> list(String jpql, Consumer<Map<String,Object>> parameters)
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); });
jpql
- The Java Persistence Query Language statement.parameters
- To put the mapped query parameters in.protected List<E> list(BaseEntityService.CriteriaQueryBuilder<E> queryBuilder, Consumer<Map<String,Object>> parameters)
BaseEntityService.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); } );
queryBuilder
- This creates the JPA criteria query.parameters
- To put the mapped query parameters in.BaseEntityService.CriteriaQueryBuilder
and mapped parameters, if any.public I persist(E entity)
entity
- Entity to persist.IllegalEntityStateException
- When entity is already persisted or its ID is not generated.public E update(E entity)
javax.persistence.validation.mode
property in persistence.xml
is explicitly set
to CALLBACK
(and thus not to its default of AUTO
), 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.entity
- Entity to update.IllegalEntityStateException
- When entity is not persisted or its ID is not generated.protected E updateAndFlush(E entity)
update(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.entity
- Entity to update.IllegalEntityStateException
- When entity is not persisted or its ID is not generated.public List<E> update(Iterable<E> entities)
entities
- Entities to update.IllegalEntityStateException
- When at least one entity has no ID.protected int update(String jpql, Object... parameters)
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);
jpql
- The Java Persistence Query Language statement.parameters
- The positional query parameters, if any.Query.executeUpdate()
protected int update(String jpql, Consumer<Map<String,Object>> parameters)
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); });
jpql
- The Java Persistence Query Language statement.parameters
- To put the mapped query parameters in, if any.Query.executeUpdate()
public E save(E entity)
persist(BaseEntity)
or to update(BaseEntity)
.entity
- Entity to save.protected E saveAndFlush(E entity)
save(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.entity
- Entity to save.public void delete(E entity)
entity
- Entity to delete.NonDeletableEntityException
- When entity has NonDeletable
annotation set.IllegalEntityStateException
- When entity has no ID.EntityNotFoundException
- When entity has in meanwhile been deleted.public void softDelete(E entity)
entity
- Entity to soft delete.NonSoftDeletableEntityException
- When entity doesn't have SoftDeletable
annotation set on any of its fields.IllegalEntityStateException
- When entity has no ID.EntityNotFoundException
- When entity has in meanwhile been hard deleted.public void softUndelete(E entity)
entity
- Entity to soft undelete.NonSoftDeletableEntityException
- When entity doesn't have SoftDeletable
annotation set on any of its fields.IllegalEntityStateException
- When entity has no ID.EntityNotFoundException
- When entity has in meanwhile been hard deleted.public void delete(Iterable<E> entities)
entities
- Entities to delete.NonDeletableEntityException
- When at least one entity has NonDeletable
annotation set.IllegalEntityStateException
- When at least one entity has no ID.EntityNotFoundException
- When at least one entity has in meanwhile been deleted.public void softDelete(Iterable<E> entities)
entities
- Entities to soft delete.NonSoftDeletableEntityException
- When entity doesn't have SoftDeletable
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.public void softUndelete(Iterable<E> entities)
entities
- Entities to soft undelete.NonSoftDeletableEntityException
- When entity doesn't have SoftDeletable
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.protected E manage(E entity)
entity
- Entity to manage.NullPointerException
- When given entity is null
.IllegalEntityStateException
- When entity has no ID.EntityNotFoundException
- When entity has in meanwhile been deleted.protected <E> E manageIfNecessary(E entity)
null
entities as well as proxied entities as well as DTOs.E
- The generic entity type.entity
- Entity to manage, may be null
.null
when null
was supplied.
It leniently returns the very same argument if the entity has no ID or has been deleted in the meanwhile.IllegalArgumentException
- When the given entity is actually not an instance of BaseEntity
.public void reset(E entity)
entity
- Entity to reset.IllegalEntityStateException
- When entity is already managed, or has no ID.EntityNotFoundException
- When entity has in meanwhile been deleted.protected long countForeignKeyReferencesTo(E entity)
entity
- Entity to count all foreign key references for.protected E fetchLazyCollections(E entity, Function<E,Collection<?>>... getters)
PluralAttribute
not of type PluralAttribute.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);
entity
- Entity instance to fetch lazy collections on.getters
- Getters of those lazy collections.protected Optional<E> fetchLazyCollections(Optional<E> entity, Function<E,Collection<?>>... getters)
PluralAttribute
not of type PluralAttribute.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);
entity
- Optional entity instance to fetch lazy collections on.getters
- Getters of those lazy collections.protected E fetchLazyMaps(E entity, Function<E,Map<?,?>>... getters)
PluralAttribute
of type PluralAttribute.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);
entity
- Entity instance to fetch lazy maps on.getters
- Getters of those lazy collections.protected Optional<E> fetchLazyMaps(Optional<E> entity, Function<E,Map<?,?>>... getters)
PluralAttribute
of type PluralAttribute.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);
entity
- Optional entity instance to fetch lazy maps on.getters
- Getters of those lazy collections.protected E fetchLazyBlobs(E entity)
entity
- Entity instance to fetch all blobs on.protected Optional<E> fetchLazyBlobs(Optional<E> entity)
entity
- Optional entity instance to fetch all blobs on.protected Consumer<EntityManager> beforePage()
BaseEntityService
subclass define the callback method which needs to be invoked before any of
getPage(Page, boolean)
methods is called. For example, to set a vendor specific EntityManager
hint.
The default implementation returns a no-op callback.getPage(Page, boolean)
methods is called.protected <T extends E> Consumer<TypedQuery<?>> onPage(Class<T> resultType, boolean cacheable)
BaseEntityService
subclass define the callback method which needs to be invoked when any query involved in
getPage(Page, boolean)
is about to be executed. For example, to set a vendor specific Query
hint.
The default implementation sets Hibernate, EclipseLink and JPA 2.0 cache-related hints. When cacheable
argument is
true
, 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.T
- The generic type of the entity or a DTO subclass thereof.resultType
- The result type which can be the entity type itself or a DTO subclass thereof.cacheable
- Whether the results should be cacheable.getPage(Page, boolean)
is about
to be executed.protected Consumer<EntityManager> afterPage()
BaseEntityService
subclass define the callback method which needs to be invoked after any of
getPage(Page, boolean)
methods is called. For example, to remove a vendor specific EntityManager
hint.
The default implementation returns a no-op callback.getPage(Page, boolean)
methods is called.public org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count)
Page
. 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);
page
- The page to return a partial result list for.count
- Whether to run the COUNT(id)
query to estimate total number of results. This will be
available by PartialResultList.getEstimatedTotalNumberOfResults()
.Page
.Page
,
Criteria
protected org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, String... fetchFields)
Page
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");
page
- The page to return a partial result list for.count
- Whether to run the COUNT(id)
query to estimate total number of results. This will be
available by PartialResultList.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 as parent.child.subchild
.Page
.Page
,
Criteria
protected org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, boolean cacheable, String... fetchFields)
Page
with the option whether to cache the results or not.
Usage example: see getPage(Page, boolean)
and getPage(Page, boolean, String...)
.
page
- The page to return a partial result list for.count
- Whether to run the COUNT(id)
query to estimate total number of results. This will be
available by PartialResultList.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 as parent.child.subchild
.Page
.Page
,
Criteria
protected org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, BaseEntityService.QueryBuilder<E> queryBuilder)
Page
and BaseEntityService.QueryBuilder
. This will by default cache
the results.
Usage example: see BaseEntityService.QueryBuilder
.
page
- The page to return a partial result list for.count
- Whether to run the COUNT(id)
query to estimate total number of results. This will be
available by PartialResultList.getEstimatedTotalNumberOfResults()
.queryBuilder
- This allows fine-graining the JPA criteria query.Page
and BaseEntityService.QueryBuilder
.Page
,
Criteria
protected org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, boolean cacheable, BaseEntityService.QueryBuilder<E> queryBuilder)
Page
, entity type and BaseEntityService.QueryBuilder
with the option
whether to cache the results or not.
Usage example: see BaseEntityService.QueryBuilder
.
page
- The page to return a partial result list for.count
- Whether to run the COUNT(id)
query to estimate total number of results. This will be
available by PartialResultList.getEstimatedTotalNumberOfResults()
.cacheable
- Whether the results should be cacheable.queryBuilder
- This allows fine-graining the JPA criteria query.Page
and BaseEntityService.QueryBuilder
.Page
,
Criteria
protected <T extends E> org.omnifaces.utils.collection.PartialResultList<T> getPage(Page page, boolean count, Class<T> resultType, BaseEntityService.MappedQueryBuilder<T> mappedQueryBuilder)
Page
, result type and BaseEntityService.MappedQueryBuilder
. This will
by default cache the results.
Usage example: see BaseEntityService.MappedQueryBuilder
.
T
- The generic type of the entity or a DTO subclass thereof.page
- The page to return a partial result list for.count
- Whether to run the COUNT(id)
query to estimate total number of results. This will be
available by PartialResultList.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.Page
and BaseEntityService.MappedQueryBuilder
.IllegalArgumentException
- When the result type does not equal entity type and mapping is empty.Page
,
Criteria
protected <T extends E> org.omnifaces.utils.collection.PartialResultList<T> getPage(Page page, boolean count, boolean cacheable, Class<T> resultType, BaseEntityService.MappedQueryBuilder<T> queryBuilder)
Page
, entity type and BaseEntityService.QueryBuilder
with the option
whether to cache the results or not.
Usage example: see BaseEntityService.MappedQueryBuilder
.
T
- The generic type of the entity or a DTO subclass thereof.page
- The page to return a partial result list for.count
- Whether to run the COUNT(id)
query to estimate total number of results. This will be
available by PartialResultList.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.Page
and BaseEntityService.MappedQueryBuilder
.IllegalArgumentException
- When the result type does not equal entity type and mapping is empty.Page
,
Criteria
public static BaseEntityService<?,?> getCurrentInstance()
BaseEntityService
from the SessionContext
.BaseEntityService
from the SessionContext
.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 of BaseEntityService
.Copyright © 2015–2021 OmniFaces. All rights reserved.