Skip to content Skip to sidebar Skip to footer

Ebean Rollback and Save Again Dropped



com.avaje.ebean
Class Ebean

java.lang.Object        extended by         com.avaje.ebean.Ebean      

public last class            Ebean            
extends Object

This Ebean object is effectively a singleton that holds a map of registered EbeanServers. It additionally provides a convenient way to use the 'default/primary' EbeanServer.

If you lot are using a Dependency Injection framework such as Spring or Guice you volition probably Not apply this Ebean singleton object. Instead you lot will configure and construct EbeanServer instances using ServerConfig and EbeanServerFactory and inject those EbeanServer instances into your data access objects.

In documentation "Ebean singleton" refers to this object.

  • There is one EbeanServer per Database (javax.sql.DataSource).
  • EbeanServers tin be 'registered' with the Ebean singleton (put into its map). Registered EbeanServer'south tin can afterwards be retrieved via getServer(Cord).
  • One EbeanServer can exist referred to every bit the 'default' EbeanServer. For convenience, the Ebean singleton (this object) provides methods such as find(Grade) that proxy through to the 'default' EbeanServer. This can be useful for applications that use a single database.

For programmer convenience Ebean has static methods that proxy through to the methods on the 'default' EbeanServer. These methods are provided for developers who are mostly using a single database. Many developers volition be able to utilise the methods on Ebean rather than get a EbeanServer.

EbeanServers can be created and used without ever needing or using the Ebean singleton. Refer to ServerConfig.setRegister(boolean).

You can either programmatically create/annals EbeanServers via EbeanServerFactory or they can automatically exist created and registered when you offset use the Ebean singleton. When EbeanServers are created automatically they are configured using data in the ebean.properties file.

        // fetch shipped orders (and also their customer)  List<Order> list = Ebean.notice(Order.class)         .fetch("client")         .where()          .eq("status.code", Guild.Condition.SHIPPED)          .findList();    // read/use the society list ...   for (Order society : list) {          Customer customer = order.getCustomer();          ...   }      
        // fetch order 10, modify and save   Order order = Ebean.notice(Order.course, x);    OrderStatus shipped = Ebean.getReference(OrderStatus.class,"SHIPPED");   order.setStatus(shipped);  order.setShippedDate(shippedDate);   ...    // implicitly creates a transaction and commits   Ebean.relieve(club);      

When you lot have multiple databases and demand access to a specific one the getServer(String) method provides admission to the EbeanServer for that specific database.

        // Get access to the Human Resources EbeanServer/Database  EbeanServer hrDb = Ebean.getServer("hr");      // fetch contact three from the Hour database   Contact contact = hrDb.find(Contact.class, 3);    contact.setName("I'm going to change");   ...    // relieve the contact back to the Hr database   hrDb.save(contact);      
Version:
2.5

Method Summary
static Transaction beginTransaction()
Get-go a new explicit transaction.
static Transaction beginTransaction(TxIsolation isolation)
Kickoff a transaction additionally specifying the isolation level.
static void commitTransaction()
Commit the current transaction.
static CallableSql createCallableSql(String sql)
Create a CallableSql to execute a given stored process.
static

<T> CsvReader<T>

createCsvReader(Class<T> beanType)
Create a CsvReader for a given beanType.
static JsonContext createJsonContext()
Create a JsonContext that volition utilise the default configuration options.
static

<T> Query<T>

createNamedQuery(Class<T> beanType, Cord namedQuery)
Render a named Query that will take divers fetch paths, predicates etc.
static SqlQuery createNamedSqlQuery(Cord namedQuery)
Create a named sql query.
static SqlUpdate createNamedSqlUpdate(String namedQuery)
Create a named sql update.
static

<T> Update<T>

createNamedUpdate(Grade<T> beanType, String namedUpdate)
Create a named orm update.
static

<T> Query<T>

createQuery(Course<T> beanType)
Create a query for a type of entity bean.
static

<T> Query<T>

createQuery(Grade<T> beanType, String query)
Create a query using the query linguistic communication.
static SqlQuery createSqlQuery(String sql)
Create a SqlQuery for executing native sql query statements.
static SqlUpdate createSqlUpdate(Cord sql)
Create a sql update for executing native dml statements.
static

<T> Update<T>

createUpdate(Form<T> beanType, String ormUpdate)
Create a orm update where y'all will supply the insert/update or delete argument (rather than using a named one that is already defined using the @NamedUpdates notation).
static Transaction currentTransaction()
Returns the current transaction or null if there is no current transaction in scope.
static void delete(Grade<?> beanType, Collection<?> ids)
Delete several beans given their type and id values.
static int delete(Grade<?> beanType, Object id)
Delete the bean given its type and id.
static int delete(Collection<?> c)
Delete all the beans from a Collection.
static int delete(Iterator<?> it)
Delete all the beans from an Iterator.
static void delete(Object edible bean)
Delete the edible bean.
static int deleteManyToManyAssociations(Object ownerBean, String propertyName)
Delete the associations (from the intersection tabular array) of a ManyToMany given the owner bean and the propertyName of the ManyToMany drove.
static Map<String,ValuePair> unequal(Object a, Object b)
Render a map of the differences between two objects of the same type.
static void endTransaction()
If the electric current transaction has already been committed practice null otherwise rollback the transaction.
static int execute(CallableSql callableSql)
For making calls to stored procedures.
static int execute(SqlUpdate sqlUpdate)
Execute a Sql Update Delete or Insert argument.
static

<T> T

execute(TxCallable<T> c)
Execute a TxCallable in a Transaction with the default scope.
static void execute(TxRunnable r)
Execute a TxRunnable in a Transaction with the default scope.
static

<T> T

execute(TxScope scope, TxCallable<T> c)
Execute a TxCallable in a Transaction with an explicit telescopic.
static void execute(TxScope scope, TxRunnable r)
Execute a TxRunnable in a Transaction with an explicit scope.
static void externalModification(Cord tableName, boolean inserts, boolean updates, boolean deletes)
Inform Ebean that tables have been modified externally.
static

<T> Filter<T>

filter(Class<T> beanType)
Create a filter for sorting and filtering lists of entities locally without going back to the database.
static

<T> Query<T>

find(Class<T> beanType)
Create a query for a type of entity bean.
static

<T> T

find(Form<T> beanType, Object id)
Find a bean using its unique id.
static BackgroundExecutor getBackgroundExecutor()
Render the BackgroundExecutor service for asynchronous processing of queries.
static BeanState getBeanState(Object bean)
Render the BeanState for a given entity bean.
static ExpressionFactory getExpressionFactory()
Return the ExpressionFactory from the default server.
static

<T> T

getReference(Class<T> beanType, Object id)
Get a reference object.
static EbeanServer getServer(String proper noun)
Get the EbeanServer for a given DataSource.
static ServerCacheManager getServerCacheManager()
Return the manager of the server enshroud ("L2" cache).
static void logComment(Cord msg)
Log a annotate to the transaction log of the current transaction.
static Object nextId(Grade<?> beanType)
Render the next identity value for a given bean type.
static void refresh(Object bean)
Refresh the values of a bean.
static void refreshMany(Object bean, String manyPropertyName)
Refresh a 'many' holding of a bean.
static void rollbackTransaction()
Rollback the current transaction.
static void runCacheWarming()
Run the cache warming queries on all bean types that take i defined for the default/primary EbeanServer.
static void runCacheWarming(Course<?> beanType)
Run the cache warming query for a specific edible bean blazon for the default/primary EbeanServer.
static int save(Collection<?> c)
Salve all the beans from a Collection.
static int save(Iterator<?> iterator)
Salvage all the beans from an Iterator.
static void save(Object bean)
Either Insert or Update the bean depending on its state.
static void saveAssociation(Object ownerBean, Cord propertyName)
Save the associated collection or edible bean given the property proper name.
static void saveManyToManyAssociations(Object ownerBean, Cord propertyName)
Save the associations of a ManyToMany given the owner bean and the propertyName of the ManyToMany drove.
static

<T> void

sort(List<T> list, String sortByClause)
Sort the listing using the sortByClause which can contain a comma delimited listing of property names and keywords asc, desc, nullsHigh and nullsLow.
static void update(Object bean)
Strength an update using the bean updating the not-cipher properties.
static void update(Object bean, Gear up<Cord> updateProps)
Force an update using the bean explicitly stating the properties to update.
static InvalidValue validate(Object edible bean)
Validate a bean.
static InvalidValue[] validate(Object bean, String propertyName, Object value)
Validate a bean property.
Methods inherited from grade java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, look, wait
Method Particular

getServer

public static EbeanServer        getServer(Cord name)
Get the EbeanServer for a given DataSource. If name is null this will return the 'default' EbeanServer.

This is provided to access EbeanServer for databases other than the 'default' database. EbeanServer also provides more command over transactions and the ability to use transactions created externally to Ebean.

            // employ the "hr" database   EbeanServer hrDatabase = Ebean.getServer("hour");    Person person = hrDatabase.detect(Person.class, ten);          
Parameters:
name - the name of the server, apply nothing for the 'default server'

getExpressionFactory

public static ExpressionFactory        getExpressionFactory()
Return the ExpressionFactory from the default server.

The ExpressionFactory is used internally by the query and ExpressionList to build the WHERE and HAVING clauses. Alternatively you tin can use the ExpressionFactory direct to create expressions to add together to the query where clause.

Alternatively y'all can use the Expr as a shortcut to the ExpressionFactory of the 'Default' EbeanServer.

You by and large need to the an ExpressionFactory (or Expr) to build an expression that uses OR like Expression e = Expr.or(..., ...);


nextId

public static Object        nextId(Class<?> beanType)
Return the next identity value for a given bean type.

This volition simply work when a IdGenerator is on this edible bean type such as a DB sequence or UUID.

For DB's supporting getGeneratedKeys and sequences such every bit Oracle10 you do not need to utilise this method mostly. It is made available for more than complex cases where it is useful to go an ID prior to some processing.


logComment

public static void        logComment(String msg)
Log a comment to the transaction log of the current transaction.

beginTransaction

public static Transaction        beginTransaction()
Start a new explicit transaction.

The transaction is stored in a ThreadLocal variable and typically you merely demand to employ the returned Transaction IF you wish to exercise things like use batch mode, alter the transaction isolation level, utilise savepoints or log comments to the transaction log.

Instance of using a transaction to bridge multiple calls to find(), save() etc.

            // start a transaction (stored in a ThreadLocal)  Ebean.beginTransaction();   endeavor {          Order lodge = Ebean.find(Order.class,x); ...           Ebean.salve(order);           Ebean.commitTransaction();    } finally {          // rollback if we didn't commit          // i.e. an exception occurred before commitTransaction().          Ebean.endTransaction();   }          

If y'all want to externalise the transaction management so yous should be able to do this via EbeanServer. Specifically with EbeanServer you tin can pass the transaction to the various find() and save() execute() methods. This gives you the ability to create the transactions yourself externally from Ebean and pass those transactions through to the various methods available on EbeanServer.


beginTransaction

public static Transaction        beginTransaction(TxIsolation isolation)
Get-go a transaction additionally specifying the isolation level.
Parameters:
isolation - the Transaction isolation level

currentTransaction

public static Transaction        currentTransaction()
Returns the electric current transaction or nil if there is no current transaction in scope.

commitTransaction

public static void        commitTransaction()
Commit the current transaction.

rollbackTransaction

public static void        rollbackTransaction()
Rollback the current transaction.

endTransaction

public static void        endTransaction()
If the current transaction has already been committed exercise 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:

            Ebean.beginTransaction();  try {      // practise some fetching and or persisting      // commit at the terminate Ebean.commitTransaction();    } finally {      // if commit didn't occur then rollback the transaction      Ebean.endTransaction();  }          

validate

public static InvalidValue        validate(Object bean)
Validate a bean.

This will validate all of the properties on the bean in a recursive fashion. Typically if cascade salve or delete is on then the validation volition cascade those same associations.

If no errors are detected then this returns null. Otherwise the returned InvalidValue holds the errors from all the rules tested. Use InvalidValue.getErrors() to get the list of errors that occurred.

Returns:
a InvalidValue holding the errors or null

validate

public static InvalidValue[]        validate(Object bean,                                       String propertyName,                                       Object value)
Validate a edible bean property.

If value passed in is nix, then the belongings value from the bean is used.

If no errors are detected an empty array is returned.

Parameters:
bean - the edible bean used if value is null
propertyName - the property to validate
value - the value to validate. If this is null then the value from the bean is used to validate.
Returns:
a InvalidValue holding the errors for this belongings (returns an empty array if in that location are no errors).

unequal

public static Map<String,ValuePair>        diff(Object a,                                          Object b)
Return a map of the differences between two objects of the aforementioned type.

When null is passed in for b, and so the 'OldValues' of a is used for the difference comparison.


save

public static void        salve(Object bean)                  throws javax.persistence.OptimisticLockException
Either Insert or Update the bean depending on its state.

If there is no electric current transaction ane will exist created and committed for yous automatically.

Save can cascade along relationships. For this to happen you demand to specify a cascade of CascadeType.ALL or CascadeType.PERSIST on the OneToMany, OneToOne or ManyToMany annotation.

In this instance below the details holding has a CascadeType.ALL set so saving an social club volition also save all its details.

            public course Gild { ...                  @OneToMany(pour=CascadeType.ALL, mappedBy="order")         @JoinColumn(name="order_id")          Listing<OrderDetail> details;          ...   }          

When a relieve cascades via a OneToMany or ManyToMany Ebean will automatically set the 'parent' object to the 'item' object. In the example beneath in saving the order and pour saving the order details the 'parent' order will be set confronting each order particular when it is saved.

Throws:
javax.persistence.OptimisticLockException

update

public static void        update(Object bean)
Forcefulness an update using the bean updating the non-null properties.

You can employ this method to FORCE an update to occur. When save(Object) is used Ebean determines whether to use an insert or an update based on the land of the bean. Using this method will force an update to occur.

Information technology is expected that this method is most useful in stateless web applications where you have the values you wish to update but no existing edible bean.

            Customer c = new Customer();  c.setId(vii);  c.setName("ModifiedNameNoOCC");    // generally you should set the version belongings   // so that Optimistic Concurrency Checking is used.  // If a version holding is not prepare then no Optimistic  // Concurrency Checking occurs for the update  //c.setLastUpdate(lastUpdateTime);    // past default the Non-null properties   // are included in the update  Ebean.update(c);          

update

public static void        update(Object bean,                           Set<String> updateProps)
Force an update using the bean explicitly stating the properties to update.

If you don't specify explicit backdrop to employ in the update then the not-null properties are included in the update.

Parameters:
bean - The bean holding the values to be included in the update.
updateProps - the explicit set of properties to include in the update.

save

public static int        save(Iterator<?> iterator)                 throws javax.persistence.OptimisticLockException
Save all the beans from an Iterator.
Throws:
javax.persistence.OptimisticLockException

save

public static int        save(Collection<?> c)                 throws javax.persistence.OptimisticLockException
Save all the beans from a Collection.
Throws:
javax.persistence.OptimisticLockException

deleteManyToManyAssociations

public static 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 drove.

Typically these deletions occur automatically when persisting a ManyToMany drove and this provides a mode to invoke those deletions straight.

Returns:
the number of associations deleted (from the intersection table).

saveManyToManyAssociations

public static void        saveManyToManyAssociations(Object ownerBean,                                               String propertyName)
Salvage the associations of a ManyToMany given the owner bean and the propertyName of the ManyToMany collection.

Typically the saving of these associations (inserting into the intersection tabular array) occurs automatically when persisting a ManyToMany. This provides a fashion to invoke those insertions directly.

You can use this when the collection is new and in this case all the entries in the collection are treated as additions are effect in inserts into the intersection tabular array.


saveAssociation

public static void        saveAssociation(Object ownerBean,                                    String propertyName)
Salvage the associated collection or bean given the belongings name.

This is similar to performing a salvage pour on a specific property manually/programmatically.

Annotation that you tin can plough on/off cascading for a transaction via Transaction.setPersistCascade(boolean)

Parameters:
ownerBean - the edible bean example holding the property nosotros want to salve
propertyName - the property nosotros want to save

delete

public static void        delete(Object bean)                    throws javax.persistence.OptimisticLockException
Delete the bean.

If there is no current transaction one volition be created and committed for you lot automatically.

Throws:
javax.persistence.OptimisticLockException

delete

public static int        delete(Class<?> beanType,                          Object id)
Delete the edible bean given its blazon and id.

delete

public static void        delete(Class<?> beanType,                           Collection<?> ids)
Delete several beans given their blazon and id values.

delete

public static int        delete(Iterator<?> it)                   throws javax.persistence.OptimisticLockException
Delete all the beans from an Iterator.
Throws:
javax.persistence.OptimisticLockException

delete

public static int        delete(Drove<?> c)                   throws javax.persistence.OptimisticLockException
Delete all the beans from a Collection.
Throws:
javax.persistence.OptimisticLockException

refresh

public static void        refresh(Object bean)
Refresh the values of a bean.

Note that this does non refresh any OneToMany or ManyToMany properties.


refreshMany

public static void        refreshMany(Object edible bean,                                Cord manyPropertyName)
Refresh a 'many' property of a edible bean.
            Society order = ...;  ...  // refresh the order details...  Ebean.refreshMany(order, "details");          
Parameters:
bean - the entity bean containing the Listing Set or Map to refresh.
manyPropertyName - the belongings name of the List Set or Map to refresh.

getReference

public static <T> T        getReference(Form<T> beanType,                                  Object id)
Get a reference object.

This is sometimes described as a proxy (with lazy loading).

            Production product = Ebean.getReference(Product.form, i);    // Y'all can go the id without causing a fetch/lazy load   Integer productId = product.getId();    // If yous try to get whatever 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 edible bean
id - the id value

sort

public static <T> void        sort(List<T> list,                             Cord sortByClause)
Sort the list using the sortByClause which can contain a comma delimited listing 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 minor values

If you go out off any keywords the defaults are ascending order and treating nulls every bit high values.

Note that the sorting uses a Comparator and Collections.sort(); and does non invoke a DB query.

            // find orders and their customers   List<Order> list = Ebean.find(Club.class)   .fetch("client")   .orderBy("id")   .findList();    // sort by client proper noun ascending, then by order shipDate   // ... then by the society condition descending   Ebean.sort(list, "client.proper name, shipDate, status desc");    // sort by customer proper name descending (with nulls low)   // ... then by the order id   Ebean.sort(list, "customer.name desc nullsLow, id");          
Parameters:
list - the list of entity beans
sortByClause - the properties to sort the listing past

find

public static <T> T        notice(Form<T> beanType,                          Object id)
Find a bean using its unique id. This will not use caching.
            // Fetch order ane   Order society = Ebean.find(Order.grade, i);          

If you want more control over the query and then y'all tin can use createQuery() and Query.findUnique();

            // ... additionally fetching customer, customer aircraft accost,   // gild details, and the product associated with each order detail.   // note: just product id and name is fetch (its a "fractional object").   // note: all other objects use "*" and have all their properties fetched.    Query<Order> query = Ebean.createQuery(Order.course);  query.setId(1);  query.fetch("customer");  query.fetch("customer.shippingAddress");  query.fetch("details");    // fetch associated products only only fetch their product id and name  query.fetch("details.product", "name");    // traverse the object graph...    Social club order = query.findUnique();  Customer customer = order.getCustomer();  Address shippingAddress = client.getShippingAddress();  List<OrderDetail> details = guild.getDetails();  OrderDetail detail0 = details.get(0);  Product production = detail0.getProduct();  String productName = product.getName();          
Parameters:
beanType - the type of entity bean to fetch
id - the id value

createSqlQuery

public static SqlQuery        createSqlQuery(Cord sql)
Create a SqlQuery for executing native sql query statements.

Note that yous can apply raw SQL with entity beans, refer to the SqlSelect annotation for examples.


createNamedSqlQuery

public static SqlQuery        createNamedSqlQuery(Cord namedQuery)
Create a named sql query.

The query statement volition exist defined in a deployment orm xml file.

Parameters:
namedQuery - the proper name of the query

createSqlUpdate

public static SqlUpdate        createSqlUpdate(String sql)
Create a sql update for executing native dml statements.

Apply this to execute a Insert Update or Delete statement. The statement volition be native to the database and contain database table and column names.

See SqlUpdate for example usage.

Where possible information technology would be expected practice to put the statement in a orm xml file (named update) and use createNamedSqlUpdate(String) .


createCallableSql

public static CallableSql        createCallableSql(String sql)
Create a CallableSql to execute a given stored procedure.
Run across Also:
CallableSql

createNamedSqlUpdate

public static SqlUpdate        createNamedSqlUpdate(String namedQuery)
Create a named sql update.

The statement (an Insert Update or Delete argument) will be defined in a deployment orm xml file.

            // Use a namedQuery   UpdateSql update = Ebean.createNamedSqlUpdate("update.topic.count");    update.setParameter("count", one);  update.setParameter("topicId", 50);    int modifiedCount = update.execute();          

createNamedQuery

public static <T> Query<T>        createNamedQuery(Class<T> beanType,                                             String namedQuery)
Render a named Query that will accept divers fetch paths, predicates etc.

The query is created from a argument that will exist divers in a deployment orm xml file or NamedQuery annotations. The query volition typically already ascertain fetch paths, predicates, order past clauses etc so ofttimes you will but need to demark required parameters and so execute the query.

            // instance   Query<Order> query = Ebean.createNamedQuery(Guild.grade, "new.for.customer");  query.setParameter("customerId", 23);  List<Social club> newOrders = query.findList();          
Parameters:
beanType - the class of entity to exist fetched
namedQuery - the name of the query

createQuery

public static <T> Query<T>        createQuery(Course<T> beanType,                                        String query)
Create a query using the query language.

Annotation that y'all are allowed to add additional clauses using where() as well as apply 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(Form, String).

            Cord q = "find lodge fetch details where status = :st";      List<Order> newOrders          = Ebean.createQuery(Order.course, q)              .setParameter("st", Order.Condition.NEW)              .findList();          
Parameters:
query - the object query

createNamedUpdate

public static <T> Update<T>        createNamedUpdate(Class<T> beanType,                                               String namedUpdate)
Create a named orm update. The update argument is specified via the NamedUpdate annotation.

The orm update differs from the SqlUpdate in that it uses the bean proper noun and bean property names rather than table and column names.

Note that named update statements can be specified in raw sql (with column and tabular array names) or using bean name and bean holding names. This tin can be specified with the isSql flag.

Example named updates:

            bundle app.data;    import ...    @NamedUpdates(value = {          @NamedUpdate( proper name = "setTitle",                  isSql = false,                  notifyCache = false,                  update = "update topic ready title = :title, postCount = :postCount where id = :id"),          @NamedUpdate( proper name = "setPostCount",                 notifyCache = imitation,                 update = "update f_topic fix post_count = :postCount where id = :id"),          @NamedUpdate( name = "incrementPostCount",                  notifyCache = false,                  isSql = false,                 update = "update Topic ready postCount = postCount + one where id = :id") })   @Entity   @Table(name = "f_topic")   public course Topic { ...          

Instance using a named update:

            Update<Topic> update = Ebean.createNamedUpdate(Topic.class, "setPostCount");  update.setParameter("postCount", 10);  update.setParameter("id", 3);    int rows = update.execute();  System.out.println("rows updated: " + rows);          

createUpdate

public static <T> Update<T>        createUpdate(Class<T> beanType,                                          String ormUpdate)
Create a orm update where you volition supply the insert/update or delete statement (rather than using a named ane that is already defined using the @NamedUpdates annotation).

The orm update differs from the sql update in that it you tin can use the bean name and edible bean property names rather than table and column names.

An instance:

            // The bean proper noun and properties - "topic","postCount" and "id"     // will exist converted into their associated table and cavalcade names   String updStatement = "update topic set postCount = :pc where id = :id";    Update<Topic> update = Ebean.createUpdate(Topic.class, updStatement);    update.fix("pc", 9);  update.set("id", iii);    int rows = update.execute();  Organization.out.println("rows updated:" + rows);          

createCsvReader

public static <T> CsvReader<T>        createCsvReader(Course<T> beanType)
Create a CsvReader for a given beanType.

createQuery

public static <T> Query<T>        createQuery(Class<T> beanType)
Create a query for a type of entity edible bean.

You lot can employ the methods on the Query object to specify fetch paths, predicates, order by, limits etc.

Y'all then utilize findList(), findSet(), findMap() and findUnique() to execute the query and render the collection or bean.

Note that a query executed by Query.findList() Query.findSet() etc will execute against the aforementioned EbeanServer from which is was created.

            // Find order 2 additionally fetching the customer, details and details.product name.    Query<Order> query = Ebean.createQuery(Social club.class);  query.fetch("customer");  query.fetch("details");  query.fetch("particular.production", "name");  query.setId(2);    Society order = query.findUnique();    // Notice guild 2 additionally fetching the customer, details and details.product proper name.   // Note: same query as above but using the query language   // Note: using a named query would be preferred practice    String oql = "find order fetch customer fetch details fetch details.production (name) where id = :orderId ";    Query<Guild> query = Ebean.createQuery(Order.class);  query.setQuery(oql);  query.setParameter("orderId", 2);    Society guild = query.findUnique();    // Using a named query   Query<Order> query = Ebean.createQuery(Society.grade, "with.details");  query.setParameter("orderId", ii);    Order order = query.findUnique();          
Parameters:
beanType - the grade of entity to be fetched
Returns:
A ORM Query object for this beanType

find

public static <T> Query<T>        detect(Course<T> beanType)
Create a query for a blazon of entity bean.

This is really the aforementioned equally createQuery(Course). The reason it exists is that people used to JPA will probably be looking for a createQuery method (the same as entityManager).

Parameters:
beanType - the type of entity edible bean to discover
Returns:
A ORM Query object for this beanType

filter

public static <T> Filter<T>        filter(Grade<T> beanType)
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 practical.

Refer to Filter for an instance of its use.


execute

public static int        execute(SqlUpdate sqlUpdate)
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 and then this returns -i. You can become the actual rowCount after commit() from updateSql.getRowCount().

If you wish to execute a Sql Select natively so you should use the FindByNativeSql object.

Notation that the table modification information is automatically deduced and you do not need to call the Ebean.externalModification() method when you use this method.

Instance:

            // example that uses 'named' parameters   String s = "UPDATE f_topic set up post_count = :count where id = :id"    SqlUpdate update = Ebean.createSqlUpdate(southward);    update.setParameter("id", 1);  update.setParameter("count", fifty);    int modifiedCount = Ebean.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.
Run into Besides:
SqlUpdate, CallableSql, execute(CallableSql)

execute

public static int        execute(CallableSql callableSql)
For making calls to stored procedures.

Example:

            String sql = "{call sp_order_modify(?,?,?)}";    CallableSql cs = Ebean.createCallableSql(sql);  cs.setParameter(1, 27);  cs.setParameter(2, "SHIPPED");  cs.registerOut(3, Types.INTEGER);    Ebean.execute(cs);    // read the out parameter   Integer returnValue = (Integer) cs.getObject(3);          
Run into Also:
CallableSql, execute(SqlUpdate)

execute

public static void        execute(TxScope scope,                            TxRunnable r)
Execute a TxRunnable in a Transaction with an explicit scope.

The scope tin can control the transaction type, isolation and rollback semantics.

            // ready specific transactional scope settings   TxScope scope = TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE);    Ebean.execute(scope, new TxRunnable() {          public void run() {                  User u1 = Ebean.notice(User.form, 1);                  ...           }   });          

execute

public static void        execute(TxRunnable r)
Execute a TxRunnable in a Transaction with the default scope.

The default telescopic runs with REQUIRED and past default will rollback on any exception (checked or runtime).

            Ebean.execute(new TxRunnable() {      public void run() {          User u1 = Ebean.find(User.grade, 1);          User u2 = Ebean.find(User.class, 2);            u1.setName("u1 mod");          u2.setName("u2 mod");            Ebean.relieve(u1);          Ebean.save(u2);      }  });          

execute

public static <T> T        execute(TxScope scope,                             TxCallable<T> c)
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);    Ebean.execute(scope, new TxCallable<Cord>() {         public String call() {                  User u1 = Ebean.observe(User.class, one);                  ...                 return u1.getEmail();          }   });          

execute

public static <T> T        execute(TxCallable<T> c)
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).

This is basically the aforementioned equally TxRunnable except that it returns an Object (and you specify the return type via generics).

            Ebean.execute(new TxCallable<String>() {      public String phone call() {          User u1 = Ebean.find(User.grade, i);          User u2 = Ebean.observe(User.class, 2);            u1.setName("u1 mod");          u2.setName("u2 modernistic");            Ebean.relieve(u1);          Ebean.salvage(u2);            return u1.getEmail();      }  });          

externalModification

public static void        externalModification(String tableName,                                         boolean inserts,                                         boolean updates,                                         boolean deletes)
Inform Ebean that tables have been modified externally. These could be the upshot of from calling a stored procedure, other JDBC calls or external programs including other frameworks.

If you lot utilise Ebean.execute(UpdateSql) then the table modification information is automatically deduced and yous do not need to telephone call this method yourself.

This information is used to invalidate objects out of the cache and potentially the lucene text indexes. This information is also automatically circulate beyond the cluster.

If there is a transaction so this information is placed into the current transactions upshot data. When the transaction is commited this data is registered (with the transaction manager). If this transaction is rolled dorsum then none of the transaction event data registers including the data you put in via this method.

If there is NO current transaction when you telephone call this method then this data is registered immediately (with the transaction director).

Parameters:
tableName - the name of the tabular array that was modified
inserts - truthful if rows where inserted into the tabular array
updates - true if rows on the table where updated
deletes - true if rows on the table where deleted

getBeanState

public static BeanState        getBeanState(Object bean)
Return the BeanState for a given entity bean.

This will return null if the edible bean is not an enhanced (or subclassed) entity bean.


getServerCacheManager

public static ServerCacheManager        getServerCacheManager()
Return the manager of the server enshroud ("L2" cache).

getBackgroundExecutor

public static BackgroundExecutor        getBackgroundExecutor()
Render the BackgroundExecutor service for asynchronous processing of queries.

runCacheWarming

public static void        runCacheWarming()
Run the cache warming queries on all bean types that take one divers for the default/master EbeanServer.

A cache warming query can exist defined via CacheStrategy.


runCacheWarming

public static void        runCacheWarming(Class<?> beanType)
Run the cache warming query for a specific bean type for the default/primary EbeanServer.

A cache warming query can be defined via CacheStrategy.


createJsonContext

public static JsonContext        createJsonContext()
Create a JsonContext that will utilise the default configuration options.


Copyright © 2010. All Rights Reserved.

pospisilpanduch.blogspot.com

Source: https://archive-avaje-org.github.io/static/javadoc/pub/com/avaje/ebean/Ebean.html

Postar um comentário for "Ebean Rollback and Save Again Dropped"