Class DefaultServer
- java.lang.Object
-
- io.ebeaninternal.server.core.DefaultServer
-
- All Implemented Interfaces:
BeanCollectionLoader
,BeanLoader
,Database
,EbeanServer
,ExtendedServer
,SpiServer
,SpiEbeanServer
public final class DefaultServer extends Object implements SpiServer, SpiEbeanServer
The default server side implementation of EbeanServer.
-
-
Constructor Summary
Constructors Constructor Description DefaultServer(InternalConfiguration config, ServerCacheManager cache)
Create the DefaultServer.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description void
addBatch(SpiSqlUpdate sqlUpdate, SpiTransaction transaction)
Add to JDBC batch for later execution.SpiTransaction
beginServerTransaction()
Begin a managed transaction (Uses scope manager / ThreadLocal).Transaction
beginTransaction()
Start a transaction with 'REQUIRED' semantics.Transaction
beginTransaction(io.ebean.annotation.TxIsolation isolation)
Start a transaction additionally specifying the isolation level.Transaction
beginTransaction(TxScope txScope)
Start a transaction typically specifying REQUIRES_NEW or REQUIRED semantics.Set<Property>
checkUniqueness(Object bean)
This method checks the uniqueness of a bean.Set<Property>
checkUniqueness(Object bean, Transaction transaction)
Same asDatabase.checkUniqueness(Object)
.void
clearQueryStatistics()
Clear the query execution statistics.void
clearServerTransaction()
Clear an implicit transaction from the scope.long
clockNow()
Return the NOW time from the Clock.void
commitTransaction()
Commit the current transaction.<T> CQuery<T>
compileQuery(Query<T> query, Transaction t)
Compile a query.CallableSql
createCallableSql(String sql)
Create a CallableSql to execute a given stored procedure.CallOrigin
createCallOrigin()
Create a CallStack object.<T> CsvReader<T>
createCsvReader(Class<T> beanType)
Create a CsvReader for a given beanType.DdlHandler
createDdlHandler()
Create DDL handler given the platform and configuration of the server.<T> T
createEntityBean(Class<T> type)
Create a new EntityBean bean.<T> DtoQuery<T>
createNamedDtoQuery(Class<T> dtoType, String namedQuery)
Create a named Query for DTO beans.<T> Query<T>
createNamedQuery(Class<T> beanType, String namedQuery)
Create a named query.<T> DefaultOrmQuery<T>
createQuery(Class<T> beanType)
Create a query for an entity bean and synonym forDatabase.find(Class)
.<T> DefaultOrmQuery<T>
createQuery(Class<T> beanType, String eql)
Parse the Ebean query language statement returning the query which can then be modified (add expressions, change order by clause, change maxRows, change fetch and select paths etc).SpiQueryBindCapture
createQueryBindCapture(SpiQueryPlan plan)
Create a query bind capture for the given query plan.SpiTransaction
createReadOnlyTransaction(Object tenantId)
Create a ServerTransaction for query purposes.SqlQuery
createSqlQuery(String sql)
Deprecated - migrate to sqlQuery().SqlUpdate
createSqlUpdate(String sql)
Deprecated - migrate to sqlUpdate().Transaction
createTransaction()
Creates a new Transaction that is NOT stored in TransactionThreadLocal.Transaction
createTransaction(io.ebean.annotation.TxIsolation isolation)
Create a transaction additionally specify the Isolation level.<T> Update<T>
createUpdate(Class<T> beanType, String ormUpdate)
Create a orm update where you will supply the insert/update or delete statement (rather than using a named one that is already defined using the @NamedUpdates annotation).SpiTransaction
currentServerTransaction()
Return the current transaction or null if there is no current transaction.Object
currentTenantId()
Return the current Tenant Id.Transaction
currentTransaction()
Returns the current transaction or null if there is no current transaction in scope.<T> int
delete(Query<T> query, Transaction t)
Execute as a delete query deleting the 'root level' beans that match the predicates in the query.int
delete(Class<?> beanType, Object id)
Delete the bean given its type and id.int
delete(Class<?> beanType, Object id, Transaction transaction)
Delete the bean given its type and id with an explicit transaction.boolean
delete(Object bean)
Delete the bean.boolean
delete(Object bean, Transaction t)
Delete the bean with the explicit transaction.int
deleteAll(Class<?> beanType, Collection<?> ids)
Delete several beans given their type and id values.int
deleteAll(Class<?> beanType, Collection<?> ids, Transaction t)
Delete several beans given their type and id values with an explicit transaction.int
deleteAll(Collection<?> beans)
Delete all the beans in the collection.int
deleteAll(Collection<?> beans, Transaction t)
Delete all the beans in the collection.int
deleteAllPermanent(Class<?> beanType, Collection<?> ids)
Delete permanent for several beans given their type and id values.int
deleteAllPermanent(Class<?> beanType, Collection<?> ids, Transaction t)
Delete permanent for several beans given their type and id values with an explicit transaction.int
deleteAllPermanent(Collection<?> beans)
Delete all the beans in the collection permanently without soft delete.int
deleteAllPermanent(Collection<?> beans, Transaction t)
Delete all the beans in the collection permanently without soft delete using an explicit transaction.int
deletePermanent(Class<?> beanType, Object id)
Delete permanent given the bean type and id.int
deletePermanent(Class<?> beanType, Object id, Transaction transaction)
Delete permanent given the bean type and id with an explicit transaction.boolean
deletePermanent(Object bean)
Delete a bean permanently without soft delete.boolean
deletePermanent(Object bean, Transaction t)
Delete a bean permanently without soft delete using an explicit transaction.void
deregister(BeanPersistController c)
Map<String,ValuePair>
diff(Object a, Object b)
Return a map of the differences between two objects of the same type.DocumentStore
docStore()
Return the Document store.<T> List<T>
draftRestore(Query<T> query)
Restore the draft beans matching the query back to the live state.<T> List<T>
draftRestore(Query<T> query, Transaction transaction)
Restore the draft beans matching the query back to the live state.<T> T
draftRestore(Class<T> beanType, Object id)
Restore the draft bean back to the live state.<T> T
draftRestore(Class<T> beanType, Object id, Transaction transaction)
Restore the draft bean back to the live state.void
endTransaction()
If the current transaction has already been committed do nothing otherwise rollback the transaction.int
execute(CallableSql callSql)
Execute the CallableSql.int
execute(CallableSql callSql, Transaction t)
Execute the CallableSql with an explicit transaction.int
execute(SqlUpdate updSql)
Execute the updateSql.int
execute(SqlUpdate updSql, Transaction t)
Execute the updateSql with an explicit transaction.void
execute(TxScope scope, Runnable r)
Execute a Runnable in a Transaction with an explicit scope.int
execute(Update<?> update)
Execute the orm update.int
execute(Update<?> update, Transaction t)
Execute the updateSql with an explicit transaction.void
execute(Runnable r)
Execute a Runnable in a Transaction with the default scope.int[]
executeBatch(SpiSqlUpdate sqlUpdate, SpiTransaction transaction)
Execute the batched statement.<T> T
executeCall(TxScope scope, Callable<T> c)
Execute a TxCallable in a Transaction with an explicit scope.<T> T
executeCall(Callable<T> c)
Execute a TxCallable in a Transaction with the default scope.int
executeNow(SpiSqlUpdate sqlUpdate)
Execute the sql update regardless of transaction batch mode.void
executePlugins(boolean online)
Execute all the plugins with an online flag indicating the DB is up or not.<T> boolean
exists(Query<?> ormQuery, Transaction transaction)
Execute the query returning true if a row is found.boolean
exists(Class<?> beanType, Object beanId, Transaction transaction)
Return true if a row for the bean type and id exists.ExtendedServer
extended()
Return the extended API for Database.void
externalModification(TransactionEventTable tableEvent)
Process committed beans from another framework or server in another cluster.void
externalModification(String tableName, boolean inserts, boolean updates, boolean deletes)
Developer informing eBean that tables where modified outside of eBean.<T> Filter<T>
filter(Class<T> beanType)
Create a filter for sorting and filtering lists of entities locally without going back to the database.<T> Query<T>
find(Class<T> beanType)
Create a query for a type of entity bean.<T> T
find(Class<T> beanType, Object uid)
Find a bean using its unique id.<T> T
find(Class<T> beanType, Object id, Transaction t)
Find a bean using its unique id.<T> int
findCount(Query<T> query, Transaction t)
Return the number of 'top level' or 'root' entities this query should return.<T> int
findCountWithCopy(Query<T> query, Transaction t)
Execute the findCount query but without copying the query.<T> DtoQuery<T>
findDto(Class<T> dtoType, SpiQuery<?> ormQuery)
Return / wrap the ORM query as a DTO query.<T> DtoQuery<T>
findDto(Class<T> dtoType, String sql)
Create a Query for DTO beans.<T> void
findDtoEach(SpiDtoQuery<T> query, Consumer<T> consumer)
DTO findEach query.<T> void
findDtoEachWhile(SpiDtoQuery<T> query, Predicate<T> consumer)
DTO findEachWhile query.<T> List<T>
findDtoList(SpiDtoQuery<T> query)
DTO findList query.<T> T
findDtoOne(SpiDtoQuery<T> query)
DTO findOne query.<T> void
findEach(Query<T> query, Consumer<T> consumer, Transaction t)
Execute the query visiting the each bean one at a time.void
findEach(SqlQuery query, Consumer<SqlRow> consumer, Transaction transaction)
Execute the SqlQuery iterating a row at a time.void
findEachRow(SpiSqlQuery query, RowConsumer consumer)
SqlQuery find each with consumer.<T> void
findEachWhile(Query<T> query, Predicate<T> consumer, Transaction t)
Execute the query visiting the each bean one at a time.void
findEachWhile(SqlQuery query, Predicate<SqlRow> consumer, Transaction transaction)
Execute the SqlQuery iterating a row at a time with the ability to stop consuming part way through.<T> FutureRowCount<T>
findFutureCount(Query<T> q, Transaction t)
Execute find row count query in a background thread.<T> FutureIds<T>
findFutureIds(Query<T> query, Transaction t)
Execute find Id's query in a background thread.<T> FutureList<T>
findFutureList(Query<T> query, Transaction t)
Execute find list query in a background thread returning a FutureList object.<A,T>
List<A>findIds(Query<T> query, Transaction t)
Return the Id values of the query as a List.<A,T>
List<A>findIdsWithCopy(Query<T> query, Transaction t)
Execute the findId's query but without copying the query.<T> QueryIterator<T>
findIterate(Query<T> query, Transaction t)
Return a QueryIterator for the query.<T> Stream<T>
findLargeStream(Query<T> query, Transaction transaction)
Return the query result as a Stream (with multiple persistence contexts).<T> List<T>
findList(Query<T> query, Transaction t)
Execute a query returning a list of beans.List<SqlRow>
findList(SqlQuery query, Transaction t)
Execute the sql query returning a list of MapBean.<T> List<T>
findListMapper(SpiSqlQuery query, RowMapper<T> mapper)
SqlQuery find list with mapper.<K,T>
Map<K,T>findMap(Query<T> query, Transaction t)
Execute the query returning the entity beans in a Map.<T> Query<T>
findNative(Class<T> beanType, String nativeSql)
Create a query using native SQL.<T> T
findOne(Query<T> query, Transaction transaction)
Execute the query returning at most one entity bean or null (if no matching bean is found).SqlRow
findOne(SqlQuery query, Transaction t)
Execute the sql query returning a single MapBean or null.<T> T
findOneMapper(SpiSqlQuery query, RowMapper<T> mapper)
SqlQuery find one with mapper.<T> Optional<T>
findOneOrEmpty(Query<T> query, Transaction transaction)
Similar to findOne() but returns an Optional (rather than nullable).<T> PagedList<T>
findPagedList(Query<T> query, Transaction transaction)
Return a PagedList for this query using firstRow and maxRows.SpiResultSet
findResultSet(SpiQuery<?> ormQuery, SpiTransaction transaction)
Execute the underlying ORM query returning as a JDBC ResultSet to map to DTO beans.<T> Set<T>
findSet(Query<T> query, Transaction t)
Execute the query returning a set of entity beans.<T> T
findSingleAttribute(SpiSqlQuery query, Class<T> cls)
SqlQuery find single attribute.<A,T>
List<A>findSingleAttributeList(Query<T> query, Transaction t)
Execute the query returning a list of values for a single property.<T> List<T>
findSingleAttributeList(SpiSqlQuery query, Class<T> cls)
SqlQuery find single attribute list.<T> Stream<T>
findStream(Query<T> query, Transaction transaction)
Return the query result as a Stream using a single persistence context.<T> List<Version<T>>
findVersions(Query<T> query, Transaction transaction)
Return versions of a @History entity bean.void
flush()
Flush the JDBC batch on the current transaction.AutoTune
getAutoTune()
Return AutoTune which is used to control the AutoTune service at runtime.BackgroundExecutor
getBackgroundExecutor()
Return the BackgroundExecutor service for asynchronous processing of queries.<T> BeanDescriptor<T>
getBeanDescriptor(Class<T> beanClass)
Return the BeanDescriptor for a given type of bean.BeanDescriptor<?>
getBeanDescriptorById(String beanClassName)
Return the BeanDescriptor using its class name.BeanDescriptor<?>
getBeanDescriptorByQueueId(String queueId)
Return BeanDescriptor using it's unique doc store queueId.List<BeanDescriptor<?>>
getBeanDescriptors()
Return all the BeanDescriptors.List<BeanDescriptor<?>>
getBeanDescriptors(String tableName)
Return the BeanDescriptor's for a given table name.Object
getBeanId(Object bean)
Return the value of the Id property for a given bean.BeanState
getBeanState(Object bean)
Return the BeanState for a given entity bean.<T> BeanType<T>
getBeanType(Class<T> beanType)
Return the SPI bean types for the given bean class.BeanType<?>
getBeanTypeForQueueId(String queueId)
Return the bean type for a given doc store queueId.List<? extends BeanType<?>>
getBeanTypes()
Return all the SPI BeanTypes.List<? extends BeanType<?>>
getBeanTypes(String tableName)
Return the SPI bean types mapped to the given table.DatabasePlatform
getDatabasePlatform()
Return the DatabasePlatform for this database.DataSource
getDataSource()
Return the associated DataSource for this Database instance.DataTimeZone
getDataTimeZone()
Return the DataTimeZone to use when reading/writing timestamps via JDBC.ExpressionFactory
getExpressionFactory()
Return the ExpressionFactory for this database.int
getLazyLoadBatchSize()
Return the default batch size for lazy loading.MetaInfoManager
getMetaInfoManager()
Return the MetaInfoManager which is used to get meta data from the Database such as query execution statistics.String
getName()
Return the server name.PersistenceContextScope
getPersistenceContextScope(SpiQuery<?> query)
Return the PersistenceContextScope to use defined at query or server level.SpiServer
getPluginApi()
Return the extended API intended for use by plugins.int
getQueryBatchSize()
ReadAuditLogger
getReadAuditLogger()
Return the ReadAuditLogger to use for logging all read audit events.ReadAuditPrepare
getReadAuditPrepare()
Return the ReadAuditPrepare used to populate the read audit events with user context information (user id, user ip address etc).DataSource
getReadOnlyDataSource()
Return the associated read only DataSource for this Database instance (can be null).<T> T
getReference(Class<T> type, Object id)
Return a Reference bean.ServerCacheManager
getServerCacheManager()
Return the manager of the server cache ("L2" cache).ServerConfig
getServerConfig()
Return the serverConfig.SpiTransactionManager
getTransactionManager()
Return the transaction manager.void
initialise()
Run any initialisation required before registering with the ClusterManager.void
insert(Object bean)
Insert the bean.void
insert(Object bean, Transaction t)
Insert the bean with a transaction.void
insertAll(Collection<?> beans)
Insert all beans in the collection.void
insertAll(Collection<?> beans, Transaction transaction)
Insert all beans in the collection with a transaction.boolean
isSupportedType(Type genericType)
Return true if the type is known as an Entity or Xml type or a List Set or Map of known bean types.boolean
isUpdateAllPropertiesInBatch()
Return true if updates in JDBC batch should include all columns if unspecified on the transaction.JsonContext
json()
Return the JsonContext for reading/writing JSON.SpiJsonContext
jsonExtended()
Return the server extended Json context.void
loadBean(EntityBeanIntercept ebi)
Invoke lazy loading on this single bean when no BeanLoader is set.void
loadBean(LoadBeanRequest loadRequest)
Load a batch of Associated One Beans.void
loadBeanL2(EntityBeanIntercept ebi)
Invoke lazy loading on this single bean (L2 cache bean).void
loadBeanRef(EntityBeanIntercept ebi)
Invoke lazy loading on this single bean (reference bean).void
loadMany(BeanCollection<?> bc, boolean onlyIds)
Invoke the lazy loading for this bean collection.void
loadMany(LoadManyRequest loadRequest)
Lazy load a batch of Many's.SpiLogManager
log()
Return the log manager.void
markAsDirty(Object bean)
Marks the entity bean as dirty.void
merge(Object bean)
Merge the bean using the default merge options (no paths specified, default delete).void
merge(Object bean, MergeOptions options)
Merge the bean using the given merge options.void
merge(Object bean, MergeOptions options, Transaction transaction)
Merge the bean using the given merge options and a transaction.Object
nextId(Class<?> beanType)
Return the next unique identity value for a given bean type.<T> List<T>
publish(Query<T> query)
Publish the beans that match the query returning the resulting published beans.<T> List<T>
publish(Query<T> query, Transaction transaction)
Publish the beans that match the query returning the resulting published beans.<T> T
publish(Class<T> beanType, Object id)
Publish a single bean given its type and id returning the resulting live bean.<T> T
publish(Class<T> beanType, Object id, Transaction transaction)
Publish a single bean given its type and id returning the resulting live bean.void
refresh(Object bean)
Refresh the values of a bean.void
refreshMany(Object parentBean, String propertyName)
Refresh a many property of an entity bean.void
register(BeanPersistController c)
void
register(TransactionCallback transactionCallback)
Register a TransactionCallback on the currently active transaction.void
remoteTransactionEvent(RemoteTransactionEvent event)
Another server in the cluster sent this event so that we can inform local BeanListeners of inserts updates and deletes that occurred remotely (on another server in the cluster).void
rollbackTransaction()
Rollback the current transaction.void
save(Object bean)
Persist the bean by either performing an insert or update.void
save(Object bean, Transaction t)
Save the bean with an explicit transaction.int
saveAll(Object... beans)
Save all the beans.int
saveAll(Collection<?> beans)
Save all the beans in the collection.int
saveAll(Collection<?> beans, Transaction transaction)
Save all the beans in the collection with an explicit transaction.void
scopedTransactionEnter(TxScope txScope)
Start an enhanced transactional method.void
scopedTransactionExit(Object returnOrThrowable, int opCode)
Handle the end of an enhanced Transactional method.ScriptRunner
script()
Return a ScriptRunner for running SQL or DDL scripts.Object
setBeanId(Object bean, Object id)
Set the Id value onto the bean converting the type of the id value if necessary.void
setClock(Clock clock)
Set the Clock to use for@WhenCreated
and@WhenModified
.void
shutdown(boolean shutdownDataSource, boolean deregisterDriver)
Shutting down manually.void
shutdownManaged()
Shutting down via JVM Shutdown hook.void
slowQueryCheck(long timeMicros, int rowCount, SpiQuery<?> query)
Check for slow query event.<T> void
sort(List<T> list, String sortByClause)
Sort the list in memory using the sortByClause which can contain a comma delimited list of property names and keywords asc, desc, nullsHigh and nullsLow.SqlQuery
sqlQuery(String sql)
Look to execute a native sql query that does not returns beans but instead returns SqlRow or direct access to ResultSet (seeSqlQuery.findList(RowMapper)
.SqlUpdate
sqlUpdate(String sql)
Look to execute a native sql insert update or delete statement.void
start()
Start any services after registering with the ClusterManager.void
truncate(Class<?>... types)
Truncate the base tables for the given bean types.void
truncate(String... tables)
Truncate all the given tables.<T> int
update(Query<T> query, Transaction t)
Execute the update query returning the number of rows updated.<T> UpdateQuery<T>
update(Class<T> beanType)
Create an Update query to perform a bulk update.void
update(Object bean)
Saves the bean using an update.void
update(Object bean, Transaction t)
Update a bean additionally specifying a transaction.void
updateAll(Collection<?> beans)
Update a collection of beans.void
updateAll(Collection<?> beans, Transaction transaction)
Update all beans in the collection with an explicit transaction.<T> Set<String>
validateQuery(Query<T> query)
Returns the set of properties/paths that are unknown (do not map to known properties or paths).void
visitMetrics(MetricVisitor visitor)
Visit all the metrics (typically reporting them).
-
-
-
Constructor Detail
-
DefaultServer
public DefaultServer(InternalConfiguration config, ServerCacheManager cache)
Create the DefaultServer.
-
-
Method Detail
-
executePlugins
public void executePlugins(boolean online)
Execute all the plugins with an online flag indicating the DB is up or not.
-
log
public SpiLogManager log()
Description copied from interface:SpiEbeanServer
Return the log manager.- Specified by:
log
in interfaceSpiEbeanServer
-
isUpdateAllPropertiesInBatch
public boolean isUpdateAllPropertiesInBatch()
Description copied from interface:SpiEbeanServer
Return true if updates in JDBC batch should include all columns if unspecified on the transaction.- Specified by:
isUpdateAllPropertiesInBatch
in interfaceSpiEbeanServer
-
getLazyLoadBatchSize
public int getLazyLoadBatchSize()
Description copied from interface:SpiEbeanServer
Return the default batch size for lazy loading.- Specified by:
getLazyLoadBatchSize
in interfaceSpiEbeanServer
-
getQueryBatchSize
public int getQueryBatchSize()
-
currentTenantId
public Object currentTenantId()
Description copied from interface:SpiEbeanServer
Return the current Tenant Id.- Specified by:
currentTenantId
in interfaceSpiEbeanServer
-
getServerConfig
public ServerConfig getServerConfig()
Description copied from interface:SpiServer
Return the serverConfig.- Specified by:
getServerConfig
in interfaceSpiEbeanServer
- Specified by:
getServerConfig
in interfaceSpiServer
-
getDatabasePlatform
public DatabasePlatform getDatabasePlatform()
Description copied from interface:SpiServer
Return the DatabasePlatform for this database.- Specified by:
getDatabasePlatform
in interfaceSpiEbeanServer
- Specified by:
getDatabasePlatform
in interfaceSpiServer
-
script
public ScriptRunner script()
Description copied from interface:Database
Return a ScriptRunner for running SQL or DDL scripts. Intended to use mostly in testing to run seed SQL scripts or truncate table scripts etc.
-
createDdlHandler
public DdlHandler createDdlHandler()
Description copied from interface:SpiEbeanServer
Create DDL handler given the platform and configuration of the server.- Specified by:
createDdlHandler
in interfaceSpiEbeanServer
-
getDataTimeZone
public DataTimeZone getDataTimeZone()
Description copied from interface:SpiEbeanServer
Return the DataTimeZone to use when reading/writing timestamps via JDBC.- Specified by:
getDataTimeZone
in interfaceSpiEbeanServer
-
getMetaInfoManager
public MetaInfoManager getMetaInfoManager()
Description copied from interface:Database
Return the MetaInfoManager which is used to get meta data from the Database such as query execution statistics.- Specified by:
getMetaInfoManager
in interfaceDatabase
-
getPluginApi
public SpiServer getPluginApi()
Description copied from interface:Database
Return the extended API intended for use by plugins.- Specified by:
getPluginApi
in interfaceDatabase
-
getBackgroundExecutor
public BackgroundExecutor getBackgroundExecutor()
Description copied from interface:Database
Return the BackgroundExecutor service for asynchronous processing of queries.- Specified by:
getBackgroundExecutor
in interfaceDatabase
-
getExpressionFactory
public ExpressionFactory getExpressionFactory()
Description copied from interface:Database
Return the ExpressionFactory for this database.- Specified by:
getExpressionFactory
in interfaceDatabase
-
getAutoTune
public AutoTune getAutoTune()
Description copied from interface:Database
Return AutoTune which is used to control the AutoTune service at runtime.- Specified by:
getAutoTune
in interfaceDatabase
-
getDataSource
public DataSource getDataSource()
Description copied from interface:SpiServer
Return the associated DataSource for this Database instance.- Specified by:
getDataSource
in interfaceSpiServer
-
getReadOnlyDataSource
public DataSource getReadOnlyDataSource()
Description copied from interface:SpiServer
Return the associated read only DataSource for this Database instance (can be null).- Specified by:
getReadOnlyDataSource
in interfaceSpiServer
-
getReadAuditPrepare
public ReadAuditPrepare getReadAuditPrepare()
Description copied from interface:SpiEbeanServer
Return the ReadAuditPrepare used to populate the read audit events with user context information (user id, user ip address etc).- Specified by:
getReadAuditPrepare
in interfaceSpiEbeanServer
-
getReadAuditLogger
public ReadAuditLogger getReadAuditLogger()
Description copied from interface:SpiEbeanServer
Return the ReadAuditLogger to use for logging all read audit events.- Specified by:
getReadAuditLogger
in interfaceSpiEbeanServer
-
initialise
public void initialise()
Run any initialisation required before registering with the ClusterManager.
-
start
public void start()
Start any services after registering with the ClusterManager.
-
shutdownManaged
public void shutdownManaged()
Shutting down via JVM Shutdown hook.- Specified by:
shutdownManaged
in interfaceSpiEbeanServer
-
shutdown
public void shutdown(boolean shutdownDataSource, boolean deregisterDriver)
Shutting down manually.
-
getName
public String getName()
Return the server name.- Specified by:
getName
in interfaceBeanCollectionLoader
- Specified by:
getName
in interfaceBeanLoader
- Specified by:
getName
in interfaceDatabase
-
extended
public ExtendedServer extended()
Description copied from interface:Database
Return the extended API for Database.The extended API has the options for executing queries that take an explicit transaction as an argument.
Typically we only need to use the extended API when we do NOT want to use the usual ThreadLocal based mechanism to obtain the current transaction but instead supply the transaction explicitly.
-
clockNow
public long clockNow()
Description copied from interface:ExtendedServer
Return the NOW time from the Clock.- Specified by:
clockNow
in interfaceExtendedServer
-
setClock
public void setClock(Clock clock)
Description copied from interface:ExtendedServer
Set the Clock to use for@WhenCreated
and@WhenModified
.Note that we only expect to change the Clock for testing purposes.
- Specified by:
setClock
in interfaceExtendedServer
-
getBeanState
public BeanState getBeanState(Object bean)
Description copied from interface:Database
Return the BeanState for a given entity bean.This will return null if the bean is not an enhanced entity bean.
- Specified by:
getBeanState
in interfaceDatabase
-
compileQuery
public <T> CQuery<T> compileQuery(Query<T> query, Transaction t)
Compile a query. Only valid for ORM queries.- Specified by:
compileQuery
in interfaceSpiEbeanServer
-
getServerCacheManager
public ServerCacheManager getServerCacheManager()
Description copied from interface:Database
Return the manager of the server cache ("L2" cache).- Specified by:
getServerCacheManager
in interfaceDatabase
-
refreshMany
public void refreshMany(Object parentBean, String propertyName)
Description copied from interface:Database
Refresh a many property of an entity bean.- Specified by:
refreshMany
in interfaceDatabase
- Parameters:
parentBean
- the entity bean containing the 'many' propertypropertyName
- the 'many' property to be refreshed
-
loadMany
public void loadMany(LoadManyRequest loadRequest)
Description copied from interface:SpiEbeanServer
Lazy load a batch of Many's.- Specified by:
loadMany
in interfaceSpiEbeanServer
-
loadMany
public void loadMany(BeanCollection<?> bc, boolean onlyIds)
Description copied from interface:BeanCollectionLoader
Invoke the lazy loading for this bean collection.- Specified by:
loadMany
in interfaceBeanCollectionLoader
-
refresh
public void refresh(Object bean)
Description copied from interface:Database
Refresh the values of a bean.Note that this resets OneToMany and ManyToMany properties so that if they are accessed a lazy load will refresh the many property.
-
loadBean
public void loadBean(LoadBeanRequest loadRequest)
Description copied from interface:SpiEbeanServer
Load a batch of Associated One Beans.- Specified by:
loadBean
in interfaceSpiEbeanServer
-
loadBean
public void loadBean(EntityBeanIntercept ebi)
Description copied from interface:SpiServer
Invoke lazy loading on this single bean when no BeanLoader is set. Typically due to serialisation or multiple stateless updates.- Specified by:
loadBean
in interfaceBeanLoader
- Specified by:
loadBean
in interfaceSpiServer
-
loadBeanRef
public void loadBeanRef(EntityBeanIntercept ebi)
Description copied from interface:SpiServer
Invoke lazy loading on this single bean (reference bean).- Specified by:
loadBeanRef
in interfaceSpiServer
-
loadBeanL2
public void loadBeanL2(EntityBeanIntercept ebi)
Description copied from interface:SpiServer
Invoke lazy loading on this single bean (L2 cache bean).- Specified by:
loadBeanL2
in interfaceSpiServer
-
diff
public Map<String,ValuePair> diff(Object a, Object b)
Description copied from interface:Database
Return a map of the differences between two objects of the same type.When null is passed in for b, then the 'OldValues' of a is used for the difference comparison.
-
externalModification
public void externalModification(TransactionEventTable tableEvent)
Process committed beans from another framework or server in another cluster.This notifies this instance of the framework that beans have been committed externally to it. Either by another framework or clustered server. It needs to maintain its cache and text indexes appropriately.
- Specified by:
externalModification
in interfaceSpiEbeanServer
-
externalModification
public void externalModification(String tableName, boolean inserts, boolean updates, boolean deletes)
Developer informing eBean that tables where modified outside of eBean. Invalidate the cache etc as required.- Specified by:
externalModification
in interfaceDatabase
- Parameters:
tableName
- the name of the table that was modifiedinserts
- true if rows where inserted into the tableupdates
- true if rows on the table where updateddeletes
- true if rows on the table where deleted
-
truncate
public void truncate(Class<?>... types)
Description copied from interface:Database
Truncate the base tables for the given bean types.
-
truncate
public void truncate(String... tables)
Description copied from interface:Database
Truncate all the given tables.
-
clearQueryStatistics
public void clearQueryStatistics()
Clear the query execution statistics.- Specified by:
clearQueryStatistics
in interfaceSpiEbeanServer
-
createEntityBean
public <T> T createEntityBean(Class<T> type)
Create a new EntityBean bean.This will generally return a subclass of the parameter 'type' which additionally implements the EntityBean interface. That is, the returned bean is typically an instance of a dynamically generated class.
- Specified by:
createEntityBean
in interfaceDatabase
-
getReference
public <T> T getReference(Class<T> type, Object id)
Return a Reference bean.If a current transaction is active then this will check the Context of that transaction to see if the bean is already loaded. If it is already loaded then it will returned that object.
- Specified by:
getReference
in interfaceDatabase
- Parameters:
type
- the type of entity beanid
- the id value
-
register
public void register(TransactionCallback transactionCallback)
Description copied from interface:Database
Register a TransactionCallback on the currently active transaction. If there is no currently active transaction then a PersistenceException is thrown.
-
createTransaction
public Transaction createTransaction()
Creates a new Transaction that is NOT stored in TransactionThreadLocal. Use this when you want a thread to have a second independent transaction.- Specified by:
createTransaction
in interfaceDatabase
-
createTransaction
public Transaction createTransaction(io.ebean.annotation.TxIsolation isolation)
Create a transaction additionally specify the Isolation level.Note that this transaction is not stored in a thread local.
- Specified by:
createTransaction
in interfaceDatabase
-
executeCall
public <T> T executeCall(Callable<T> c)
Description copied from interface:Database
Execute a TxCallable in a Transaction with the default scope.The default scope runs with REQUIRED and by default will rollback on any exception (checked or runtime).
database.executeCall(new Callable<String>() { public String call() { User u1 = database.find(User.class, 1); User u2 = database.find(User.class, 2); u1.setName("u1 mod"); u2.setName("u2 mod"); database.save(u1); database.save(u2); return u1.getEmail(); } });
- Specified by:
executeCall
in interfaceDatabase
-
executeCall
public <T> T executeCall(TxScope scope, Callable<T> c)
Description copied from interface:Database
Execute a TxCallable in a Transaction with an explicit scope.The scope can control the transaction type, isolation and rollback semantics.
// set specific transactional scope settings TxScope scope = TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE); database.executeCall(scope, new Callable<String>() { public String call() { User u1 = database.find(User.class, 1); ... return u1.getEmail(); } });
- Specified by:
executeCall
in interfaceDatabase
-
execute
public void execute(Runnable r)
Description copied from interface:Database
Execute a Runnable in a Transaction with the default scope.The default scope runs with REQUIRED and by default will rollback on any exception (checked or runtime).
database.execute(() -> { User u1 = database.find(User.class, 1); User u2 = database.find(User.class, 2); u1.setName("u1 mod"); u2.setName("u2 mod"); u1.save(); u2.save(); });
-
execute
public void execute(TxScope scope, Runnable r)
Description copied from interface:Database
Execute a Runnable in a Transaction with an explicit scope.The scope can control the transaction type, isolation and rollback semantics.
// set specific transactional scope settings TxScope scope = TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE); database.execute(scope, new Runnable() { public void run() { User u1 = database.find(User.class, 1); ... } });
-
scopedTransactionEnter
public void scopedTransactionEnter(TxScope txScope)
Description copied from interface:SpiEbeanServer
Start an enhanced transactional method.- Specified by:
scopedTransactionEnter
in interfaceSpiEbeanServer
-
scopedTransactionExit
public void scopedTransactionExit(Object returnOrThrowable, int opCode)
Description copied from interface:SpiEbeanServer
Handle the end of an enhanced Transactional method.- Specified by:
scopedTransactionExit
in interfaceSpiEbeanServer
-
currentServerTransaction
public SpiTransaction currentServerTransaction()
Description copied from interface:SpiEbeanServer
Return the current transaction or null if there is no current transaction.- Specified by:
currentServerTransaction
in interfaceSpiEbeanServer
-
beginTransaction
public Transaction beginTransaction()
Description copied from interface:Database
Start a transaction with 'REQUIRED' semantics.With REQUIRED semantics if an active transaction already exists that transaction will be used.
The transaction is stored in a ThreadLocal variable and typically you only need to use the returned Transaction IF you wish to do things like use batch mode, change the transaction isolation level, use savepoints or log comments to the transaction log.
Example of using a transaction to span multiple calls to find(), save() etc.
Using try with resources
// start a transaction (stored in a ThreadLocal) try (Transaction txn = database.beginTransaction()) { Order order = database.find(Order.class, 10); ... database.save(order); txn.commit(); }
Using try finally block
// start a transaction (stored in a ThreadLocal) Transaction txn = database.beginTransaction(); try { Order order = database.find(Order.class,10); database.save(order); txn.commit(); } finally { txn.end(); }
Transaction options
try (Transaction txn = database.beginTransaction()) { // explicitly turn on/off JDBC batch use txn.setBatchMode(true); txn.setBatchSize(50); // control flushing when mixing save and queries txn.setBatchFlushOnQuery(false); // turn off persist cascade if needed txn.setPersistCascade(false); // for large batch insert processing when we do not // ... need the generatedKeys, don't get them txn.setBatchGetGeneratedKeys(false); // explicitly flush the JDBC batch buffer txn.flush(); ... txn.commit(); }
If you want to externalise the transaction management then you use createTransaction() and pass the transaction around to the various methods on Database yourself.
- Specified by:
beginTransaction
in interfaceDatabase
-
beginTransaction
public Transaction beginTransaction(TxScope txScope)
Description copied from interface:Database
Start a transaction typically specifying REQUIRES_NEW or REQUIRED semantics.Note that this provides an try finally alternative to using
Database.executeCall(TxScope, Callable)
orDatabase.execute(TxScope, Runnable)
.REQUIRES_NEW example:
// Start a new transaction. If there is a current transaction // suspend it until this transaction ends try (Transaction txn = database.beginTransaction(TxScope.requiresNew())) { ... // commit the transaction txn.commit(); // At end this transaction will: // A) will rollback transaction if it has not been committed // B) will restore a previously suspended transaction }
REQUIRED example:
// start a new transaction if there is not a current transaction try (Transaction txn = database.beginTransaction(TxScope.required())) { ... // commit the transaction if it was created or // do nothing if there was already a current transaction txn.commit(); }
- Specified by:
beginTransaction
in interfaceDatabase
-
beginTransaction
public Transaction beginTransaction(io.ebean.annotation.TxIsolation isolation)
Description copied from interface:Database
Start a transaction additionally specifying the isolation level.- Specified by:
beginTransaction
in interfaceDatabase
-
currentTransaction
public Transaction currentTransaction()
Description copied from interface:Database
Returns the current transaction or null if there is no current transaction in scope.- Specified by:
currentTransaction
in interfaceDatabase
-
flush
public void flush()
Description copied from interface:Database
Flush the JDBC batch on the current transaction.This only is useful when JDBC batch is used. Flush occurs automatically when the transaction commits or batch size is reached. This manually flushes the JDBC batch buffer.
This is the same as
currentTransaction().flush()
.
-
commitTransaction
public void commitTransaction()
Description copied from interface:Database
Commit the current transaction.- Specified by:
commitTransaction
in interfaceDatabase
-
rollbackTransaction
public void rollbackTransaction()
Description copied from interface:Database
Rollback the current transaction.- Specified by:
rollbackTransaction
in interfaceDatabase
-
endTransaction
public void endTransaction()
Description copied from interface:Database
If the current transaction has already been committed do nothing otherwise rollback the transaction.Useful to put in a finally block to ensure the transaction is ended, rather than a rollbackTransaction() in each catch block.
Code example:
database.beginTransaction(); try { // do some fetching and or persisting ... // commit at the end database.commitTransaction(); } finally { // if commit didn't occur then rollback the transaction database.endTransaction(); }
- Specified by:
endTransaction
in interfaceDatabase
-
nextId
public Object nextId(Class<?> beanType)
Description copied from interface:Database
Return the next unique identity value for a given bean type.This will only work when a IdGenerator is on the bean such as for beans that use a DB sequence or UUID.
For DB's supporting getGeneratedKeys and sequences such as Oracle10 you do not need to use this method generally. It is made available for more complex cases where it is useful to get an ID prior to some processing.
-
sort
public <T> void sort(List<T> list, String sortByClause)
Description copied from interface:Database
Sort the list in memory using the sortByClause which can contain a comma delimited list of property names and keywords asc, desc, nullsHigh and nullsLow.- asc - ascending order (which is the default)
- desc - Descending order
- nullsHigh - Treat null values as high/large values (which is the default)
- nullsLow- Treat null values as low/very small values
If you leave off any keywords the defaults are ascending order and treating nulls as high values.
Note that the sorting uses a Comparator and Collections.sort(); and does not invoke a DB query.
// find orders and their customers List<Order> list = database.find(Order.class) .fetch("customer") .order("id") .findList(); // sort by customer name ascending, then by order shipDate // ... then by the order status descending database.sort(list, "customer.name, shipDate, status desc"); // sort by customer name descending (with nulls low) // ... then by the order id database.sort(list, "customer.name desc nullsLow, id");
-
validateQuery
public <T> Set<String> validateQuery(Query<T> query)
Description copied from interface:Database
Returns the set of properties/paths that are unknown (do not map to known properties or paths).Validate the query checking the where and orderBy expression paths to confirm if they represent valid properties/path for the given bean type.
- Specified by:
validateQuery
in interfaceDatabase
-
filter
public <T> Filter<T> filter(Class<T> beanType)
Description copied from interface:Database
Create a filter for sorting and filtering lists of entities locally without going back to the database.This produces and returns a new list with the sort and filters applied.
Refer to
Filter
for an example of its use.
-
createCsvReader
public <T> CsvReader<T> createCsvReader(Class<T> beanType)
Description copied from interface:Database
Create a CsvReader for a given beanType.- Specified by:
createCsvReader
in interfaceDatabase
-
update
public <T> UpdateQuery<T> update(Class<T> beanType)
Description copied from interface:Database
Create an Update query to perform a bulk update.int rows = database .update(Customer.class) .set("status", Customer.Status.ACTIVE) .set("updtime", new Timestamp(System.currentTimeMillis())) .where() .gt("id", 1000) .update();
-
merge
public void merge(Object bean)
Description copied from interface:Database
Merge the bean using the default merge options (no paths specified, default delete).
-
merge
public void merge(Object bean, MergeOptions options)
Description copied from interface:Database
Merge the bean using the given merge options.
-
merge
public void merge(Object bean, MergeOptions options, Transaction transaction)
Description copied from interface:Database
Merge the bean using the given merge options and a transaction.
-
find
public <T> Query<T> find(Class<T> beanType)
Description copied from interface:Database
Create a query for a type of entity bean.You can use the methods on the Query object to specify fetch paths, predicates, order by, limits etc.
You then use findList(), findSet(), findMap() and findOne() to execute the query and return the collection or bean.
Note that a query executed by
Query.findList()
Query.findSet()
etc will execute against the same Database from which is was created.// Find order 2 specifying explicitly the parts of the object graph to // eagerly fetch. In this case eagerly fetch the associated customer, // details and details.product.name Order order = database.find(Order.class) .fetch("customer") .fetch("details") .fetch("detail.product", "name") .setId(2) .findOne(); // find some new orders ... with firstRow/maxRows List<Order> orders = database.find(Order.class) .where().eq("status", Order.Status.NEW) .setFirstRow(20) .setMaxRows(10) .findList();
-
findNative
public <T> Query<T> findNative(Class<T> beanType, String nativeSql)
Description copied from interface:Database
Create a query using native SQL.The native SQL can contain named parameters or positioned parameters.
String sql = "select c.id, c.name from customer c where c.name like ? order by c.name"; Query<Customer> query = database.findNative(Customer.class, sql); query.setParameter(1, "Rob%"); List<Customer> customers = query.findList();
- Specified by:
findNative
in interfaceDatabase
- Parameters:
beanType
- The type of entity bean to fetchnativeSql
- The SQL that can contain named or positioned parameters- Returns:
- The query to set parameters and execute
-
createNamedQuery
public <T> Query<T> createNamedQuery(Class<T> beanType, String namedQuery)
Description copied from interface:Database
Create a named query.For RawSql the named query is expected to be in ebean.xml.
- Specified by:
createNamedQuery
in interfaceDatabase
- Type Parameters:
T
- The type of entity bean- Parameters:
beanType
- The type of entity beannamedQuery
- The name of the query- Returns:
- The query
-
createQuery
public <T> DefaultOrmQuery<T> createQuery(Class<T> beanType, String eql)
Description copied from interface:Database
Parse the Ebean query language statement returning the query which can then be modified (add expressions, change order by clause, change maxRows, change fetch and select paths etc).Example
// Find order additionally fetching the customer, details and details.product name. String ormQuery = "fetch customer fetch details fetch details.product (name) where id = :orderId "; Query<Order> query = DB.createQuery(Order.class, ormQuery); query.setParameter("orderId", 2); Order order = query.findOne(); // This is the same as: Order order = DB.find(Order.class) .fetch("customer") .fetch("details") .fetch("detail.product", "name") .setId(2) .findOne();
- Specified by:
createQuery
in interfaceDatabase
- Type Parameters:
T
- The type of the entity bean- Parameters:
beanType
- The type of bean to fetcheql
- The Ebean ORM query- Returns:
- The query with expressions defined as per the parsed query statement
-
createQuery
public <T> DefaultOrmQuery<T> createQuery(Class<T> beanType)
Description copied from interface:Database
Create a query for an entity bean and synonym forDatabase.find(Class)
.- Specified by:
createQuery
in interfaceDatabase
- See Also:
Database.find(Class)
-
createUpdate
public <T> Update<T> createUpdate(Class<T> beanType, String ormUpdate)
Description copied from interface:Database
Create a orm update where you will supply the insert/update or delete statement (rather than using a named one that is already defined using the @NamedUpdates annotation).The orm update differs from the sql update in that it you can use the bean name and bean property names rather than table and column names.
An example:
// The bean name and properties - "topic","postCount" and "id" // will be converted into their associated table and column names String updStatement = "update topic set postCount = :pc where id = :id"; Update<Topic> update = database.createUpdate(Topic.class, updStatement); update.set("pc", 9); update.set("id", 3); int rows = update.execute(); System.out.println("rows updated:" + rows);
- Specified by:
createUpdate
in interfaceDatabase
-
findDto
public <T> DtoQuery<T> findDto(Class<T> dtoType, String sql)
Description copied from interface:Database
Create a Query for DTO beans.DTO beans are just normal bean like classes with public constructor(s) and setters. They do not need to be registered with DB before use.
-
createNamedDtoQuery
public <T> DtoQuery<T> createNamedDtoQuery(Class<T> dtoType, String namedQuery)
Description copied from interface:Database
Create a named Query for DTO beans.DTO beans are just normal bean like classes with public constructor(s) and setters. They do not need to be registered with DB before use.
- Specified by:
createNamedDtoQuery
in interfaceDatabase
- Type Parameters:
T
- The type of the DTO bean.- Parameters:
dtoType
- The type of the DTO bean the rows will be mapped into.namedQuery
- The name of the query
-
findDto
public <T> DtoQuery<T> findDto(Class<T> dtoType, SpiQuery<?> ormQuery)
Description copied from interface:SpiEbeanServer
Return / wrap the ORM query as a DTO query.- Specified by:
findDto
in interfaceSpiEbeanServer
-
findResultSet
public SpiResultSet findResultSet(SpiQuery<?> ormQuery, SpiTransaction transaction)
Description copied from interface:SpiEbeanServer
Execute the underlying ORM query returning as a JDBC ResultSet to map to DTO beans.- Specified by:
findResultSet
in interfaceSpiEbeanServer
-
sqlQuery
public SqlQuery sqlQuery(String sql)
Description copied from interface:Database
Look to execute a native sql query that does not returns beans but instead returns SqlRow or direct access to ResultSet (seeSqlQuery.findList(RowMapper)
.Refer to
DtoQuery
for native sql queries returning DTO beans.Refer to
Database.findNative(Class, String)
for native sql queries returning entity beans.
-
createSqlQuery
public SqlQuery createSqlQuery(String sql)
Description copied from interface:Database
Deprecated - migrate to sqlQuery().This is an alias for
Database.sqlQuery(String)
.- Specified by:
createSqlQuery
in interfaceDatabase
-
sqlUpdate
public SqlUpdate sqlUpdate(String sql)
Description copied from interface:Database
Look to execute a native sql insert update or delete statement.Use this to execute a Insert Update or Delete statement. The statement will be native to the database and contain database table and column names.
See
SqlUpdate
for example usage.
-
createSqlUpdate
public SqlUpdate createSqlUpdate(String sql)
Description copied from interface:Database
Deprecated - migrate to sqlUpdate().This is an alias for
Database.sqlUpdate(String)
.- Specified by:
createSqlUpdate
in interfaceDatabase
-
createCallableSql
public CallableSql createCallableSql(String sql)
Description copied from interface:Database
Create a CallableSql to execute a given stored procedure.- Specified by:
createCallableSql
in interfaceDatabase
-
find
public <T> T find(Class<T> beanType, Object uid)
Description copied from interface:Database
Find a bean using its unique id.// Fetch order 1 Order order = database.find(Order.class, 1);
If you want more control over the query then you can use createQuery() and Query.findOne();
// ... additionally fetching customer, customer shipping address, // order details, and the product associated with each order detail. // note: only product id and name is fetch (its a "partial object"). // note: all other objects use "*" and have all their properties fetched. Query<Order> query = database.find(Order.class) .setId(1) .fetch("customer") .fetch("customer.shippingAddress") .fetch("details") .query(); // fetch associated products but only fetch their product id and name query.fetch("details.product", "name"); Order order = query.findOne(); // traverse the object graph... Customer customer = order.getCustomer(); Address shippingAddress = customer.getShippingAddress(); List<OrderDetail> details = order.getDetails(); OrderDetail detail0 = details.get(0); Product product = detail0.getProduct(); String productName = product.getName();
-
find
public <T> T find(Class<T> beanType, Object id, Transaction t)
Find a bean using its unique id.
-
getPersistenceContextScope
public PersistenceContextScope getPersistenceContextScope(SpiQuery<?> query)
Return the PersistenceContextScope to use defined at query or server level.- Specified by:
getPersistenceContextScope
in interfaceSpiEbeanServer
-
findOneOrEmpty
public <T> Optional<T> findOneOrEmpty(Query<T> query, Transaction transaction)
Description copied from interface:ExtendedServer
Similar to findOne() but returns an Optional (rather than nullable).- Specified by:
findOneOrEmpty
in interfaceExtendedServer
-
findOne
public <T> T findOne(Query<T> query, Transaction transaction)
Description copied from interface:ExtendedServer
Execute the query returning at most one entity bean or null (if no matching bean is found).This will throw a NonUniqueResultException if the query finds more than one result.
Generally you are able to use
Query.findOne()
rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.- Specified by:
findOne
in interfaceExtendedServer
- Type Parameters:
T
- the type of entity bean to fetch.- Parameters:
query
- the query to execute.transaction
- the transaction to use (can be null).- Returns:
- the list of fetched beans.
- See Also:
Query.findOne()
-
findSet
public <T> Set<T> findSet(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Execute the query returning a set of entity beans.Generally you are able to use
Query.findSet()
rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.Set<Customer> customers = DB.find(Customer.class) .where().ilike("name", "rob%") .findSet();
- Specified by:
findSet
in interfaceExtendedServer
- Type Parameters:
T
- the type of entity bean to fetch.- Parameters:
query
- the query to executet
- the transaction to use (can be null).- Returns:
- the set of fetched beans.
- See Also:
Query.findSet()
-
findMap
public <K,T> Map<K,T> findMap(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Execute the query returning the entity beans in a Map.Generally you are able to use
Query.findMap()
rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.- Specified by:
findMap
in interfaceExtendedServer
T
- the type of entity bean to fetch.- Parameters:
query
- the query to execute.t
- the transaction to use (can be null).- Returns:
- the map of fetched beans.
- See Also:
Query.findMap()
-
findSingleAttributeList
public <A,T> List<A> findSingleAttributeList(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Execute the query returning a list of values for a single property.Example 1:
List<String> names = DB.find(Customer.class) .select("name") .order().asc("name") .findSingleAttributeList();
Example 2:
List<String> names = DB.find(Customer.class) .setDistinct(true) .select("name") .where().eq("status", Customer.Status.NEW) .order().asc("name") .setMaxRows(100) .findSingleAttributeList();
- Specified by:
findSingleAttributeList
in interfaceExtendedServer
- Returns:
- the list of values for the selected property
- See Also:
Query.findSingleAttributeList()
-
findCount
public <T> int findCount(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Return the number of 'top level' or 'root' entities this query should return.- Specified by:
findCount
in interfaceExtendedServer
- See Also:
Query.findCount()
,Query.findFutureCount()
-
findCountWithCopy
public <T> int findCountWithCopy(Query<T> query, Transaction t)
Description copied from interface:SpiEbeanServer
Execute the findCount query but without copying the query.- Specified by:
findCountWithCopy
in interfaceSpiEbeanServer
-
exists
public boolean exists(Class<?> beanType, Object beanId, Transaction transaction)
Description copied from interface:SpiEbeanServer
Return true if a row for the bean type and id exists.- Specified by:
exists
in interfaceSpiEbeanServer
-
exists
public <T> boolean exists(Query<?> ormQuery, Transaction transaction)
Description copied from interface:ExtendedServer
Execute the query returning true if a row is found.The query is executed using max rows of 1 and will only select the id property. This method is really just a convenient way to optimise a query to perform a 'does a row exist in the db' check.
Example:
boolean userExists = query().where().eq("email", "[email protected]").exists();
Example using a query bean:
boolean userExists = new QContact().email.equalTo("[email protected]").exists();
- Specified by:
exists
in interfaceExtendedServer
- Returns:
- True if the query finds a matching row in the database
-
findIds
public <A,T> List<A> findIds(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Return the Id values of the query as a List.- Specified by:
findIds
in interfaceExtendedServer
- See Also:
Query.findIds()
-
findIdsWithCopy
public <A,T> List<A> findIdsWithCopy(Query<T> query, Transaction t)
Description copied from interface:SpiEbeanServer
Execute the findId's query but without copying the query.Used so that the list of Id's can be made accessible to client code before the query has finished (if executing in a background thread).
- Specified by:
findIdsWithCopy
in interfaceSpiEbeanServer
-
delete
public <T> int delete(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Execute as a delete query deleting the 'root level' beans that match the predicates in the query.Note that if the query includes joins then the generated delete statement may not be optimal depending on the database platform.
- Specified by:
delete
in interfaceExtendedServer
- Type Parameters:
T
- the type of entity bean to fetch.- Parameters:
query
- the query used for the deletet
- the transaction to use (can be null)- Returns:
- the number of beans/rows that were deleted
-
update
public <T> int update(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Execute the update query returning the number of rows updated.The update query must be created using
Database.update(Class)
.- Specified by:
update
in interfaceExtendedServer
- Type Parameters:
T
- the type of entity bean- Parameters:
query
- the update query to executet
- the optional transaction to use for the update (can be null)- Returns:
- The number of rows updated
-
findFutureCount
public <T> FutureRowCount<T> findFutureCount(Query<T> q, Transaction t)
Description copied from interface:ExtendedServer
Execute find row count query in a background thread.This returns a Future object which can be used to cancel, check the execution status (isDone etc) and get the value (with or without a timeout).
- Specified by:
findFutureCount
in interfaceExtendedServer
- Parameters:
q
- the query to execute the row count ont
- the transaction (can be null).- Returns:
- a Future object for the row count query
- See Also:
Query.findFutureCount()
-
findFutureIds
public <T> FutureIds<T> findFutureIds(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Execute find Id's query in a background thread.This returns a Future object which can be used to cancel, check the execution status (isDone etc) and get the value (with or without a timeout).
- Specified by:
findFutureIds
in interfaceExtendedServer
- Parameters:
query
- the query to execute the fetch Id's ont
- the transaction (can be null).- Returns:
- a Future object for the list of Id's
- See Also:
Query.findFutureIds()
-
findFutureList
public <T> FutureList<T> findFutureList(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Execute find list query in a background thread returning a FutureList object.This returns a Future object which can be used to cancel, check the execution status (isDone etc) and get the value (with or without a timeout).
This query will execute in it's own PersistenceContext and using its own transaction. What that means is that it will not share any bean instances with other queries.
- Specified by:
findFutureList
in interfaceExtendedServer
- Parameters:
query
- the query to execute in the backgroundt
- the transaction (can be null).- Returns:
- a Future object for the list result of the query
- See Also:
Query.findFutureList()
-
findPagedList
public <T> PagedList<T> findPagedList(Query<T> query, Transaction transaction)
Description copied from interface:ExtendedServer
Return a PagedList for this query using firstRow and maxRows.The benefit of using this over findList() is that it provides functionality to get the total row count etc.
If maxRows is not set on the query prior to calling findPagedList() then a PersistenceException is thrown.
PagedList<Order> pagedList = DB.find(Order.class) .setFirstRow(50) .setMaxRows(20) .findPagedList(); // fetch the total row count in the background pagedList.loadRowCount(); List<Order> orders = pagedList.getList(); int totalRowCount = pagedList.getTotalRowCount();
- Specified by:
findPagedList
in interfaceExtendedServer
- Returns:
- The PagedList
- See Also:
Query.findPagedList()
-
findIterate
public <T> QueryIterator<T> findIterate(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Return a QueryIterator for the query.Generally using
ExtendedServer.findEach(Query, Consumer, Transaction)
orExtendedServer.findEachWhile(Query, Predicate, Transaction)
is preferred to findIterate(). The reason is that those methods automatically take care of closing the queryIterator (and the underlying jdbc statement and resultSet).This is similar to findEach in that not all the result beans need to be held in memory at the same time and as such is good for processing large queries.
- Specified by:
findIterate
in interfaceExtendedServer
- See Also:
Query.findIterate()
,Query.findEach(Consumer)
,Query.findEachWhile(Predicate)
-
findLargeStream
public <T> Stream<T> findLargeStream(Query<T> query, Transaction transaction)
Description copied from interface:ExtendedServer
Return the query result as a Stream (with multiple persistence contexts).Note that the stream needs to be closed so use with try with resources.
- Specified by:
findLargeStream
in interfaceExtendedServer
-
findStream
public <T> Stream<T> findStream(Query<T> query, Transaction transaction)
Description copied from interface:ExtendedServer
Return the query result as a Stream using a single persistence context.Note that the stream needs to be closed so use with try with resources.
- Specified by:
findStream
in interfaceExtendedServer
-
findEach
public <T> void findEach(Query<T> query, Consumer<T> consumer, Transaction t)
Description copied from interface:ExtendedServer
Execute the query visiting the each bean one at a time.Unlike findList() this is suitable for processing a query that will return a very large resultSet. The reason is that not all the result beans need to be held in memory at the same time and instead processed one at a time.
Internally this query using a PersistenceContext scoped to each bean (and the beans associated object graph).
DB.find(Order.class) .where().eq("status", Order.Status.NEW) .order().asc("id") .findEach((Order order) -> { // do something with the order bean System.out.println(" -- processing order ... " + order); });
- Specified by:
findEach
in interfaceExtendedServer
- See Also:
Query.findEach(Consumer)
,Query.findEachWhile(Predicate)
-
findEachWhile
public <T> void findEachWhile(Query<T> query, Predicate<T> consumer, Transaction t)
Description copied from interface:ExtendedServer
Execute the query visiting the each bean one at a time.Compared to findEach() this provides the ability to stop processing the query results early by returning false for the Predicate.
Unlike findList() this is suitable for processing a query that will return a very large resultSet. The reason is that not all the result beans need to be held in memory at the same time and instead processed one at a time.
Internally this query using a PersistenceContext scoped to each bean (and the beans associated object graph).
DB.find(Order.class) .where().eq("status", Order.Status.NEW) .order().asc("id") .findEachWhile((Order order) -> { // do something with the order bean System.out.println(" -- processing order ... " + order); boolean carryOnProcessing = ... return carryOnProcessing; });
- Specified by:
findEachWhile
in interfaceExtendedServer
- See Also:
Query.findEach(Consumer)
,Query.findEachWhile(Predicate)
-
findVersions
public <T> List<Version<T>> findVersions(Query<T> query, Transaction transaction)
Description copied from interface:ExtendedServer
Return versions of a @History entity bean.Generally this query is expected to be a find by id or unique predicates query. It will execute the query against the history returning the versions of the bean.
- Specified by:
findVersions
in interfaceExtendedServer
-
findList
public <T> List<T> findList(Query<T> query, Transaction t)
Description copied from interface:ExtendedServer
Execute a query returning a list of beans.Generally you are able to use
Query.findList()
rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.List<Customer> customers = DB.find(Customer.class) .where().ilike("name", "rob%") .findList();
- Specified by:
findList
in interfaceExtendedServer
- Type Parameters:
T
- the type of entity bean to fetch.- Parameters:
query
- the query to execute.t
- the transaction to use (can be null).- Returns:
- the list of fetched beans.
- See Also:
Query.findList()
-
findOne
public SqlRow findOne(SqlQuery query, Transaction t)
Description copied from interface:ExtendedServer
Execute the sql query returning a single MapBean or null.This will throw a PersistenceException if the query found more than one result.
Generally you are able to use
SqlQuery.findOne()
rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.- Specified by:
findOne
in interfaceExtendedServer
- Parameters:
query
- the query to execute.t
- the transaction to use (can be null).- Returns:
- the fetched MapBean or null if none was found.
- See Also:
SqlQuery.findOne()
-
findEach
public void findEach(SqlQuery query, Consumer<SqlRow> consumer, Transaction transaction)
Description copied from interface:ExtendedServer
Execute the SqlQuery iterating a row at a time.This streaming type query is useful for large query execution as only 1 row needs to be held in memory.
- Specified by:
findEach
in interfaceExtendedServer
-
findEachWhile
public void findEachWhile(SqlQuery query, Predicate<SqlRow> consumer, Transaction transaction)
Description copied from interface:ExtendedServer
Execute the SqlQuery iterating a row at a time with the ability to stop consuming part way through.Returning false after processing a row stops the iteration through the query results.
This streaming type query is useful for large query execution as only 1 row needs to be held in memory.
- Specified by:
findEachWhile
in interfaceExtendedServer
-
findList
public List<SqlRow> findList(SqlQuery query, Transaction t)
Description copied from interface:ExtendedServer
Execute the sql query returning a list of MapBean.Generally you are able to use
SqlQuery.findList()
rather than explicitly calling this method. You could use this method if you wish to explicitly control the transaction used for the query.- Specified by:
findList
in interfaceExtendedServer
- Parameters:
query
- the query to execute.t
- the transaction to use (can be null).- Returns:
- the list of fetched MapBean.
- See Also:
SqlQuery.findList()
-
findEachRow
public void findEachRow(SpiSqlQuery query, RowConsumer consumer)
Description copied from interface:SpiEbeanServer
SqlQuery find each with consumer.- Specified by:
findEachRow
in interfaceSpiEbeanServer
-
findListMapper
public <T> List<T> findListMapper(SpiSqlQuery query, RowMapper<T> mapper)
Description copied from interface:SpiEbeanServer
SqlQuery find list with mapper.- Specified by:
findListMapper
in interfaceSpiEbeanServer
-
findOneMapper
public <T> T findOneMapper(SpiSqlQuery query, RowMapper<T> mapper)
Description copied from interface:SpiEbeanServer
SqlQuery find one with mapper.- Specified by:
findOneMapper
in interfaceSpiEbeanServer
-
findSingleAttributeList
public <T> List<T> findSingleAttributeList(SpiSqlQuery query, Class<T> cls)
Description copied from interface:SpiEbeanServer
SqlQuery find single attribute list.- Specified by:
findSingleAttributeList
in interfaceSpiEbeanServer
-
findSingleAttribute
public <T> T findSingleAttribute(SpiSqlQuery query, Class<T> cls)
Description copied from interface:SpiEbeanServer
SqlQuery find single attribute.- Specified by:
findSingleAttribute
in interfaceSpiEbeanServer
-
findDtoEach
public <T> void findDtoEach(SpiDtoQuery<T> query, Consumer<T> consumer)
Description copied from interface:SpiEbeanServer
DTO findEach query.- Specified by:
findDtoEach
in interfaceSpiEbeanServer
-
findDtoEachWhile
public <T> void findDtoEachWhile(SpiDtoQuery<T> query, Predicate<T> consumer)
Description copied from interface:SpiEbeanServer
DTO findEachWhile query.- Specified by:
findDtoEachWhile
in interfaceSpiEbeanServer
-
findDtoList
public <T> List<T> findDtoList(SpiDtoQuery<T> query)
Description copied from interface:SpiEbeanServer
DTO findList query.- Specified by:
findDtoList
in interfaceSpiEbeanServer
-
findDtoOne
public <T> T findDtoOne(SpiDtoQuery<T> query)
Description copied from interface:SpiEbeanServer
DTO findOne query.- Specified by:
findDtoOne
in interfaceSpiEbeanServer
-
save
public void save(Object bean, Transaction t)
Save the bean with an explicit transaction.
-
markAsDirty
public void markAsDirty(Object bean)
Description copied from interface:Database
Marks the entity bean as dirty.This is used so that when a bean that is otherwise unmodified is updated the version property is updated.
An unmodified bean that is saved or updated is normally skipped and this marks the bean as dirty so that it is not skipped.
Customer customer = database.find(Customer, id); // mark the bean as dirty so that a save() or update() will // increment the version property database.markAsDirty(customer); database.save(customer);
- Specified by:
markAsDirty
in interfaceDatabase
-
update
public void update(Object bean)
Description copied from interface:Database
Saves the bean using an update. If you know you are updating a bean then it is preferable to use this update() method rather than save().Stateless updates: Note that the bean does not have to be previously fetched to call update().You can create a new instance and set some of its properties programmatically for via JSON/XML marshalling etc. This is described as a 'stateless update'.
Optimistic Locking: Note that if the version property is not set when update() is called then no optimistic locking is performed (internally ConcurrencyMode.NONE is used).
// A 'stateless update' example Customer customer = new Customer(); customer.setId(7); customer.setName("ModifiedNameNoOCC"); database.update(customer);
-
update
public void update(Object bean, Transaction t)
Description copied from interface:Database
Update a bean additionally specifying a transaction.
-
updateAll
public void updateAll(Collection<?> beans) throws javax.persistence.OptimisticLockException
Description copied from interface:Database
Update a collection of beans. If there is no current transaction one is created and used to update all the beans in the collection.
-
updateAll
public void updateAll(Collection<?> beans, Transaction transaction)
Update all beans in the collection with an explicit transaction.
-
insert
public void insert(Object bean, Transaction t)
Insert the bean with a transaction.
-
insertAll
public void insertAll(Collection<?> beans)
Insert all beans in the collection.
-
insertAll
public void insertAll(Collection<?> beans, Transaction transaction)
Insert all beans in the collection with a transaction.
-
publish
public <T> List<T> publish(Query<T> query, Transaction transaction)
Description copied from interface:Database
Publish the beans that match the query returning the resulting published beans.The values are published from the draft beans to the live beans.
-
publish
public <T> T publish(Class<T> beanType, Object id)
Description copied from interface:Database
Publish a single bean given its type and id returning the resulting live bean. This will use the current transaction or create one if required.The values are published from the draft to the live bean.
-
publish
public <T> List<T> publish(Query<T> query)
Description copied from interface:Database
Publish the beans that match the query returning the resulting published beans. This will use the current transaction or create one if required.The values are published from the draft beans to the live beans.
-
publish
public <T> T publish(Class<T> beanType, Object id, Transaction transaction)
Description copied from interface:Database
Publish a single bean given its type and id returning the resulting live bean.The values are published from the draft to the live bean.
-
draftRestore
public <T> List<T> draftRestore(Query<T> query, Transaction transaction)
Description copied from interface:Database
Restore the draft beans matching the query back to the live state.The values from the live beans are set back to the draft bean and the
@DraftDirty
and@DraftReset
properties are reset.- Specified by:
draftRestore
in interfaceDatabase
- Type Parameters:
T
- the type of the entity bean- Parameters:
query
- the query used to select the draft beans to restoretransaction
- the transaction the restore process should use (can be null)
-
draftRestore
public <T> T draftRestore(Class<T> beanType, Object id, Transaction transaction)
Description copied from interface:Database
Restore the draft bean back to the live state.The values from the live beans are set back to the draft bean and the
@DraftDirty
and@DraftReset
properties are reset.- Specified by:
draftRestore
in interfaceDatabase
- Type Parameters:
T
- the type of the entity bean- Parameters:
beanType
- the type of the entity beanid
- the id of the entity bean to restoretransaction
- the transaction the restore process should use (can be null)
-
draftRestore
public <T> T draftRestore(Class<T> beanType, Object id)
Description copied from interface:Database
Restore the draft bean back to the live state.The values from the live beans are set back to the draft bean and the
@DraftDirty
and@DraftReset
properties are reset.- Specified by:
draftRestore
in interfaceDatabase
- Type Parameters:
T
- the type of the entity bean- Parameters:
beanType
- the type of the entity beanid
- the id of the entity bean to restore
-
draftRestore
public <T> List<T> draftRestore(Query<T> query)
Description copied from interface:Database
Restore the draft beans matching the query back to the live state.The values from the live beans are set back to the draft bean and the
@DraftDirty
and@DraftReset
properties are reset.- Specified by:
draftRestore
in interfaceDatabase
- Type Parameters:
T
- the type of the entity bean- Parameters:
query
- the query used to select the draft beans to restore
-
saveAll
public int saveAll(Collection<?> beans, Transaction transaction) throws javax.persistence.OptimisticLockException
Description copied from interface:Database
Save all the beans in the collection with an explicit transaction.
-
saveAll
public int saveAll(Collection<?> beans) throws javax.persistence.OptimisticLockException
Description copied from interface:Database
Save all the beans in the collection.
-
saveAll
public int saveAll(Object... beans) throws javax.persistence.OptimisticLockException
Description copied from interface:Database
Save all the beans.
-
delete
public int delete(Class<?> beanType, Object id)
Description copied from interface:Database
Delete the bean given its type and id.
-
delete
public int delete(Class<?> beanType, Object id, Transaction transaction)
Description copied from interface:Database
Delete the bean given its type and id with an explicit transaction.
-
deletePermanent
public int deletePermanent(Class<?> beanType, Object id)
Description copied from interface:Database
Delete permanent given the bean type and id.- Specified by:
deletePermanent
in interfaceDatabase
-
deletePermanent
public int deletePermanent(Class<?> beanType, Object id, Transaction transaction)
Description copied from interface:Database
Delete permanent given the bean type and id with an explicit transaction.- Specified by:
deletePermanent
in interfaceDatabase
-
deleteAll
public int deleteAll(Class<?> beanType, Collection<?> ids)
Description copied from interface:Database
Delete several beans given their type and id values.
-
deleteAll
public int deleteAll(Class<?> beanType, Collection<?> ids, Transaction t)
Description copied from interface:Database
Delete several beans given their type and id values with an explicit transaction.
-
deleteAllPermanent
public int deleteAllPermanent(Class<?> beanType, Collection<?> ids)
Description copied from interface:Database
Delete permanent for several beans given their type and id values.- Specified by:
deleteAllPermanent
in interfaceDatabase
-
deleteAllPermanent
public int deleteAllPermanent(Class<?> beanType, Collection<?> ids, Transaction t)
Description copied from interface:Database
Delete permanent for several beans given their type and id values with an explicit transaction.- Specified by:
deleteAllPermanent
in interfaceDatabase
-
delete
public boolean delete(Object bean, Transaction t) throws javax.persistence.OptimisticLockException
Delete the bean with the explicit transaction.
-
deletePermanent
public boolean deletePermanent(Object bean) throws javax.persistence.OptimisticLockException
Description copied from interface:Database
Delete a bean permanently without soft delete.- Specified by:
deletePermanent
in interfaceDatabase
- Throws:
javax.persistence.OptimisticLockException
-
deletePermanent
public boolean deletePermanent(Object bean, Transaction t) throws javax.persistence.OptimisticLockException
Description copied from interface:Database
Delete a bean permanently without soft delete using an explicit transaction.- Specified by:
deletePermanent
in interfaceDatabase
- Throws:
javax.persistence.OptimisticLockException
-
deleteAllPermanent
public int deleteAllPermanent(Collection<?> beans)
Description copied from interface:Database
Delete all the beans in the collection permanently without soft delete.- Specified by:
deleteAllPermanent
in interfaceDatabase
-
deleteAllPermanent
public int deleteAllPermanent(Collection<?> beans, Transaction t)
Description copied from interface:Database
Delete all the beans in the collection permanently without soft delete using an explicit transaction.- Specified by:
deleteAllPermanent
in interfaceDatabase
-
deleteAll
public int deleteAll(Collection<?> beans)
Delete all the beans in the collection.
-
deleteAll
public int deleteAll(Collection<?> beans, Transaction t)
Delete all the beans in the collection.
-
execute
public int execute(CallableSql callSql, Transaction t)
Execute the CallableSql with an explicit transaction.
-
execute
public int execute(CallableSql callSql)
Execute the CallableSql.
-
execute
public int execute(SqlUpdate updSql, Transaction t)
Execute the updateSql with an explicit transaction.
-
executeNow
public int executeNow(SpiSqlUpdate sqlUpdate)
Description copied from interface:SpiEbeanServer
Execute the sql update regardless of transaction batch mode.- Specified by:
executeNow
in interfaceSpiEbeanServer
-
addBatch
public void addBatch(SpiSqlUpdate sqlUpdate, SpiTransaction transaction)
Description copied from interface:SpiEbeanServer
Add to JDBC batch for later execution.- Specified by:
addBatch
in interfaceSpiEbeanServer
-
executeBatch
public int[] executeBatch(SpiSqlUpdate sqlUpdate, SpiTransaction transaction)
Description copied from interface:SpiEbeanServer
Execute the batched statement.- Specified by:
executeBatch
in interfaceSpiEbeanServer
-
execute
public int execute(SqlUpdate updSql)
Execute the updateSql.- Specified by:
execute
in interfaceDatabase
- Parameters:
updSql
- the update sql potentially with bind values- Returns:
- the number of rows updated or deleted. -1 if executed in batch.
- See Also:
CallableSql
-
execute
public int execute(Update<?> update, Transaction t)
Execute the updateSql with an explicit transaction.
-
getBeanDescriptors
public List<BeanDescriptor<?>> getBeanDescriptors()
Return all the BeanDescriptors.- Specified by:
getBeanDescriptors
in interfaceSpiEbeanServer
-
getTransactionManager
public SpiTransactionManager getTransactionManager()
Return the transaction manager.- Specified by:
getTransactionManager
in interfaceSpiEbeanServer
-
register
public void register(BeanPersistController c)
-
deregister
public void deregister(BeanPersistController c)
-
isSupportedType
public boolean isSupportedType(Type genericType)
Description copied from interface:SpiEbeanServer
Return true if the type is known as an Entity or Xml type or a List Set or Map of known bean types.- Specified by:
isSupportedType
in interfaceSpiEbeanServer
-
setBeanId
public Object setBeanId(Object bean, Object id)
Description copied from interface:Database
Set the Id value onto the bean converting the type of the id value if necessary.For example, if the id value passed in is a String but ought to be a Long or UUID etc then it will automatically be converted.
-
getBeanId
public Object getBeanId(Object bean)
Description copied from interface:Database
Return the value of the Id property for a given bean.
-
getBeanDescriptor
public <T> BeanDescriptor<T> getBeanDescriptor(Class<T> beanClass)
Return the BeanDescriptor for a given type of bean.- Specified by:
getBeanDescriptor
in interfaceSpiEbeanServer
-
getBeanDescriptors
public List<BeanDescriptor<?>> getBeanDescriptors(String tableName)
Return the BeanDescriptor's for a given table name.- Specified by:
getBeanDescriptors
in interfaceSpiEbeanServer
-
getBeanTypes
public List<? extends BeanType<?>> getBeanTypes()
Return all the SPI BeanTypes.- Specified by:
getBeanTypes
in interfaceSpiServer
-
getBeanTypes
public List<? extends BeanType<?>> getBeanTypes(String tableName)
Return the SPI bean types mapped to the given table.- Specified by:
getBeanTypes
in interfaceSpiServer
-
getBeanTypeForQueueId
public BeanType<?> getBeanTypeForQueueId(String queueId)
Description copied from interface:SpiServer
Return the bean type for a given doc store queueId.- Specified by:
getBeanTypeForQueueId
in interfaceSpiServer
-
getBeanDescriptorByQueueId
public BeanDescriptor<?> getBeanDescriptorByQueueId(String queueId)
Description copied from interface:SpiEbeanServer
Return BeanDescriptor using it's unique doc store queueId.- Specified by:
getBeanDescriptorByQueueId
in interfaceSpiEbeanServer
-
getBeanType
public <T> BeanType<T> getBeanType(Class<T> beanType)
Return the SPI bean types for the given bean class.- Specified by:
getBeanType
in interfaceSpiServer
-
getBeanDescriptorById
public BeanDescriptor<?> getBeanDescriptorById(String beanClassName)
Return the BeanDescriptor using its class name.- Specified by:
getBeanDescriptorById
in interfaceSpiEbeanServer
-
remoteTransactionEvent
public void remoteTransactionEvent(RemoteTransactionEvent event)
Another server in the cluster sent this event so that we can inform local BeanListeners of inserts updates and deletes that occurred remotely (on another server in the cluster).- Specified by:
remoteTransactionEvent
in interfaceSpiEbeanServer
-
clearServerTransaction
public void clearServerTransaction()
Description copied from interface:SpiEbeanServer
Clear an implicit transaction from the scope.- Specified by:
clearServerTransaction
in interfaceSpiEbeanServer
-
beginServerTransaction
public SpiTransaction beginServerTransaction()
Description copied from interface:SpiEbeanServer
Begin a managed transaction (Uses scope manager / ThreadLocal).- Specified by:
beginServerTransaction
in interfaceSpiEbeanServer
-
createReadOnlyTransaction
public SpiTransaction createReadOnlyTransaction(Object tenantId)
Description copied from interface:SpiEbeanServer
Create a ServerTransaction for query purposes.- Specified by:
createReadOnlyTransaction
in interfaceSpiEbeanServer
- Parameters:
tenantId
- For multi-tenant lazy loading provide the tenantId to use.
-
createCallOrigin
public CallOrigin createCallOrigin()
Create a CallStack object.This trims off the avaje ebean part of the stack trace so that the first element in the CallStack should be application code.
- Specified by:
createCallOrigin
in interfaceSpiEbeanServer
-
docStore
public DocumentStore docStore()
Description copied from interface:Database
Return the Document store.
-
json
public JsonContext json()
Description copied from interface:Database
Return the JsonContext for reading/writing JSON.This instance is safe to be used concurrently by multiple threads and this method is cheap to call.
Simple example:
JsonContext json = database.json(); String jsonOutput = json.toJson(list); System.out.println(jsonOutput);
Using PathProperties:
// specify just the properties we want PathProperties paths = PathProperties.parse("name, status, anniversary"); List<Customer> customers = database.find(Customer.class) // apply those paths to the query (only fetch what we need) .apply(paths) .where().ilike("name", "rob%") .findList(); // ... get the json JsonContext jsonContext = database.json(); String json = jsonContext.toJson(customers, paths);
- Specified by:
json
in interfaceDatabase
- See Also:
FetchPath
,Query.apply(FetchPath)
-
jsonExtended
public SpiJsonContext jsonExtended()
Description copied from interface:SpiEbeanServer
Return the server extended Json context.- Specified by:
jsonExtended
in interfaceSpiEbeanServer
-
slowQueryCheck
public void slowQueryCheck(long timeMicros, int rowCount, SpiQuery<?> query)
Description copied from interface:SpiEbeanServer
Check for slow query event.- Specified by:
slowQueryCheck
in interfaceSpiEbeanServer
-
checkUniqueness
public Set<Property> checkUniqueness(Object bean)
Description copied from interface:Database
This method checks the uniqueness of a bean. I.e. if the save will work. It will return the properties that violates an unique / primary key. This may be done in an UI save action to validate if the user has entered correct values.Note: This method queries the DB for uniqueness of all indices, so do not use it in a batch update.
Note: This checks only the root bean!
// there is a unique constraint on title Document doc = new Document(); doc.setTitle("One flew over the cuckoo's nest"); doc.setBody("clashes with doc1"); Set<Property> properties = DB.checkUniqueness(doc); if (properties.isEmpty()) { // it is unique ... carry on } else { // build a user friendly message // to return message back to user String uniqueProperties = properties.toString(); StringBuilder msg = new StringBuilder(); properties.forEach((it)-> { Object propertyValue = it.getVal(doc); String propertyName = it.getName(); msg.append(" property["+propertyName+"] value["+propertyValue+"]"); }); // uniqueProperties > [title] // custom msg > property[title] value[One flew over the cuckoo's nest] }
- Specified by:
checkUniqueness
in interfaceDatabase
- Parameters:
bean
- The entity bean to check uniqueness on- Returns:
- a set of Properties if constraint validation was detected or empty list.
-
checkUniqueness
public Set<Property> checkUniqueness(Object bean, Transaction transaction)
Description copied from interface:Database
Same asDatabase.checkUniqueness(Object)
. but with given transaction.- Specified by:
checkUniqueness
in interfaceDatabase
-
visitMetrics
public void visitMetrics(MetricVisitor visitor)
Description copied from interface:SpiEbeanServer
Visit all the metrics (typically reporting them).- Specified by:
visitMetrics
in interfaceSpiEbeanServer
-
createQueryBindCapture
public SpiQueryBindCapture createQueryBindCapture(SpiQueryPlan plan)
Description copied from interface:SpiEbeanServer
Create a query bind capture for the given query plan.- Specified by:
createQueryBindCapture
in interfaceSpiEbeanServer
-
-