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:
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 soft deletable, 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.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
Modifier and Type | Class and Description |
---|---|
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 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. |
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,
Consumer<Map<String,Object>> parameters)
Find entity by given query and parameters.
|
Optional<E> |
findById(I id)
Find entity by given ID.
|
protected Optional<E> |
findById(I id,
boolean includeSoftDeleted)
Find entity by given ID and set whether it may return a soft deleted one.
|
Optional<E> |
findSoftDeletedById(I id)
Find soft deleted entity by given ID.
|
List<E> |
getAll()
Get all entities.
|
protected List<E> |
getAll(boolean includeSoftDeleted)
Get all entities and set whether it may include soft deleted ones.
|
List<E> |
getAllSoftDeleted()
Get all entities that have been soft deleted.
|
E |
getById(I id)
Get entity by given ID.
|
protected E |
getById(I id,
boolean includeSoftDeleted)
Get entity by given ID and set whether it may return a soft deleted one.
|
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 List<E> |
getList(String jpql,
Consumer<Map<String,Object>> parameters)
Get all entities matching the given query and query parameters.
|
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 . |
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 . |
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 . |
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 . |
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 given ID.
|
protected boolean |
isGeneratedId()
Returns whether the ID is generated.
|
protected E |
manage(E entity)
Make given entity managed.
|
protected Consumer<TypedQuery<?>> |
onPage(Page page,
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.
|
void |
reset(E entity)
Reset given entity.
|
E |
save(E entity)
Save given entity.
|
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 query parameters.
|
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 value).I
.protected Class<E> getEntityType()
E
. This is immutable (you can't override the method to change the value).E
.protected boolean isGeneratedId()
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 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 TypedQuery<E> createNamedTypedQuery(String name)
TypedQuery
for executing a Java Persistence Query Language statement identified
by the given name, usually to perform a SELECT.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.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 Optional<E> find(String jpql, Consumer<Map<String,Object>> parameters)
jpql
- The Java Persistence Query Language statement.parameters
- To put the query parameters in.IllegalArgumentException
- When more than one entity is found matching given query and parameters.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 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.protected boolean exists(E entity)
entity
- Entity to check.protected List<E> getList(String jpql, Consumer<Map<String,Object>> parameters)
jpql
- The Java Persistence Query Language statement.parameters
- To put the query parameters in.public List<E> getAll()
protected List<E> getAll(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> getAllSoftDeleted()
NonSoftDeletableEntityException
- When entity doesn't have SoftDeletable
annotation set on any of its fields.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, Consumer<Map<String,Object>> parameters)
jpql
- The Java Persistence Query Language statement.parameters
- To put the query parameters in.Query.executeUpdate()
public E save(E entity)
persist(BaseEntity)
or to update(BaseEntity)
.entity
- Entity to save.public void reset(E entity)
entity
- Entity to reset.IllegalEntityStateException
- When entity has no ID.EntityNotFoundException
- When entity has in meanwhile been deleted.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.IllegalEntityStateException
- When entity 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.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.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.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.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 Consumer<TypedQuery<?>> onPage(Page page, 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. Additionally, the default implementation sets Hibernate cache region identifier to
Page.toString()
.page
- The page on which this query is based.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.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
.public org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, String... fetchFields)
Page
and fetch fields. This will by default cache the results.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
.protected org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, boolean cacheable, String... fetchFields)
Page
.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
.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.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
.protected org.omnifaces.utils.collection.PartialResultList<E> getPage(Page page, boolean count, boolean cacheable, BaseEntityService.QueryBuilder<E> queryBuilder)
Page
, entity type and 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
.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.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.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
.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.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–2018 OmniFaces. All rights reserved.