- All Known Subinterfaces:
SpiServer
Registration with the DB singleton
When a Database instance is created it can be registered with the DB
singleton (see DatabaseConfig.setRegister(boolean)
). The DB
singleton is essentially a map of Database's that have been registered
with it.
The Database can then be retrieved later via DB.byName(String)
.
The 'default' Database
One Database can be designated as the 'default' or 'primary' Database
(see DatabaseConfig.setDefaultServer(boolean)
. Many methods on DB
such as DB.find(Class)
etc are actually just a convenient way to
call methods on the 'default/primary' Database.
Constructing a Database
Database's are constructed by the DatabaseFactory. They can be created
programmatically via DatabaseFactory.create(DatabaseConfig)
or they
can be automatically constructed on demand using configuration information in
the application.properties file.
Example: Get a Database
// Get access to the Human Resources Database
Database hrDatabase = DB.byName("hr");
// fetch contact 3 from the HR database
Contact contact = hrDatabase.find(Contact.class, new Integer(3));
contact.setStatus("INACTIVE"); ...
// save the contact back to the HR database
hrDatabase.save(contact);
Database vs DB API
Database provides additional API compared with DB. For example it provides more control over the use of Transactions that is not available in the DB API.
External Transactions: If you wanted to use transactions created externally to Ebean then Database provides additional methods where you can explicitly pass a transaction (that can be created externally).
Bypass ThreadLocal Mechanism: If you want to bypass the built in ThreadLocal transaction management you can use the createTransaction() method. Example: a single thread requires more than one transaction.
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionautoTune()
Return AutoTune which is used to control the AutoTune service at runtime.Return the BackgroundExecutor service for asynchronous processing of queries.Return the value of the Id property for a given bean.Set the Id value onto the bean converting the type of the id value if necessary.Return the BeanState for a given entity bean.Start a transaction with 'REQUIRED' semantics.beginTransaction
(io.ebean.annotation.TxIsolation isolation) Start a transaction additionally specifying the isolation level.beginTransaction
(TxScope scope) Start a transaction typically specifying REQUIRES_NEW or REQUIRED semantics.Return the manager of the server cache ("L2" cache).checkUniqueness
(Object bean) This method checks the uniqueness of a bean.checkUniqueness
(Object bean, Transaction transaction) Same ascheckUniqueness(Object)
.void
Commit the current transaction.createCallableSql
(String callableSql) Create a CallableSql to execute a given stored procedure.<T> CsvReader<T>
createCsvReader
(Class<T> beanType) Create a CsvReader for a given beanType.<T> T
createEntityBean
(Class<T> type) Create a new instance of T that is an EntityBean.<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> Query<T>
createQuery
(Class<T> beanType) Create a query for an entity bean and synonym forfind(Class)
.<T> Query<T>
createQuery
(Class<T> beanType, String ormQuery) 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).Create a new transaction that is not held in TransactionThreadLocal.createTransaction
(io.ebean.annotation.TxIsolation isolation) Create a new transaction additionally specifying 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).Returns the current transaction or null if there is no current transaction in scope.Return the associated DataSource for this Database instance.int
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 the bean.boolean
delete
(Object bean, Transaction transaction) Delete the bean with an explicit transaction.int
deleteAll
(Class<?> beanType, Collection<?> ids) Delete several beans given their type and id values.int
deleteAll
(Class<?> beanType, Collection<?> ids, Transaction transaction) 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 transaction) Delete all the beans in the collection using an explicit transaction.int
deleteAllPermanent
(Class<?> beanType, Collection<?> ids) Delete permanent for several beans given their type and id values.int
deleteAllPermanent
(Class<?> beanType, Collection<?> ids, Transaction transaction) 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 transaction) 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 transaction) Delete a bean permanently without soft delete using an explicit transaction.Return a map of the differences between two objects of the same type.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
If the current transaction has already been committed do nothing otherwise rollback the transaction.int
execute
(CallableSql callableSql) For making calls to stored procedures.int
execute
(CallableSql callableSql, Transaction transaction) Execute explicitly passing a transaction.int
Execute a Sql Update Delete or Insert statement.int
execute
(SqlUpdate updSql, Transaction transaction) Execute explicitly passing a transaction.void
Execute a Runnable in a Transaction with an explicit scope.int
Execute a ORM insert update or delete statement using the current transaction.int
execute
(Update<?> update, Transaction transaction) Execute a ORM insert update or delete statement with an explicit transaction.void
Execute a Runnable in a Transaction with the default scope.<T> T
executeCall
(TxScope scope, Callable<T> callable) Execute a TxCallable in a Transaction with an explicit scope.<T> T
executeCall
(Callable<T> callable) Execute a TxCallable in a Transaction with the default scope.Return the ExpressionFactory for this database.extended()
Return the extended API for Database.void
externalModification
(String tableName, boolean inserted, boolean updated, boolean deleted) Inform Ebean that tables have been modified externally.<T> Filter<T>
Create a filter for sorting and filtering lists of entities locally without going back to the database.<T> Query<T>
Create a query for a type of entity bean.<T> T
Find a bean using its unique id.<T> T
find
(Class<T> beanType, Object id, Transaction transaction) Find a entity bean with an explicit transaction.<T> DtoQuery<T>
Create a Query for DTO beans.<T> Query<T>
findNative
(Class<T> beanType, String nativeSql) Create a query using native SQL.void
flush()
Flush the JDBC batch on the current transaction.void
Insert the bean.void
insert
(Object bean, Transaction transaction) Insert the bean with a transaction.void
insertAll
(Collection<?> beans) Insert a collection of beans.void
insertAll
(Collection<?> beans, Transaction transaction) Insert a collection of beans with an explicit transaction.json()
Return the JsonContext for reading/writing JSON.void
Load and lock the bean usingselect for update
.void
markAsDirty
(Object bean) Marks the entity bean as dirty.void
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.metaInfo()
Return the MetaInfoManager which is used to get meta data from the Database such as query execution statistics.name()
Return the name.Return the next unique identity value for a given bean type.io.ebean.annotation.Platform
platform()
Return the platform used for this database instance.Return the extended API intended for use by plugins.<T> List<T>
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 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.Return the associated read only DataSource for this Database instance (can be null).<T> T
Get a reference object.void
Refresh the values of a bean.void
refreshMany
(Object bean, String propertyName) Refresh a many property of an entity bean.void
register
(TransactionCallback transactionCallback) Register a TransactionCallback on the currently active transaction.void
Rollback the current transaction.void
Either Insert or Update the bean depending on its state.void
save
(Object bean, Transaction transaction) Insert or update a bean with an explicit transaction.int
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.script()
Return a ScriptRunner for running SQL or DDL scripts.void
shutdown()
Shutdown the Database instance.void
shutdown
(boolean shutdownDataSource, boolean deregisterDriver) Shutdown the Database instance programmatically.<T> void
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.Look to execute a native sql query that does not return beans but instead returns SqlRow or direct access to ResultSet.Look to execute a native sql insert update or delete statement.void
Truncate the base tables for the given bean types.void
Truncate all the given tables.<T> UpdateQuery<T>
Create an Update query to perform a bulk update.void
Saves the bean using an update.void
update
(Object bean, Transaction transaction) Update a bean additionally specifying a transaction.void
updateAll
(Collection<?> beans) Update a collection of beans.void
updateAll
(Collection<?> beans, Transaction transaction) Update a collection of beans with an explicit transaction.validateQuery
(Query<T> query) Returns the set of properties/paths that are unknown (do not map to known properties or paths).
-
Method Details
-
shutdown
void shutdown()Shutdown the Database instance. -
shutdown
void shutdown(boolean shutdownDataSource, boolean deregisterDriver) Shutdown the Database instance programmatically.This method is not normally required. Ebean registers a shutdown hook and shuts down cleanly.
If the under underlying DataSource is the Ebean implementation then you also have the option of shutting down the DataSource and deregistering the JDBC driver.
- Parameters:
shutdownDataSource
- if true then shutdown the underlying DataSource if it is the Ebean DataSource implementation.deregisterDriver
- if true then deregister the JDBC driver if it is the Ebean DataSource implementation.
-
autoTune
AutoTune autoTune()Return AutoTune which is used to control the AutoTune service at runtime. -
dataSource
DataSource dataSource()Return the associated DataSource for this Database instance. -
readOnlyDataSource
DataSource readOnlyDataSource()Return the associated read only DataSource for this Database instance (can be null). -
name
String name()Return the name. This is used withDB.byName(String)
to get a Database that was registered with the DB singleton. -
expressionFactory
ExpressionFactory expressionFactory()Return the ExpressionFactory for this database. -
metaInfo
MetaInfoManager metaInfo()Return the MetaInfoManager which is used to get meta data from the Database such as query execution statistics. -
platform
io.ebean.annotation.Platform platform()Return the platform used for this database instance.Note many platforms have multiple specific platform types so often we want to get the base platform via
Platform.base()
.Platform platform = database.getPlatform().base(); if (platform == Platform.MYSQL) { // do MySql specific function }
- Returns:
- platform for this database instance
-
pluginApi
SpiServer pluginApi()Return the extended API intended for use by plugins. -
beanState
Return the BeanState for a given entity bean.This will return null if the bean is not an enhanced entity bean.
-
beanId
Return the value of the Id property for a given bean. -
beanId
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.
- Parameters:
bean
- The entity bean to set the id value on.id
- The id value to set.
-
diff
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.
-
createEntityBean
Create a new instance of T that is an EntityBean.Useful if you use BeanPostConstructListeners or @PostConstruct Annotations. In this case you should not use "new Bean...()". Making all bean constructors protected could be a good idea here.
-
createCsvReader
Create a CsvReader for a given beanType. -
update
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();
- Type Parameters:
T
- The type of entity bean- Parameters:
beanType
- The type of entity bean to update- Returns:
- The update query to use
-
createNamedQuery
Create a named query.For RawSql the named query is expected to be in ebean.xml.
- Type Parameters:
T
- The type of entity bean- Parameters:
beanType
- The type of entity beannamedQuery
- The name of the query- Returns:
- The query
-
createQuery
Create a query for an entity bean and synonym forfind(Class)
.- See Also:
-
createQuery
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();
- Type Parameters:
T
- The type of the entity bean- Parameters:
beanType
- The type of bean to fetchormQuery
- The Ebean ORM query- Returns:
- The query with expressions defined as per the parsed query statement
-
find
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
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();
- 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
-
nextId
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.
-
filter
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. -
sort
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");
- Parameters:
list
- the list of entity beanssortByClause
- the properties to sort the list by
-
createUpdate
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);
-
findDto
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.
- Type Parameters:
T
- The type of the DTO bean.- Parameters:
dtoType
- The type of the DTO bean the rows will be mapped into.sql
- The SQL query to execute.
-
createNamedDtoQuery
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.
- 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
-
sqlQuery
Look to execute a native sql query that does not return beans but instead returns SqlRow or direct access to ResultSet.Refer to
DtoQuery
for native sql queries returning DTO beans.Refer to
findNative(Class, String)
for native sql queries returning entity beans. -
sqlUpdate
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.- Returns:
- The SqlUpdate instance to set parameters and execute
-
createCallableSql
Create a CallableSql to execute a given stored procedure. -
register
void register(TransactionCallback transactionCallback) throws javax.persistence.PersistenceException Register a TransactionCallback on the currently active transaction. If there is no currently active transaction then a PersistenceException is thrown.- Parameters:
transactionCallback
- The transaction callback to be registered with the current transaction.- Throws:
javax.persistence.PersistenceException
- If there is no currently active transaction
-
createTransaction
Transaction createTransaction()Create a new transaction that is not held in TransactionThreadLocal.You will want to do this if you want multiple Transactions in a single thread or generally use transactions outside of the TransactionThreadLocal management.
-
createTransaction
Create a new transaction additionally specifying the isolation level.Note that this transaction is NOT stored in a thread local.
-
beginTransaction
Transaction beginTransaction()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.
-
beginTransaction
Start a transaction additionally specifying the isolation level. -
beginTransaction
Start a transaction typically specifying REQUIRES_NEW or REQUIRED semantics.Note that this provides an try finally alternative to using
executeCall(TxScope, Callable)
orexecute(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(); }
-
currentTransaction
Transaction currentTransaction()Returns the current transaction or null if there is no current transaction in scope. -
flush
void flush()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
void commitTransaction()Commit the current transaction. -
rollbackTransaction
void rollbackTransaction()Rollback the current transaction. -
endTransaction
void endTransaction()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(); }
-
refresh
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.
-
refreshMany
Refresh a many property of an entity bean.- Parameters:
bean
- the entity bean containing the 'many' propertypropertyName
- the 'many' property to be refreshed
-
find
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();
- Parameters:
beanType
- the type of entity bean to fetchid
- the id value
-
reference
Get a reference object.This will not perform a query against the database unless some property other that the id property is accessed.
It is most commonly used to set a 'foreign key' on another bean like:
Product product = database.getReference(Product.class, 1); OrderDetail orderDetail = new OrderDetail(); // set the product 'foreign key' orderDetail.setProduct(product); orderDetail.setQuantity(42); ... database.save(orderDetail);
Lazy loading characteristics
Product product = database.getReference(Product.class, 1); // You can get the id without causing a fetch/lazy load Long productId = product.getId(); // If you try to get any other property a fetch/lazy loading will occur // This will cause a query to execute... String name = product.getName();
- Parameters:
beanType
- the type of entity beanid
- the id value
-
extended
ExtendedServer extended()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.
-
save
Either Insert or Update the bean depending on its state.If there is no current transaction one will be created and committed for you automatically.
Save can cascade along relationships. For this to happen you need to specify a cascade of CascadeType.ALL or CascadeType.PERSIST on the OneToMany, OneToOne or ManyToMany annotation.
In this example below the details property has a CascadeType.ALL set so saving an order will also save all its details.
public class Order { ... @OneToMany(cascade=CascadeType.ALL, mappedBy="order") List<OrderDetail> details; ... }
When a save cascades via a OneToMany or ManyToMany Ebean will automatically set the 'parent' object to the 'detail' object. In the example below in saving the order and cascade saving the order details the 'parent' order will be set against each order detail when it is saved.
- Throws:
javax.persistence.OptimisticLockException
-
saveAll
Save all the beans in the collection.- Throws:
javax.persistence.OptimisticLockException
-
saveAll
Save all the beans.- Throws:
javax.persistence.OptimisticLockException
-
delete
Delete the bean.This will return true if the bean was deleted successfully or JDBC batch is being used.
If there is no current transaction one will be created and committed for you automatically.
If the Bean does not have a version property (or loaded version property) and the bean does not exist then this returns false indicating that nothing was deleted. Note that, if JDBC batch mode is used then this always returns true.
- Throws:
javax.persistence.OptimisticLockException
-
delete
boolean delete(Object bean, Transaction transaction) throws javax.persistence.OptimisticLockException Delete the bean with an explicit transaction.This will return true if the bean was deleted successfully or JDBC batch is being used.
If the Bean does not have a version property (or loaded version property) and the bean does not exist then this returns false indicating that nothing was deleted. However, if JDBC batch mode is used then this always returns true.
- Throws:
javax.persistence.OptimisticLockException
-
deletePermanent
Delete a bean permanently without soft delete.- Throws:
javax.persistence.OptimisticLockException
-
deletePermanent
boolean deletePermanent(Object bean, Transaction transaction) throws javax.persistence.OptimisticLockException Delete a bean permanently without soft delete using an explicit transaction.- Throws:
javax.persistence.OptimisticLockException
-
deleteAllPermanent
Delete all the beans in the collection permanently without soft delete.- Throws:
javax.persistence.OptimisticLockException
-
deleteAllPermanent
int deleteAllPermanent(Collection<?> beans, Transaction transaction) throws javax.persistence.OptimisticLockException Delete all the beans in the collection permanently without soft delete using an explicit transaction.- Throws:
javax.persistence.OptimisticLockException
-
delete
Delete the bean given its type and id. -
delete
Delete the bean given its type and id with an explicit transaction. -
deletePermanent
Delete permanent given the bean type and id. -
deletePermanent
Delete permanent given the bean type and id with an explicit transaction. -
deleteAll
Delete all the beans in the collection.- Throws:
javax.persistence.OptimisticLockException
-
deleteAll
int deleteAll(Collection<?> beans, Transaction transaction) throws javax.persistence.OptimisticLockException Delete all the beans in the collection using an explicit transaction.- Throws:
javax.persistence.OptimisticLockException
-
deleteAll
Delete several beans given their type and id values. -
deleteAll
Delete several beans given their type and id values with an explicit transaction. -
deleteAllPermanent
Delete permanent for several beans given their type and id values. -
deleteAllPermanent
Delete permanent for several beans given their type and id values with an explicit transaction. -
execute
Execute a Sql Update Delete or Insert statement. This returns the number of rows that where updated, deleted or inserted. If is executed in batch then this returns -1. You can get the actual rowCount after commit() from updateSql.getRowCount().If you wish to execute a Sql Select natively then you should use the SqlQuery object or DtoQuery.
Note that the table modification information is automatically deduced and you do not need to call the DB.externalModification() method when you use this method.
Example:
// example that uses 'named' parameters String s = "UPDATE f_topic set post_count = :count where id = :id" SqlUpdate update = database.createSqlUpdate(s); update.setParameter("id", 1); update.setParameter("count", 50); int modifiedCount = database.execute(update); String msg = "There where " + modifiedCount + "rows updated";
- Parameters:
sqlUpdate
- the update sql potentially with bind values- Returns:
- the number of rows updated or deleted. -1 if executed in batch.
- See Also:
-
execute
Execute a ORM insert update or delete statement using the current transaction.This returns the number of rows that where inserted, updated or deleted.
-
execute
Execute a ORM insert update or delete statement with an explicit transaction. -
execute
For making calls to stored procedures.Example:
String sql = "{call sp_order_modify(?,?,?)}"; CallableSql cs = database.createCallableSql(sql); cs.setParameter(1, 27); cs.setParameter(2, "SHIPPED"); cs.registerOut(3, Types.INTEGER); cs.execute(); // read the out parameter Integer returnValue = (Integer) cs.getObject(3);
-
externalModification
Inform Ebean that tables have been modified externally. These could be the result of from calling a stored procedure, other JDBC calls or external programs including other frameworks.If you use database.execute(UpdateSql) then the table modification information is automatically deduced and you do not need to call this method yourself.
This information is used to invalidate objects out of the cache and potentially text indexes. This information is also automatically broadcast across the cluster.
If there is a transaction then this information is placed into the current transactions event information. When the transaction is committed this information is registered (with the transaction manager). If this transaction is rolled back then none of the transaction event information registers including the information you put in via this method.
If there is NO current transaction when you call this method then this information is registered immediately (with the transaction manager).
- Parameters:
tableName
- the name of the table that was modifiedinserted
- true if rows where inserted into the tableupdated
- true if rows on the table where updateddeleted
- true if rows on the table where deleted
-
find
Find a entity bean with an explicit transaction.- Type Parameters:
T
- the type of entity bean to find- Parameters:
beanType
- the type of entity bean to findid
- the bean id valuetransaction
- the transaction to use (can be null)
-
save
Insert or update a bean with an explicit transaction.- Throws:
javax.persistence.OptimisticLockException
-
saveAll
int saveAll(Collection<?> beans, Transaction transaction) throws javax.persistence.OptimisticLockException Save all the beans in the collection with an explicit transaction.- Throws:
javax.persistence.OptimisticLockException
-
checkUniqueness
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] }
- Parameters:
bean
- The entity bean to check uniqueness on- Returns:
- a set of Properties if constraint validation was detected or empty list.
-
checkUniqueness
Same ascheckUniqueness(Object)
. but with given transaction. -
markAsDirty
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);
-
update
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);
- Throws:
javax.persistence.OptimisticLockException
-
update
Update a bean additionally specifying a transaction.- Throws:
javax.persistence.OptimisticLockException
-
updateAll
Update a collection of beans. If there is no current transaction one is created and used to update all the beans in the collection.- Throws:
javax.persistence.OptimisticLockException
-
updateAll
void updateAll(Collection<?> beans, Transaction transaction) throws javax.persistence.OptimisticLockException Update a collection of beans with an explicit transaction.- Throws:
javax.persistence.OptimisticLockException
-
merge
Merge the bean using the default merge options (no paths specified, default delete).- Parameters:
bean
- The bean to merge
-
merge
Merge the bean using the given merge options.- Parameters:
bean
- The bean to mergeoptions
- The options to control the merge
-
merge
Merge the bean using the given merge options and a transaction.- Parameters:
bean
- The bean to mergeoptions
- The options to control the merge
-
insert
Insert the bean.Compared to save() this forces bean to perform an insert rather than trying to decide based on the bean state. As such this is useful when you fetch beans from one database and want to insert them into another database (and you want to explicitly insert them).
-
insert
Insert the bean with a transaction. -
insertAll
Insert a collection of beans. If there is no current transaction one is created and used to insert all the beans in the collection. -
insertAll
Insert a collection of beans with an explicit transaction. -
execute
Execute explicitly passing a transaction. -
execute
Execute explicitly passing a transaction. -
execute
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); ... } });
-
execute
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(); });
-
executeCall
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(); } });
-
executeCall
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(); } });
-
cacheManager
ServerCacheManager cacheManager()Return the manager of the server cache ("L2" cache). -
backgroundExecutor
BackgroundExecutor backgroundExecutor()Return the BackgroundExecutor service for asynchronous processing of queries. -
json
JsonContext json()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);
- See Also:
-
script
ScriptRunner script()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. -
docStore
DocumentStore docStore()Return the Document store. -
publish
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.
- Type Parameters:
T
- the type of the entity bean- Parameters:
beanType
- the type of the entity beanid
- the id of the entity beantransaction
- the transaction the publish process should use (can be null)
-
publish
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.
- Type Parameters:
T
- the type of the entity bean- Parameters:
beanType
- the type of the entity beanid
- the id of the entity bean
-
publish
Publish the beans that match the query returning the resulting published beans.The values are published from the draft beans to the live beans.
- Type Parameters:
T
- the type of the entity bean- Parameters:
query
- the query used to select the draft beans to publishtransaction
- the transaction the publish process should use (can be null)
-
publish
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.
- Type Parameters:
T
- the type of the entity bean- Parameters:
query
- the query used to select the draft beans to publish
-
draftRestore
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.- 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
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.- 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
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.- 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
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.- Type Parameters:
T
- the type of the entity bean- Parameters:
query
- the query used to select the draft beans to restore
-
validateQuery
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.
-
lock
Load and lock the bean usingselect for update
.This should be executed inside a transaction and results in the bean being loaded or refreshed from the database and a database row lock held via
select for update
.The bean needs to have an ID property set and can be a reference bean (only has ID) or partially or fully populated bean. This will load all the properties of the bean from the database using
select for update
obtaining a database row lock (using WAIT).- Parameters:
bean
- The entity bean that we wish to obtain a database lock on.
-
truncate
Truncate all the given tables. -
truncate
Truncate the base tables for the given bean types.
-