public interface EbeanServer
Registration with the Ebean Singleton:
When a EbeanServer is constructed it can be registered with the Ebean
singleton (see ServerConfig.setRegister(boolean)). The Ebean
singleton is essentially a map of EbeanServer's that have been registered
with it. The EbeanServer can then be retrieved later via
Ebean.getServer(String).
The 'default' EbeanServer
One EbeanServer can be designated as the 'default' or 'primary' EbeanServer
(see ServerConfig.setDefaultServer(boolean). Many methods on Ebean
such as Ebean.find(Class) etc are actually just a convenient way to
call methods on the 'default/primary' EbeanServer. This is handy for
applications that use a single DataSource.
There is one EbeanServer per Database (javax.sql.DataSource). One EbeanServer
is referred to as the 'default' server and that is the one that
Ebean methods such as Ebean.find(Class) use.
Constructing a EbeanServer
EbeanServer's are constructed by the EbeanServerFactory. They can be created
programmatically via EbeanServerFactory.create(ServerConfig) or they
can be automatically constructed on demand using configuration information in
the ebean.properties file.
Example: Get a EbeanServer
// Get access to the Human Resources EbeanServer/Database
EbeanServer hrServer = Ebean.getServer("HR");
// fetch contact 3 from the HR database Contact contact =
hrServer.find(Contact.class, new Integer(3));
contact.setStatus("INACTIVE"); ...
// save the contact back to the HR database hrServer.save(contact);
EbeanServer has more API than Ebean
EbeanServer provides additional API compared with Ebean. For example it
provides more control over the use of Transactions that is not available in
the Ebean API.
External Transactions: If you wanted to use transactions created externally to eBean then EbeanServer 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.
Ebean,
EbeanServerFactory,
ServerConfig| Modifier and Type | Method and Description |
|---|---|
Transaction |
beginTransaction()
Start a transaction with 'REQUIRED' semantics.
|
Transaction |
beginTransaction(TxIsolation isolation)
Start a transaction additionally specifying the isolation level.
|
Transaction |
beginTransaction(TxScope scope)
Start a transaction typically specifying REQUIRES_NEW or REQUIRED semantics.
|
void |
commitTransaction()
Commit the current transaction.
|
CallableSql |
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> Query<T> |
createNamedQuery(Class<T> beanType,
String namedQuery)
Return a named Query that will have defined fetch paths, predicates etc.
|
SqlQuery |
createNamedSqlQuery(String namedQuery)
Create a named sql query.
|
SqlUpdate |
createNamedSqlUpdate(String namedQuery)
Create a named sql update.
|
<T> Update<T> |
createNamedUpdate(Class<T> beanType,
String namedUpdate)
Create a named orm update.
|
<T> Query<T> |
createQuery(Class<T> beanType)
Create a query for an entity bean and synonym for
find(Class). |
<T> Query<T> |
createQuery(Class<T> beanType,
String query)
Create a query using the query language.
|
SqlQuery |
createSqlQuery(String sql)
Create a SqlQuery for executing native sql
query statements.
|
SqlUpdate |
createSqlUpdate(String sql)
Create a sql update for executing native dml statements.
|
Transaction |
createTransaction()
Create a new transaction that is not held in TransactionThreadLocal.
|
Transaction |
createTransaction(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).
|
Transaction |
currentTransaction()
Returns the current transaction or null if there is no current transaction in scope.
|
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 transaction)
Delete the bean with an explicit transaction.
|
<T> int |
delete(Query<T> query,
Transaction transaction)
Execute as a delete query deleting the 'root level' beans that match the predicates
in the query.
|
void |
deleteAll(Class<?> beanType,
Collection<?> ids)
Delete several beans given their type and id values.
|
void |
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(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 |
deleteManyToManyAssociations(Object ownerBean,
String propertyName)
Delete the associations (from the intersection table) of a ManyToMany given
the owner bean and the propertyName of the ManyToMany collection.
|
int |
deleteManyToManyAssociations(Object ownerBean,
String propertyName,
Transaction transaction)
Delete the associations (from the intersection table) of a ManyToMany given
the owner bean and the propertyName of the ManyToMany collection.
|
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.
|
Map<String,ValuePair> |
diff(Object newBean,
Object oldBean)
Return a map of the differences between two objects of the same type.
|
<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.
|
<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.
|
void |
endTransaction()
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(SqlUpdate sqlUpdate)
Execute a Sql Update Delete or Insert statement.
|
int |
execute(SqlUpdate updSql,
Transaction transaction)
Execute explicitly passing a transaction.
|
<T> T |
execute(TxCallable<T> callable)
Execute a TxCallable in a Transaction with the default scope.
|
void |
execute(TxRunnable runnable)
Execute a TxRunnable in a Transaction with the default scope.
|
<T> T |
execute(TxScope scope,
TxCallable<T> callable)
Execute a TxCallable in a Transaction with an explicit scope.
|
void |
execute(TxScope scope,
TxRunnable runnable)
Execute a TxRunnable in a Transaction with an explicit scope.
|
int |
execute(Update<?> update)
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 |
externalModification(String tableName,
boolean inserted,
boolean updated,
boolean deleted)
Inform Ebean that tables have been modified externally.
|
<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 id)
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> void |
findEach(Query<T> query,
QueryEachConsumer<T> consumer,
Transaction transaction)
Execute the query visiting the each bean one at a time.
|
<T> void |
findEachWhile(Query<T> query,
QueryEachWhileConsumer<T> consumer,
Transaction transaction)
Execute the query visiting the each bean one at a time.
|
<T> FutureIds<T> |
findFutureIds(Query<T> query,
Transaction transaction)
Execute find Id's query in a background thread.
|
<T> FutureList<T> |
findFutureList(Query<T> query,
Transaction transaction)
Execute find list query in a background thread returning a FutureList object.
|
SqlFutureList |
findFutureList(SqlQuery query,
Transaction transaction)
Execute find list SQL query in a background thread.
|
<T> FutureRowCount<T> |
findFutureRowCount(Query<T> query,
Transaction transaction)
Execute find row count query in a background thread.
|
<T> List<Object> |
findIds(Query<T> query,
Transaction transaction)
Return the Id values of the query as a List.
|
<T> QueryIterator<T> |
findIterate(Query<T> query,
Transaction transaction)
Return a QueryIterator for the query.
|
<T> List<T> |
findList(Query<T> query,
Transaction transaction)
Execute a query returning a list of beans.
|
List<SqlRow> |
findList(SqlQuery query,
Transaction transaction)
Execute the sql query returning a list of MapBean.
|
<T> Map<?,T> |
findMap(Query<T> query,
Transaction transaction)
Execute the query returning the entity beans in a Map.
|
Map<?,SqlRow> |
findMap(SqlQuery query,
Transaction transaction)
Execute the sql query returning a map of MapBean.
|
<T> PagedList<T> |
findPagedList(Query<T> query,
Transaction transaction)
Return a PagedList for this query using firstRow and maxRows.
|
<T> PagedList<T> |
findPagedList(Query<T> query,
Transaction transaction,
int pageIndex,
int pageSize)
Return a PagedList for this query using pageIndex and pageSize.
|
<T> int |
findRowCount(Query<T> query,
Transaction transaction)
Return the number of 'top level' or 'root' entities this query should
return.
|
<T> Set<T> |
findSet(Query<T> query,
Transaction transaction)
Execute the query returning a set of entity beans.
|
Set<SqlRow> |
findSet(SqlQuery query,
Transaction transaction)
Execute the sql query returning a set of MapBean.
|
<T> T |
findUnique(Query<T> query,
Transaction transaction)
Execute the query returning at most one entity bean or null (if no matching
bean is found).
|
SqlRow |
findUnique(SqlQuery query,
Transaction transaction)
Execute the sql query returning a single MapBean or null.
|
<T> List<Version<T>> |
findVersions(Query<T> query,
Transaction transaction)
Return versions of a @History entity bean.
|
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.
|
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.
|
ExpressionFactory |
getExpressionFactory()
Return the ExpressionFactory for this server.
|
MetaInfoManager |
getMetaInfoManager()
Return the MetaInfoManager which is used to get meta data from the EbeanServer
such as query execution statistics.
|
String |
getName()
Return the name.
|
SpiServer |
getPluginApi()
Return the extended API intended for use by plugins.
|
<T> T |
getReference(Class<T> beanType,
Object id)
Get a reference object.
|
ServerCacheManager |
getServerCacheManager()
Return the manager of the server cache ("L2" cache).
|
void |
insert(Object bean)
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.
|
JsonContext |
json()
Return the JsonContext for reading/writing JSON.
|
void |
markAsDirty(Object bean)
Marks the entity bean as dirty.
|
Object |
nextId(Class<?> beanType)
Return the next unique identity value for a given bean type.
|
<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.
|
<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.
|
void |
refresh(Object bean)
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 |
rollbackTransaction()
Rollback the current transaction.
|
void |
runCacheWarming()
Run the cache warming queries on all bean types that have one defined.
|
void |
runCacheWarming(Class<?> beanType)
Run the cache warming query for a specific bean type.
|
void |
save(Object bean)
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 |
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 |
saveAssociation(Object ownerBean,
String propertyName)
Save the associated collection or bean given the property name.
|
void |
saveAssociation(Object ownerBean,
String propertyName,
Transaction transaction)
Save the associated collection or bean given the property name with a
specific transaction.
|
void |
saveManyToManyAssociations(Object ownerBean,
String propertyName)
Save the associations of a ManyToMany given the owner bean and the
propertyName of the ManyToMany collection.
|
void |
saveManyToManyAssociations(Object ownerBean,
String propertyName,
Transaction transaction)
Save the associations of a ManyToMany given the owner bean and the
propertyName of the ManyToMany collection.
|
void |
shutdown(boolean shutdownDataSource,
boolean deregisterDriver)
Shutdown the EbeanServer programmatically.
|
<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.
|
void |
update(Object bean)
Saves the bean using an update.
|
void |
update(Object bean,
Transaction transaction)
Update a bean additionally specifying a transaction.
|
void |
update(Object bean,
Transaction transaction,
boolean deleteMissingChildren)
Update a bean additionally specifying a transaction and the deleteMissingChildren setting.
|
void |
updateAll(Collection<?> beans)
Update a collection of beans.
|
void |
updateAll(Collection<?> beans,
Transaction transaction)
Update a collection of beans 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 shutdown(boolean shutdownDataSource, boolean deregisterDriver)
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.
shutdownDataSource - if true then shutdown the underlying DataSource if it is the EbeanORM
DataSource implementation.deregisterDriver - if true then deregister the JDBC driver if it is the EbeanORM
DataSource implementation.AutoTune getAutoTune()
String getName()
Ebean.getServer(String) to get a
EbeanServer that was registered with the Ebean singleton.ExpressionFactory getExpressionFactory()
MetaInfoManager getMetaInfoManager()
SpiServer getPluginApi()
BeanState getBeanState(Object bean)
This will return null if the bean is not an enhanced entity bean.
Map<String,ValuePair> diff(Object newBean, Object oldBean)
When null is passed in for b, then the 'OldValues' of a is used for the difference comparison.
<T> T createEntityBean(Class<T> type)
Generally not expected to be useful (now dynamic subclassing support was removed in favour of always using enhancement).
<T> CsvReader<T> createCsvReader(Class<T> beanType)
<T> Query<T> createNamedQuery(Class<T> beanType, String namedQuery)
The query is created from a statement that will be defined in a deployment orm xml file or NamedQuery annotations. The query will typically already define fetch paths, predicates, order by clauses etc so often you will just need to bind required parameters and then execute the query.
// example
Query<Order> query = ebeanServer.createNamedQuery(Order.class, "new.for.customer");
query.setParameter("customerId", 23);
List<Order> newOrders = query.findList();
<T> Query<T> createQuery(Class<T> beanType, String query)
Note that you are allowed to add additional clauses using where() as well as use fetch() and setOrderBy() after the query has been created.
Note that this method signature used to map to named queries and that has
moved to createNamedQuery(Class, String).
EbeanServer ebeanServer = ... ;
String q = "find order fetch details where status = :st";
List<Order> newOrders
= ebeanServer.createQuery(Order.class, q)
.setParameter("st", Order.Status.NEW)
.findList();
query - the object query<T> Query<T> createQuery(Class<T> beanType)
find(Class).find(Class)<T> Query<T> find(Class<T> beanType)
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 findUnique() 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 EbeanServer 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 = ebeanServer.find(Order.class)
.fetch("customer")
.fetch("details")
.fetch("detail.product", "name")
.setId(2)
.findUnique();
// find some new orders ... with firstRow/maxRows
List<Order> orders =
ebeanServer.find(Order.class)
.where().eq("status", Order.Status.NEW)
.setFirstRow(20)
.setMaxRows(10)
.findList();
Object nextId(Class<?> beanType)
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.
<T> Filter<T> filter(Class<T> beanType)
This produces and returns a new list with the sort and filters applied.
Refer to Filter for an example of its use.
<T> void sort(List<T> list, String sortByClause)
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 = ebeanServer.find(Order.class)
.fetch("customer")
.orderBy("id")
.findList();
// sort by customer name ascending, then by order shipDate
// ... then by the order status descending
ebeanServer.sort(list, "customer.name, shipDate, status desc");
// sort by customer name descending (with nulls low)
// ... then by the order id
ebeanServer.sort(list, "customer.name desc nullsLow, id");
list - the list of entity beanssortByClause - the properties to sort the list by<T> Update<T> createNamedUpdate(Class<T> beanType, String namedUpdate)
The orm update differs from the SqlUpdate in that it uses the bean name and bean property names rather than table and column names.
Note that named update statements can be specified in raw sql (with column and table names) or using bean name and bean property names. This can be specified with the isSql flag.
Example named updates:
package app.data;
import ...
@NamedUpdates(value = {
@NamedUpdate( name = "setTitle",
isSql = false,
notifyCache = false,
update = "update topic set title = :title, postCount = :postCount where id = :id"),
@NamedUpdate( name = "setPostCount",
notifyCache = false,
update = "update f_topic set post_count = :postCount where id = :id"),
@NamedUpdate( name = "incrementPostCount",
notifyCache = false,
isSql = false,
update = "update Topic set postCount = postCount + 1 where id = :id") })
@Entity
@Table(name = "f_topic")
public class Topic { ...
Example using a named update:
Update<Topic> update = ebeanServer.createNamedUpdate(Topic.class, "setPostCount");
update.setParameter("postCount", 10);
update.setParameter("id", 3);
int rows = update.execute();
System.out.println("rows updated: " + rows);
<T> Update<T> createUpdate(Class<T> beanType, String ormUpdate)
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 = ebeanServer.createUpdate(Topic.class, updStatement);
update.set("pc", 9);
update.set("id", 3);
int rows = update.execute();
System.out.println("rows updated:" + rows);
SqlQuery createSqlQuery(String sql)
Note that you can use raw SQL with entity beans, refer to the SqlSelect annotation for examples.
SqlQuery createNamedSqlQuery(String namedQuery)
The query statement will be defined in a deployment orm xml file.
namedQuery - the name of the querySqlUpdate createSqlUpdate(String sql)
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.
Where possible it would be expected practice to put the statement in a orm
xml file (named update) and use createNamedSqlUpdate(String) .
CallableSql createCallableSql(String callableSql)
SqlUpdate createNamedSqlUpdate(String namedQuery)
The statement (an Insert Update or Delete statement) will be defined in a deployment orm xml file.
// Use a namedQuery
UpdateSql update = Ebean.createNamedSqlUpdate("update.topic.count");
update.setParameter("count", 1);
update.setParameter("topicId", 50);
int modifiedCount = update.execute();
void register(TransactionCallback transactionCallback) throws javax.persistence.PersistenceException
transactionCallback - The transaction callback to be registered with the current transaction.javax.persistence.PersistenceException - If there is no currently active transactionTransaction createTransaction()
You will want to do this if you want multiple Transactions in a single thread or generally use transactions outside of the TransactionThreadLocal management.
Transaction createTransaction(TxIsolation isolation)
Note that this transaction is NOT stored in a thread local.
Transaction beginTransaction()
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.
// start a transaction (stored in a ThreadLocal)
ebeanServer.beginTransaction();
try {
Order order = ebeanServer.find(Order.class,10);
ebeanServer.save(order);
ebeanServer.commitTransaction();
} finally {
// rollback if we didn't commit
// i.e. an exception occurred before commitTransaction().
ebeanServer.endTransaction();
}
Transaction txn = ebeanServer.beginTransaction();
try {
// 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.flushBatch();
...
txn.commit();
} finally {
// rollback if necessary
txn.end();
}
If you want to externalise the transaction management then you use createTransaction() and pass the transaction around to the various methods on EbeanServer yourself.
Transaction beginTransaction(TxIsolation isolation)
Transaction beginTransaction(TxScope scope)
Note that this provides an try finally alternative to using execute(TxScope, TxCallable) or
execute(TxScope, TxRunnable).
// Start a new transaction. If there is a current transaction
// suspend it until this transaction ends
Transaction txn = server.beginTransaction(TxScope.requiresNew());
try {
...
// commit the transaction
txn.commit();
} finally {
// end this transaction which:
// A) will rollback transaction if it has not been committed already
// B) will restore a previously suspended transaction
txn.end();
}
// start a new transaction if there is not a current transaction
Transaction txn = server.beginTransaction(TxScope.required());
try {
...
// commit the transaction if it was created or
// do nothing if there was already a current transaction
txn.commit();
} finally {
// end this transaction which will rollback the transaction
// if it was created for this try finally scope and has not
// already been committed
txn.end();
}
Transaction currentTransaction()
void commitTransaction()
void rollbackTransaction()
void endTransaction()
Useful to put in a finally block to ensure the transaction is ended, rather than a rollbackTransaction() in each catch block.
Code example:
ebeanServer.beginTransaction();
try {
// do some fetching and or persisting ...
// commit at the end
ebeanServer.commitTransaction();
} finally {
// if commit didn't occur then rollback the transaction
ebeanServer.endTransaction();
}
void refresh(Object bean)
Note that this resets OneToMany and ManyToMany properties so that if they are accessed a lazy load will refresh the many property.
void refreshMany(Object bean, String propertyName)
bean - the entity bean containing the 'many' propertypropertyName - the 'many' property to be refreshed<T> T find(Class<T> beanType, Object id)
// Fetch order 1
Order order = ebeanServer.find(Order.class, 1);
If you want more control over the query then you can use createQuery() and Query.findUnique();
// ... 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 = ebeanServer.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.findUnique();
// 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();
beanType - the type of entity bean to fetchid - the id value<T> T getReference(Class<T> beanType, Object id)
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 = ebeanServer.getReference(Product.class, 1);
OrderDetail orderDetail = new OrderDetail();
// set the product 'foreign key'
orderDetail.setProduct(product);
orderDetail.setQuantity(42);
...
ebeanServer.save(orderDetail);
Product product = ebeanServer.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();
beanType - the type of entity beanid - the id value<T> int findRowCount(Query<T> query, Transaction transaction)
Query.findRowCount(),
Query.findFutureRowCount()<T> List<Object> findIds(Query<T> query, Transaction transaction)
Query.findIds()<T> QueryIterator<T> findIterate(Query<T> query, Transaction transaction)
Generally using findEach(Query, QueryEachConsumer, Transaction) or
findEachWhile(Query, QueryEachWhileConsumer, 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.
<T> void findEach(Query<T> query, QueryEachConsumer<T> consumer, Transaction transaction)
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).
ebeanServer.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);
});
<T> void findEachWhile(Query<T> query, QueryEachWhileConsumer<T> consumer, Transaction transaction)
Compared to findEach() this provides the ability to stop processing the query results early by returning false for the QueryEachWhileConsumer.
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).
ebeanServer.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;
});
<T> List<Version<T>> findVersions(Query<T> query, Transaction transaction)
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.
<T> List<T> findList(Query<T> query, Transaction transaction)
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 =
ebeanServer.find(Customer.class)
.where().ilike("name", "rob%")
.findList();
T - the type of entity bean to fetch.query - the query to execute.transaction - the transaction to use (can be null).Query.findList()<T> FutureRowCount<T> findFutureRowCount(Query<T> query, Transaction transaction)
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).
query - the query to execute the row count ontransaction - the transaction (can be null).Query.findFutureRowCount()<T> FutureIds<T> findFutureIds(Query<T> query, Transaction transaction)
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).
query - the query to execute the fetch Id's ontransaction - the transaction (can be null).Query.findFutureIds()<T> FutureList<T> findFutureList(Query<T> query, Transaction transaction)
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.
query - the query to execute in the backgroundtransaction - the transaction (can be null).Query.findFutureList()SqlFutureList findFutureList(SqlQuery query, Transaction transaction)
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).
query - the query to execute in the backgroundtransaction - the transaction (can be null).<T> PagedList<T> findPagedList(Query<T> query, Transaction transaction, int pageIndex, int pageSize)
The benefit of using this over just using the normal Query.setFirstRow(int) and
Query.setMaxRows(int) is that it additionally wraps an optional call to
Query.findFutureRowCount() to determine total row count, total page count etc.
Internally this works using Query.setFirstRow(int) and Query.setMaxRows(int) on
the query. This translates into SQL that uses limit offset, rownum or row_number
function to limit the result set.
pageIndex - The zero based index of the page.pageSize - The number of beans to return per page.Query.findPagedList(int, int)<T> PagedList<T> findPagedList(Query<T> query, Transaction transaction)
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 = Ebean.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();
Query.findPagedList()<T> Set<T> findSet(Query<T> query, Transaction transaction)
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 =
ebeanServer.find(Customer.class)
.where().ilike("name", "rob%")
.findSet();
T - the type of entity bean to fetch.query - the query to executetransaction - the transaction to use (can be null).Query.findSet()<T> Map<?,T> findMap(Query<T> query, Transaction transaction)
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.
T - the type of entity bean to fetch.query - the query to execute.transaction - the transaction to use (can be null).Query.findMap()@Nullable <T> T findUnique(Query<T> query, Transaction transaction)
This will throw a NonUniqueResultException if the query finds more than one result.
Generally you are able to use Query.findUnique() rather than
explicitly calling this method. You could use this method if you wish to
explicitly control the transaction used for the query.
T - the type of entity bean to fetch.query - the query to execute.transaction - the transaction to use (can be null).javax.persistence.NonUniqueResultException - if more than one result was foundQuery.findUnique()<T> int delete(Query<T> query, Transaction transaction)
Note that if the query includes joins then the generated delete statement may not be optimal depending on the database platform.
T - the type of entity bean to fetch.query - the query used for the deletetransaction - the transaction to use (can be null)List<SqlRow> findList(SqlQuery query, Transaction transaction)
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.
query - the query to execute.transaction - the transaction to use (can be null).SqlQuery.findList()Set<SqlRow> findSet(SqlQuery query, Transaction transaction)
Generally you are able to use SqlQuery.findSet() rather than
explicitly calling this method. You could use this method if you wish to
explicitly control the transaction used for the query.
query - the query to execute.transaction - the transaction to use (can be null).SqlQuery.findSet()Map<?,SqlRow> findMap(SqlQuery query, Transaction transaction)
Generally you are able to use SqlQuery.findMap() rather than
explicitly calling this method. You could use this method if you wish to
explicitly control the transaction used for the query.
query - the query to execute.transaction - the transaction to use (can be null).SqlQuery.findMap()@Nullable SqlRow findUnique(SqlQuery query, Transaction transaction)
This will throw a PersistenceException if the query found more than one result.
Generally you are able to use SqlQuery.findUnique() rather than
explicitly calling this method. You could use this method if you wish to
explicitly control the transaction used for the query.
query - the query to execute.transaction - the transaction to use (can be null).SqlQuery.findUnique()void save(Object bean) throws javax.persistence.OptimisticLockException
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.
javax.persistence.OptimisticLockExceptionint saveAll(Collection<?> beans) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionboolean delete(Object bean) throws javax.persistence.OptimisticLockException
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.
javax.persistence.OptimisticLockExceptionboolean delete(Object bean, Transaction transaction) throws javax.persistence.OptimisticLockException
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.
javax.persistence.OptimisticLockExceptionboolean deletePermanent(Object bean) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionboolean deletePermanent(Object bean, Transaction transaction) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionint deleteAllPermanent(Collection<?> beans) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionint deleteAllPermanent(Collection<?> beans, Transaction transaction) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionint delete(Class<?> beanType, Object id, Transaction transaction)
int deleteAll(Collection<?> beans) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionint deleteAll(Collection<?> beans, Transaction transaction) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionvoid deleteAll(Class<?> beanType, Collection<?> ids)
void deleteAll(Class<?> beanType, Collection<?> ids, Transaction transaction)
int execute(SqlUpdate sqlUpdate)
If you wish to execute a Sql Select natively then you should use the FindByNativeSql object.
Note that the table modification information is automatically deduced and you do not need to call the Ebean.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 = ebeanServer.createSqlUpdate(s);
update.setParameter("id", 1);
update.setParameter("count", 50);
int modifiedCount = ebeanServer.execute(update);
String msg = "There where " + modifiedCount + "rows updated";
sqlUpdate - the update sql potentially with bind valuesCallableSqlint execute(Update<?> update)
This returns the number of rows that where inserted, updated or deleted.
int execute(Update<?> update, Transaction transaction)
int execute(CallableSql callableSql)
Example:
String sql = "{call sp_order_modify(?,?,?)}";
CallableSql cs = ebeanServer.createCallableSql(sql);
cs.setParameter(1, 27);
cs.setParameter(2, "SHIPPED");
cs.registerOut(3, Types.INTEGER);
ebeanServer.execute(cs);
// read the out parameter
Integer returnValue = (Integer) cs.getObject(3);
CallableSql,
Ebean.execute(SqlUpdate)void externalModification(String tableName, boolean inserted, boolean updated, boolean deleted)
If you use ebeanServer.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).
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<T> T find(Class<T> beanType, Object id, Transaction transaction)
T - the type of entity bean to findbeanType - the type of entity bean to findid - the bean id valuetransaction - the transaction to use (can be null)void save(Object bean, Transaction transaction) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionint saveAll(Collection<?> beans, Transaction transaction) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionvoid markAsDirty(Object bean)
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 = ebeanServer.find(Customer, id);
// mark the bean as dirty so that a save() or update() will
// increment the version property
ebeanServer.markAsDirty(customer);
ebeanServer.save(customer);
void update(Object bean) throws javax.persistence.OptimisticLockException
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).
ServerConfig.setUpdatesDeleteMissingChildren(boolean): When cascade saving to a
OneToMany or ManyToMany the updatesDeleteMissingChildren setting controls if any other children
that are in the database but are not in the collection are deleted.
ServerConfig.setUpdateChangesOnly(boolean): The updateChangesOnly setting
controls if only the changed properties are included in the update or if all the loaded
properties are included instead.
// A 'stateless update' example
Customer customer = new Customer();
customer.setId(7);
customer.setName("ModifiedNameNoOCC");
ebeanServer.update(customer);
javax.persistence.OptimisticLockExceptionServerConfig.setUpdatesDeleteMissingChildren(boolean),
ServerConfig.setUpdateChangesOnly(boolean)void update(Object bean, Transaction transaction) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionvoid update(Object bean, Transaction transaction, boolean deleteMissingChildren) throws javax.persistence.OptimisticLockException
bean - the bean to updatetransaction - the transaction to use (can be null).deleteMissingChildren - specify false if you do not want 'missing children' of a OneToMany
or ManyToMany to be automatically deleted.javax.persistence.OptimisticLockExceptionvoid updateAll(Collection<?> beans) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionvoid updateAll(Collection<?> beans, Transaction transaction) throws javax.persistence.OptimisticLockException
javax.persistence.OptimisticLockExceptionvoid insert(Object 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).
void insert(Object bean, Transaction transaction)
void insertAll(Collection<?> beans)
void insertAll(Collection<?> beans, Transaction transaction)
int deleteManyToManyAssociations(Object ownerBean, String propertyName)
Typically these deletions occur automatically when persisting a ManyToMany collection and this provides a way to invoke those deletions directly.
int deleteManyToManyAssociations(Object ownerBean, String propertyName, Transaction transaction)
Additionally specify a transaction to use.
Typically these deletions occur automatically when persisting a ManyToMany collection and this provides a way to invoke those deletions directly.
void saveManyToManyAssociations(Object ownerBean, String propertyName)
Typically the saving of these associations (inserting into the intersection table) occurs automatically when persisting a ManyToMany. This provides a way to invoke those insertions directly.
void saveManyToManyAssociations(Object ownerBean, String propertyName, Transaction transaction)
Typically the saving of these associations (inserting into the intersection table) occurs automatically when persisting a ManyToMany. This provides a way to invoke those insertions directly.
void saveAssociation(Object ownerBean, String propertyName)
This is similar to performing a save cascade on a specific property manually.
Note that you can turn on/off cascading for a transaction via
Transaction.setPersistCascade(boolean)
ownerBean - the bean instance holding the property we want to savepropertyName - the property we want to savevoid saveAssociation(Object ownerBean, String propertyName, Transaction transaction)
This is similar to performing a save cascade on a specific property manually.
Note that you can turn on/off cascading for a transaction via
Transaction.setPersistCascade(boolean)
ownerBean - the bean instance holding the property we want to savepropertyName - the property we want to saveint execute(SqlUpdate updSql, Transaction transaction)
int execute(CallableSql callableSql, Transaction transaction)
void execute(TxScope scope, TxRunnable runnable)
The scope can control the transaction type, isolation and rollback semantics.
// set specific transactional scope settings
TxScope scope = TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE);
ebeanServer.execute(scope, new TxRunnable() {
public void run() {
User u1 = Ebean.find(User.class, 1);
...
}
});
void execute(TxRunnable runnable)
The default scope runs with REQUIRED and by default will rollback on any exception (checked or runtime).
ebeanServer.execute(new TxRunnable() {
public void run() {
User u1 = ebeanServer.find(User.class, 1);
User u2 = ebeanServer.find(User.class, 2);
u1.setName("u1 mod");
u2.setName("u2 mod");
ebeanServer.save(u1);
ebeanServer.save(u2);
}
});
<T> T execute(TxScope scope, TxCallable<T> callable)
The scope can control the transaction type, isolation and rollback semantics.
// set specific transactional scope settings
TxScope scope = TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE);
ebeanServer.execute(scope, new TxCallable<String>() {
public String call() {
User u1 = ebeanServer.find(User.class, 1);
...
return u1.getEmail();
}
});
<T> T execute(TxCallable<T> callable)
The default scope runs with REQUIRED and by default will rollback on any exception (checked or runtime).
This is basically the same as TxRunnable except that it returns an Object (and you specify the return type via generics).
ebeanServer.execute(new TxCallable<String>() {
public String call() {
User u1 = ebeanServer.find(User.class, 1);
User u2 = ebeanServer.find(User.class, 2);
u1.setName("u1 mod");
u2.setName("u2 mod");
ebeanServer.save(u1);
ebeanServer.save(u2);
return u1.getEmail();
}
});
ServerCacheManager getServerCacheManager()
BackgroundExecutor getBackgroundExecutor()
void runCacheWarming()
A cache warming query can be defined via CacheStrategy.
void runCacheWarming(Class<?> beanType)
A cache warming query can be defined via CacheStrategy.
JsonContext json()
This instance is safe to be used concurrently by multiple threads and this method is cheap to call.
JsonContext json = ebeanServer.json();
String jsonOutput = json.toJson(list);
System.out.println(jsonOutput);
// specify just the properties we want
PathProperties paths = PathProperties.parse("name, status, anniversary");
List<Customer> customers =
ebeanServer.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 = ebeanServer.json();
String json = jsonContext.toJson(customers, paths);
<T> T publish(Class<T> beanType, Object id, Transaction transaction)
The values are published from the draft to the live bean.
T - the type of the entity beanbeanType - the type of the entity beanid - the id of the entity beantransaction - the transaction the publish process should use (can be null)<T> T publish(Class<T> beanType, Object id)
The values are published from the draft to the live bean.
T - the type of the entity beanbeanType - the type of the entity beanid - the id of the entity bean<T> List<T> publish(Query<T> query, Transaction transaction)
The values are published from the draft beans to the live beans.
T - the type of the entity beanquery - the query used to select the draft beans to publishtransaction - the transaction the publish process should use (can be null)<T> List<T> publish(Query<T> query)
The values are published from the draft beans to the live beans.
T - the type of the entity beanquery - the query used to select the draft beans to publish<T> T draftRestore(Class<T> beanType, Object id, Transaction transaction)
The values from the live beans are set back to the draft bean and the
@DraftDirty and @DraftReset properties are reset.
T - the type of the entity beanbeanType - the type of the entity beanid - the id of the entity bean to restoretransaction - the transaction the restore process should use (can be null)<T> T draftRestore(Class<T> beanType, Object id)
The values from the live beans are set back to the draft bean and the
@DraftDirty and @DraftReset properties are reset.
T - the type of the entity beanbeanType - the type of the entity beanid - the id of the entity bean to restore<T> List<T> draftRestore(Query<T> query, Transaction transaction)
The values from the live beans are set back to the draft bean and the
@DraftDirty and @DraftReset properties are reset.
T - the type of the entity beanquery - the query used to select the draft beans to restoretransaction - the transaction the restore process should use (can be null)<T> List<T> draftRestore(Query<T> query)
The values from the live beans are set back to the draft bean and the
@DraftDirty and @DraftReset properties are reset.
T - the type of the entity beanquery - the query used to select the draft beans to restore<T> Set<String> validateQuery(Query<T> query)
Validate the query checking the where and orderBy expression paths to confirm if they represent valid properties/path for the given bean type.
Copyright © 2016. All rights reserved.