001package io.ebean;
002
003import io.ebean.annotation.TxIsolation;
004import io.ebean.cache.ServerCacheManager;
005import io.ebean.plugin.Property;
006import io.ebean.text.csv.CsvReader;
007import io.ebean.text.json.JsonContext;
008
009import javax.annotation.Nonnull;
010import javax.annotation.Nullable;
011import javax.persistence.OptimisticLockException;
012import javax.persistence.PersistenceException;
013import java.util.Collection;
014import java.util.List;
015import java.util.Map;
016import java.util.Set;
017import java.util.concurrent.Callable;
018
019/**
020 * Deprecated - please migrate to use <code>io.ebean.DB</code>.
021 * <p>
022 * Ebean is a registry of {@link Database} by name. Ebean has now been renamed to {@link DB}.
023 * <p>
024 * Ebean is effectively this is an alias for {@link DB} which is the new and improved name for Ebean.
025 * <p>
026 * The preference is to use DB and Database rather than Ebean and EbeanServer.
027 */
028@Deprecated
029public final class Ebean {
030
031  private static final DbContext context = DbContext.getInstance();
032
033  private Ebean() {
034  }
035
036  /**
037   * Get the Database for a given DataSource. If name is null this will
038   * return the 'default' EbeanServer.
039   * <p>
040   * This is provided to access EbeanServer for databases other than the
041   * 'default' database. EbeanServer also provides more control over
042   * transactions and the ability to use transactions created externally to
043   * Ebean.
044   * </p>
045   * <pre>{@code
046   * // use the "hr" database
047   * EbeanServer hrDatabase = Ebean.getServer("hr");
048   *
049   * Person person = hrDatabase.find(Person.class, 10);
050   * }</pre>
051   *
052   * @param name the name of the server, can use null for the 'default server'
053   */
054  public static EbeanServer getServer(String name) {
055    return (EbeanServer)context.get(name);
056  }
057
058  /**
059   * Returns the default EbeanServer.
060   * <p>
061   * This is equivalent to <code>Ebean.getServer(null);</code>
062   * </p>
063   */
064  public static EbeanServer getDefaultServer() {
065    return (EbeanServer)context.getDefault();
066  }
067
068  /**
069   * Register the server with this Ebean singleton. Specify if the registered
070   * server is the primary/default database.
071   */
072  @Deprecated
073  public static void register(EbeanServer server, boolean defaultServer) {
074    context.register(server, defaultServer);
075  }
076
077  /**
078   * Backdoor for registering a mock implementation of EbeanServer as the default database.
079   */
080  protected static EbeanServer mock(String name, EbeanServer server, boolean defaultServer) {
081    return (EbeanServer)context.mock(name, server, defaultServer);
082  }
083
084  private static Database getDefault() {
085    return context.getDefault();
086  }
087
088  /**
089   * Return the ExpressionFactory from the default database.
090   * <p>
091   * The ExpressionFactory is used internally by the query and ExpressionList to
092   * build the WHERE and HAVING clauses. Alternatively you can use the
093   * ExpressionFactory directly to create expressions to add to the query where
094   * clause.
095   * </p>
096   * <p>
097   * Alternatively you can use the {@link Expr} as a shortcut to the
098   * ExpressionFactory of the 'Default' EbeanServer.
099   * </p>
100   * <p>
101   * You generally need to the an ExpressionFactory (or {@link Expr}) to build
102   * an expression that uses OR like Expression e = Expr.or(..., ...);
103   * </p>
104   */
105  public static ExpressionFactory getExpressionFactory() {
106    return getDefault().getExpressionFactory();
107  }
108
109  /**
110   * Return the next identity value for a given bean type.
111   * <p>
112   * This will only work when a IdGenerator is on this bean type such as a DB
113   * sequence or UUID.
114   * </p>
115   * <p>
116   * For DB's supporting getGeneratedKeys and sequences such as Oracle10 you do
117   * not need to use this method generally. It is made available for more
118   * complex cases where it is useful to get an ID prior to some processing.
119   * </p>
120   */
121  public static Object nextId(Class<?> beanType) {
122    return getDefault().nextId(beanType);
123  }
124
125  /**
126   * Start a transaction with 'REQUIRED' semantics.
127   * <p>
128   * With REQUIRED semantics if an active transaction already exists that transaction will be used.
129   * </p>
130   * <p>
131   * The transaction is stored in a ThreadLocal variable and typically you only
132   * need to use the returned Transaction <em>IF</em> you wish to do things like
133   * use batch mode, change the transaction isolation level, use savepoints or
134   * log comments to the transaction log.
135   * </p>
136   * <p>
137   * Example of using a transaction to span multiple calls to find(), save()
138   * etc.
139   * </p>
140   * <pre>{@code
141   *
142   *   // start a transaction (stored in a ThreadLocal)
143   *   Ebean.beginTransaction();
144   *   try {
145   *       Order order = Ebean.find(Order.class,10); ...
146   *
147   *       Ebean.save(order);
148   *
149   *       Ebean.commitTransaction();
150   *
151   *   } finally {
152   *       // rollback if we didn't commit
153   *       // i.e. an exception occurred before commitTransaction().
154   *       Ebean.endTransaction();
155   *   }
156   *
157   * }</pre>
158   * <p>
159   * If you want to externalise the transaction management then you should be
160   * able to do this via EbeanServer. Specifically with EbeanServer you can pass
161   * the transaction to the various find() and save() execute() methods. This
162   * gives you the ability to create the transactions yourself externally from
163   * Ebean and pass those transactions through to the various methods available
164   * on EbeanServer.
165   * </p>
166   */
167  public static Transaction beginTransaction() {
168    return getDefault().beginTransaction();
169  }
170
171  /**
172   * Start a transaction additionally specifying the isolation level.
173   *
174   * @param isolation the Transaction isolation level
175   */
176  public static Transaction beginTransaction(TxIsolation isolation) {
177    return getDefault().beginTransaction(isolation);
178  }
179
180  /**
181   * Start a transaction typically specifying REQUIRES_NEW or REQUIRED semantics.
182   * <p>
183   * Note that this provides an try finally alternative to using {@link #executeCall(TxScope, Callable)} or
184   * {@link #execute(TxScope, Runnable)}.
185   * </p>
186   * <p>
187   * <h3>REQUIRES_NEW example:</h3>
188   * <pre>{@code
189   * // Start a new transaction. If there is a current transaction
190   * // suspend it until this transaction ends
191   * Transaction txn = Ebean.beginTransaction(TxScope.requiresNew());
192   * try {
193   *
194   *   ...
195   *
196   *   // commit the transaction
197   *   txn.commit();
198   *
199   * } finally {
200   *   // end this transaction which:
201   *   //  A) will rollback transaction if it has not been committed already
202   *   //  B) will restore a previously suspended transaction
203   *   txn.end();
204   * }
205   *
206   * }</pre>
207   * <h3>REQUIRED example:</h3>
208   * <pre>{@code
209   *
210   * // start a new transaction if there is not a current transaction
211   * Transaction txn = Ebean.beginTransaction(TxScope.required());
212   * try {
213   *
214   *   ...
215   *
216   *   // commit the transaction if it was created or
217   *   // do nothing if there was already a current transaction
218   *   txn.commit();
219   *
220   * } finally {
221   *   // end this transaction which will rollback the transaction
222   *   // if it was created for this try finally scope and has not
223   *   // already been committed
224   *   txn.end();
225   * }
226   *
227   * }</pre>
228   */
229  public static Transaction beginTransaction(TxScope scope) {
230    return getDefault().beginTransaction(scope);
231  }
232
233  /**
234   * Returns the current transaction or null if there is no current transaction
235   * in scope.
236   */
237  public static Transaction currentTransaction() {
238    return getDefault().currentTransaction();
239  }
240
241  /**
242   * The batch will be flushing automatically but you can use this to explicitly
243   * flush the batch if you like.
244   * <p>
245   * Flushing occurs automatically when:
246   * </p>
247   * <ul>
248   * <li>the batch size is reached</li>
249   * <li>A query is executed on the same transaction</li>
250   * <li>UpdateSql or CallableSql are mixed with bean save and delete</li>
251   * <li>Transaction commit occurs</li>
252   * <li>A getter method is called on a batched bean</li>
253   * </ul>
254   */
255  public static void flush() {
256    currentTransaction().flush();
257  }
258
259  /**
260   * Register a TransactionCallback on the currently active transaction.
261   * <p/>
262   * If there is no currently active transaction then a PersistenceException is thrown.
263   *
264   * @param transactionCallback the transaction callback to be registered with the current transaction
265   * @throws PersistenceException if there is no currently active transaction
266   */
267  public static void register(TransactionCallback transactionCallback) throws PersistenceException {
268    getDefault().register(transactionCallback);
269  }
270
271  /**
272   * Commit the current transaction.
273   */
274  public static void commitTransaction() {
275    getDefault().commitTransaction();
276  }
277
278  /**
279   * Rollback the current transaction.
280   */
281  public static void rollbackTransaction() {
282    getDefault().rollbackTransaction();
283  }
284
285  /**
286   * If the current transaction has already been committed do nothing otherwise
287   * rollback the transaction.
288   * <p>
289   * Useful to put in a finally block to ensure the transaction is ended, rather
290   * than a rollbackTransaction() in each catch block.
291   * </p>
292   * <p>
293   * Code example:
294   * </p>
295   * <pre>{@code
296   *   Ebean.beginTransaction();
297   *   try {
298   *     // do some fetching and or persisting
299   *
300   *     // commit at the end
301   *     Ebean.commitTransaction();
302   *
303   *   } finally {
304   *     // if commit didn't occur then rollback the transaction
305   *     Ebean.endTransaction();
306   *   }
307   * }</pre>
308   */
309  public static void endTransaction() {
310    getDefault().endTransaction();
311  }
312
313  /**
314   * Mark the current transaction as rollback only.
315   */
316  public static void setRollbackOnly() {
317    getDefault().currentTransaction().setRollbackOnly();
318  }
319
320  /**
321   * Return a map of the differences between two objects of the same type.
322   * <p>
323   * When null is passed in for b, then the 'OldValues' of a is used for the
324   * difference comparison.
325   * </p>
326   */
327  public static Map<String, ValuePair> diff(Object a, Object b) {
328    return getDefault().diff(a, b);
329  }
330
331  /**
332   * Either Insert or Update the bean depending on its state.
333   * <p>
334   * If there is no current transaction one will be created and committed for
335   * you automatically.
336   * </p>
337   * <p>
338   * Save can cascade along relationships. For this to happen you need to
339   * specify a cascade of CascadeType.ALL or CascadeType.PERSIST on the
340   * OneToMany, OneToOne or ManyToMany annotation.
341   * </p>
342   * <p>
343   * In this example below the details property has a CascadeType.ALL set so
344   * saving an order will also save all its details.
345   * </p>
346   * <pre>{@code
347   *   public class Order { ...
348   *
349   *     @OneToMany(cascade=CascadeType.ALL, mappedBy="order")
350   *       List<OrderDetail> details;
351   *       ...
352   *   }
353   * }</pre>
354   * <p>
355   * When a save cascades via a OneToMany or ManyToMany Ebean will automatically
356   * set the 'parent' object to the 'detail' object. In the example below in
357   * saving the order and cascade saving the order details the 'parent' order
358   * will be set against each order detail when it is saved.
359   * </p>
360   */
361  public static void save(Object bean) throws OptimisticLockException {
362    getDefault().save(bean);
363  }
364
365  /**
366   * Insert the bean. This is useful when you set the Id property on a bean and
367   * want to explicitly insert it.
368   */
369  public static void insert(Object bean) {
370    getDefault().insert(bean);
371  }
372
373  /**
374   * Insert a collection of beans.
375   */
376  public static void insertAll(Collection<?> beans) {
377    getDefault().insertAll(beans);
378  }
379
380  /**
381   * Marks the entity bean as dirty.
382   * <p>
383   * This is used so that when a bean that is otherwise unmodified is updated with the version
384   * property updated.
385   * <p>
386   * An unmodified bean that is saved or updated is normally skipped and this marks the bean as
387   * dirty so that it is not skipped.
388   * <pre>{@code
389   *
390   *   Customer customer = Ebean.find(Customer, id);
391   *
392   *   // mark the bean as dirty so that a save() or update() will
393   *   // increment the version property
394   *   Ebean.markAsDirty(customer);
395   *   Ebean.save(customer);
396   *
397   * }</pre>
398   */
399  public static void markAsDirty(Object bean) throws OptimisticLockException {
400    getDefault().markAsDirty(bean);
401  }
402
403  /**
404   * Saves the bean using an update. If you know you are updating a bean then it is preferrable to
405   * use this update() method rather than save().
406   * <p>
407   * <b>Stateless updates:</b> Note that the bean does not have to be previously fetched to call
408   * update().You can create a new instance and set some of its properties programmatically for via
409   * JSON/XML marshalling etc. This is described as a 'stateless update'.
410   * </p>
411   * <p>
412   * <b>Optimistic Locking: </b> Note that if the version property is not set when update() is
413   * called then no optimistic locking is performed (internally ConcurrencyMode.NONE is used).
414   * </p>
415   * <pre>{@code
416   *
417   *   // A 'stateless update' example
418   *   Customer customer = new Customer();
419   *   customer.setId(7);
420   *   customer.setName("ModifiedNameNoOCC");
421   *
422   *   DB.update(customer);
423   *
424   * }</pre>
425   */
426  public static void update(Object bean) throws OptimisticLockException {
427    getDefault().update(bean);
428  }
429
430  /**
431   * Update the beans in the collection.
432   */
433  public static void updateAll(Collection<?> beans) throws OptimisticLockException {
434    getDefault().updateAll(beans);
435  }
436
437  /**
438   * Merge the bean using the default merge options.
439   *
440   * @param bean The bean to merge
441   */
442  public static void merge(Object bean) {
443    getDefault().merge(bean);
444  }
445
446  /**
447   * Merge the bean using the given merge options.
448   *
449   * @param bean    The bean to merge
450   * @param options The options to control the merge
451   */
452  public static void merge(Object bean, MergeOptions options) {
453    getDefault().merge(bean, options);
454  }
455
456  /**
457   * Save all the beans from a Collection.
458   */
459  public static int saveAll(Collection<?> beans) throws OptimisticLockException {
460    return getDefault().saveAll(beans);
461  }
462
463  /**
464   * This method checks the uniqueness of a bean. I.e. if the save will work. It will return the
465   * properties that violates an unique / primary key. This may be done in an UI save action to
466   * validate if the user has entered correct values.
467   * <p>
468   * Note: This method queries the DB for uniqueness of all indices, so do not use it in a batch update.
469   * <p>
470   * Note: This checks only the root bean!
471   * <p>
472   * <pre>{@code
473   *
474   *   // there is a unique constraint on title
475   *
476   *   Document doc = new Document();
477   *   doc.setTitle("One flew over the cuckoo's nest");
478   *   doc.setBody("clashes with doc1");
479   *
480   *   Set<Property> properties = server().checkUniqueness(doc);
481   *
482   *   if (properties.isEmpty()) {
483   *     // it is unique ... carry on
484   *
485   *   } else {
486   *     // build a user friendly message
487   *     // to return message back to user
488   *
489   *     String uniqueProperties = properties.toString();
490   *
491   *     StringBuilder msg = new StringBuilder();
492   *
493   *     properties.forEach((it)-> {
494   *       Object propertyValue = it.getVal(doc);
495   *       String propertyName = it.getName();
496   *       msg.append(" property["+propertyName+"] value["+propertyValue+"]");
497   *     });
498   *
499   *     // uniqueProperties > [title]
500   *     //       custom msg > property[title] value[One flew over the cuckoo's nest]
501   *
502   *  }
503   *
504   * }</pre>
505   *
506   * @param bean The entity bean to check uniqueness on
507   * @return a set of Properties if constraint validation was detected or empty list.
508   */
509  @Nonnull
510  public static Set<Property> checkUniqueness(Object bean) {
511    return getDefault().checkUniqueness(bean);
512  }
513
514  /**
515   * Same as {@link #checkUniqueness(Object)}. but with given transaction.
516   */
517  @Nonnull
518  public static Set<Property> checkUniqueness(Object bean, Transaction transaction) {
519    return getDefault().checkUniqueness(bean, transaction);
520  }
521
522  /**
523   * Delete the bean.
524   * <p>
525   * This will return true if the bean was deleted successfully or JDBC batch is being used.
526   * </p>
527   * <p>
528   * If there is no current transaction one will be created and committed for
529   * you automatically.
530   * </p>
531   * <p>
532   * If the bean is configured with <code>@SoftDelete</code> then this will perform a soft
533   * delete rather than a hard/permanent delete.
534   * </p>
535   * <p>
536   * If the Bean does not have a version property (or loaded version property) and
537   * the bean does not exist then this returns false indicating that nothing was
538   * deleted. Note that, if JDBC batch mode is used then this always returns true.
539   * </p>
540   */
541  public static boolean delete(Object bean) throws OptimisticLockException {
542    return getDefault().delete(bean);
543  }
544
545  /**
546   * Delete the bean in permanent fashion (will not use soft delete).
547   */
548  public static boolean deletePermanent(Object bean) throws OptimisticLockException {
549    return getDefault().deletePermanent(bean);
550  }
551
552  /**
553   * Delete the bean given its type and id.
554   */
555  public static int delete(Class<?> beanType, Object id) {
556    return getDefault().delete(beanType, id);
557  }
558
559  /**
560   * Delete permanent the bean given its type and id.
561   */
562  public static int deletePermanent(Class<?> beanType, Object id) {
563    return getDefault().deletePermanent(beanType, id);
564  }
565
566  /**
567   * Delete several beans given their type and id values.
568   */
569  public static int deleteAll(Class<?> beanType, Collection<?> ids) {
570    return getDefault().deleteAll(beanType, ids);
571  }
572
573  /**
574   * Delete permanent several beans given their type and id values.
575   */
576  public static int deleteAllPermanent(Class<?> beanType, Collection<?> ids) {
577    return getDefault().deleteAllPermanent(beanType, ids);
578  }
579
580  /**
581   * Delete all the beans in the Collection.
582   */
583  public static int deleteAll(Collection<?> beans) throws OptimisticLockException {
584    return getDefault().deleteAll(beans);
585  }
586
587  /**
588   * Delete permanent all the beans in the Collection (will not use soft delete).
589   */
590  public static int deleteAllPermanent(Collection<?> beans) throws OptimisticLockException {
591    return getDefault().deleteAllPermanent(beans);
592  }
593
594  /**
595   * Refresh the values of a bean.
596   * <p>
597   * Note that this resets OneToMany and ManyToMany properties so that if they
598   * are accessed a lazy load will refresh the many property.
599   * </p>
600   */
601  public static void refresh(Object bean) {
602    getDefault().refresh(bean);
603  }
604
605  /**
606   * Refresh a 'many' property of a bean.
607   * <pre>{@code
608   *
609   *   Order order = ...;
610   *   ...
611   *   // refresh the order details...
612   *   Ebean.refreshMany(order, "details");
613   *
614   * }</pre>
615   *
616   * @param bean             the entity bean containing the List Set or Map to refresh.
617   * @param manyPropertyName the property name of the List Set or Map to refresh.
618   */
619  public static void refreshMany(Object bean, String manyPropertyName) {
620    getDefault().refreshMany(bean, manyPropertyName);
621  }
622
623  /**
624   * Get a reference object.
625   * <p>
626   * This is sometimes described as a proxy (with lazy loading).
627   * </p>
628   * <pre>{@code
629   *
630   *   Product product = Ebean.getReference(Product.class, 1);
631   *
632   *   // You can get the id without causing a fetch/lazy load
633   *   Integer productId = product.getId();
634   *
635   *   // If you try to get any other property a fetch/lazy loading will occur
636   *   // This will cause a query to execute...
637   *   String name = product.getName();
638   *
639   * }</pre>
640   *
641   * @param beanType the type of entity bean
642   * @param id       the id value
643   */
644  public static <T> T getReference(Class<T> beanType, Object id) {
645    return getDefault().getReference(beanType, id);
646  }
647
648  /**
649   * Sort the list using the sortByClause which can contain a comma delimited
650   * list of property names and keywords asc, desc, nullsHigh and nullsLow.
651   * <ul>
652   * <li>asc - ascending order (which is the default)</li>
653   * <li>desc - Descending order</li>
654   * <li>nullsHigh - Treat null values as high/large values (which is the
655   * default)</li>
656   * <li>nullsLow- Treat null values as low/very small values</li>
657   * </ul>
658   * <p>
659   * If you leave off any keywords the defaults are ascending order and treating
660   * nulls as high values.
661   * </p>
662   * <p>
663   * Note that the sorting uses a Comparator and Collections.sort(); and does
664   * not invoke a DB query.
665   * </p>
666   * <pre>{@code
667   *
668   *   // find orders and their customers
669   *   List<Order> list = Ebean.find(Order.class)
670   *     .fetch("customer")
671   *     .order("id")
672   *     .findList();
673   *
674   *   // sort by customer name ascending, then by order shipDate
675   *   // ... then by the order status descending
676   *   Ebean.sort(list, "customer.name, shipDate, status desc");
677   *
678   *   // sort by customer name descending (with nulls low)
679   *   // ... then by the order id
680   *   Ebean.sort(list, "customer.name desc nullsLow, id");
681   *
682   * }</pre>
683   *
684   * @param list         the list of entity beans
685   * @param sortByClause the properties to sort the list by
686   */
687  public static <T> void sort(List<T> list, String sortByClause) {
688    getDefault().sort(list, sortByClause);
689  }
690
691  /**
692   * Find a bean using its unique id. This will not use caching.
693   * <pre>{@code
694   *
695   *   // Fetch order 1
696   *   Order order = Ebean.find(Order.class, 1);
697   *
698   * }</pre>
699   * <p>
700   * If you want more control over the query then you can use createQuery() and
701   * Query.findOne();
702   * </p>
703   * <pre>{@code
704   *
705   *   // ... additionally fetching customer, customer shipping address,
706   *   // order details, and the product associated with each order detail.
707   *   // note: only product id and name is fetch (its a "partial object").
708   *   // note: all other objects use "*" and have all their properties fetched.
709   *
710   *   Query<Order> query = Ebean.find(Order.class)
711   *     .setId(1)
712   *     .fetch("customer")
713   *     .fetch("customer.shippingAddress")
714   *     .fetch("details")
715   *     .query();
716   *
717   *   // fetch associated products but only fetch their product id and name
718   *   query.fetch("details.product", "name");
719   *
720   *   // traverse the object graph...
721   *
722   *   Order order = query.findOne();
723   *
724   *   Customer customer = order.getCustomer();
725   *   Address shippingAddress = customer.getShippingAddress();
726   *   List<OrderDetail> details = order.getDetails();
727   *   OrderDetail detail0 = details.get(0);
728   *   Product product = detail0.getProduct();
729   *   String productName = product.getName();
730   *
731   * }</pre>
732   *
733   * @param beanType the type of entity bean to fetch
734   * @param id       the id value
735   */
736  @Nullable
737  public static <T> T find(Class<T> beanType, Object id) {
738    return getDefault().find(beanType, id);
739  }
740
741  /**
742   * Deprecated - migrate to DB.sqlQuery().
743   * <p>
744   * Create a SqlQuery for executing native sql
745   * query statements.
746   * <p>
747   * Note that you can use raw SQL with entity beans, refer to the SqlSelect
748   * annotation for examples.
749   * </p>
750   */
751  @Deprecated
752  public static SqlQuery createSqlQuery(String sql) {
753    return getDefault().sqlQuery(sql);
754  }
755
756  /**
757   * Deprecated - migrate to DB.sqlUpdate().
758   * <p>
759   * Create a sql update for executing native dml statements.
760   * <p>
761   * Use this to execute a Insert Update or Delete statement. The statement will
762   * be native to the database and contain database table and column names.
763   * <p>
764   * See {@link SqlUpdate} for example usage.
765   */
766  @Deprecated
767  public static SqlUpdate createSqlUpdate(String sql) {
768    return getDefault().sqlUpdate(sql);
769  }
770
771  /**
772   * Create a CallableSql to execute a given stored procedure.
773   *
774   * @see CallableSql
775   */
776  public static CallableSql createCallableSql(String sql) {
777    return getDefault().createCallableSql(sql);
778  }
779
780  /**
781   * Create a orm update where you will supply the insert/update or delete
782   * statement (rather than using a named one that is already defined using the
783   * &#064;NamedUpdates annotation).
784   * <p>
785   * The orm update differs from the sql update in that it you can use the bean
786   * name and bean property names rather than table and column names.
787   * </p>
788   * <p>
789   * An example:
790   * </p>
791   * <pre>{@code
792   *
793   *   // The bean name and properties - "topic","postCount" and "id"
794   *
795   *   // will be converted into their associated table and column names
796   *   String updStatement = "update topic set postCount = :pc where id = :id";
797   *
798   *   Update<Topic> update = Ebean.createUpdate(Topic.class, updStatement);
799   *
800   *   update.set("pc", 9);
801   *   update.set("id", 3);
802   *
803   *   int rows = update.execute();
804   *   System.out.println("rows updated:" + rows);
805   *
806   * }</pre>
807   */
808  public static <T> Update<T> createUpdate(Class<T> beanType, String ormUpdate) {
809    return getDefault().createUpdate(beanType, ormUpdate);
810  }
811
812  /**
813   * Create a CsvReader for a given beanType.
814   */
815  public static <T> CsvReader<T> createCsvReader(Class<T> beanType) {
816    return getDefault().createCsvReader(beanType);
817  }
818
819  /**
820   * Create a named query.
821   * <p>
822   * For RawSql the named query is expected to be in ebean.xml.
823   * </p>
824   *
825   * @param beanType   The type of entity bean
826   * @param namedQuery The name of the query
827   * @param <T>        The type of entity bean
828   * @return The query
829   */
830  public static <T> Query<T> createNamedQuery(Class<T> beanType, String namedQuery) {
831    return getDefault().createNamedQuery(beanType, namedQuery);
832  }
833
834  /**
835   * Create a query for a type of entity bean.
836   * <p>
837   * You can use the methods on the Query object to specify fetch paths,
838   * predicates, order by, limits etc.
839   * </p>
840   * <p>
841   * You then use findList(), findSet(), findMap() and findOne() to execute
842   * the query and return the collection or bean.
843   * </p>
844   * <p>
845   * Note that a query executed by {@link Query#findList()}
846   * {@link Query#findSet()} etc will execute against the same EbeanServer from
847   * which is was created.
848   * </p>
849   *
850   * @param beanType the class of entity to be fetched
851   * @return A ORM Query object for this beanType
852   */
853  public static <T> Query<T> createQuery(Class<T> beanType) {
854    return getDefault().createQuery(beanType);
855  }
856
857  /**
858   * Parse the Ebean query language statement returning the query which can then
859   * be modified (add expressions, change order by clause, change maxRows, change
860   * fetch and select paths etc).
861   * <p>
862   * <h3>Example</h3>
863   * <pre>{@code
864   *
865   *   // Find order additionally fetching the customer, details and details.product name.
866   *
867   *   String eql = "fetch customer fetch details fetch details.product (name) where id = :orderId ";
868   *
869   *   Query<Order> query = Ebean.createQuery(Order.class, eql);
870   *   query.setParameter("orderId", 2);
871   *
872   *   Order order = query.findOne();
873   *
874   *   // This is the same as:
875   *
876   *   Order order = Ebean.find(Order.class)
877   *     .fetch("customer")
878   *     .fetch("details")
879   *     .fetch("detail.product", "name")
880   *     .setId(2)
881   *     .findOne();
882   *
883   * }</pre>
884   *
885   * @param beanType The type of bean to fetch
886   * @param eql      The Ebean query
887   * @param <T>      The type of the entity bean
888   * @return The query with expressions defined as per the parsed query statement
889   */
890  public static <T> Query<T> createQuery(Class<T> beanType, String eql) {
891    return getDefault().createQuery(beanType, eql);
892  }
893
894  /**
895   * Create a query for a type of entity bean.
896   * <p>
897   * This is actually the same as {@link #createQuery(Class)}. The reason it
898   * exists is that people used to JPA will probably be looking for a
899   * createQuery method (the same as entityManager).
900   * </p>
901   *
902   * @param beanType the type of entity bean to find
903   * @return A ORM Query object for this beanType
904   */
905  public static <T> Query<T> find(Class<T> beanType) {
906    return getDefault().find(beanType);
907  }
908
909  /**
910   * Create a query using native SQL.
911   * <p>
912   * The native SQL can contain named parameters or positioned parameters.
913   * </p>
914   * <pre>{@code
915   *
916   *   String sql = "select c.id, c.name from customer c where c.name like ? order by c.name";
917   *
918   *   List<Customer> customers = DB.findNative(Customer.class, sql)
919   *     .setParameter(1, "Rob%")
920   *     .findList()
921   *
922   * }</pre>
923   *
924   * @param beanType  The type of entity bean to fetch
925   * @param nativeSql The SQL that can contain named or positioned parameters
926   * @return The query to set parameters and execute
927   */
928  public static <T> Query<T> findNative(Class<T> beanType, String nativeSql) {
929    return getDefault().findNative(beanType, nativeSql);
930  }
931
932  /**
933   * Create a Query for DTO beans.
934   * <p>
935   * DTO beans are just normal bean like classes with public constructor(s) and setters.
936   * They do not need to be registered with Ebean before use.
937   * </p>
938   *
939   * @param dtoType The type of the DTO bean the rows will be mapped into.
940   * @param sql     The SQL query to execute.
941   * @param <T>     The type of the DTO bean.
942   */
943  public static <T> DtoQuery<T> findDto(Class<T> dtoType, String sql) {
944    return getDefault().findDto(dtoType, sql);
945  }
946
947  /**
948   * Create an Update query to perform a bulk update.
949   * <p>
950   * <pre>{@code
951   *
952   *  int rows = Ebean.update(Customer.class)
953   *      .set("status", Customer.Status.ACTIVE)
954   *      .set("updtime", new Timestamp(System.currentTimeMillis()))
955   *      .where()
956   *        .gt("id", 1000)
957   *        .update();
958   *
959   * }</pre>
960   *
961   * @param beanType The type of entity bean to update
962   * @param <T>      The type of entity bean
963   * @return The update query to use
964   */
965  public static <T> UpdateQuery<T> update(Class<T> beanType) {
966    return getDefault().update(beanType);
967  }
968
969  /**
970   * Create a filter for sorting and filtering lists of entities locally without
971   * going back to the database.
972   * <p>
973   * This produces and returns a new list with the sort and filters applied.
974   * </p>
975   * <p>
976   * Refer to {@link Filter} for an example of its use.
977   * </p>
978   */
979  public static <T> Filter<T> filter(Class<T> beanType) {
980    return getDefault().filter(beanType);
981  }
982
983  /**
984   * Execute a Sql Update Delete or Insert statement. This returns the number of
985   * rows that where updated, deleted or inserted. If is executed in batch then
986   * this returns -1. You can get the actual rowCount after commit() from
987   * updateSql.getRowCount().
988   * <p>
989   * If you wish to execute a Sql Select natively then you should use the
990   * FindByNativeSql object.
991   * </p>
992   * <p>
993   * Note that the table modification information is automatically deduced and
994   * you do not need to call the Ebean.externalModification() method when you
995   * use this method.
996   * </p>
997   * <p>
998   * Example:
999   * </p>
1000   * <pre>{@code
1001   *
1002   *   // example that uses 'named' parameters
1003   *   String s = "UPDATE f_topic set post_count = :count where id = :id"
1004   *
1005   *   SqlUpdate update = Ebean.createSqlUpdate(s);
1006   *
1007   *   update.setParameter("id", 1);
1008   *   update.setParameter("count", 50);
1009   *
1010   *   int modifiedCount = Ebean.execute(update);
1011   *
1012   *   String msg = "There where " + modifiedCount + "rows updated";
1013   *
1014   * }</pre>
1015   *
1016   * @param sqlUpdate the update sql potentially with bind values
1017   * @return the number of rows updated or deleted. -1 if executed in batch.
1018   * @see SqlUpdate
1019   * @see CallableSql
1020   * @see Ebean#execute(CallableSql)
1021   */
1022  public static int execute(SqlUpdate sqlUpdate) {
1023    return getDefault().execute(sqlUpdate);
1024  }
1025
1026  /**
1027   * For making calls to stored procedures.
1028   * <p>
1029   * Example:
1030   * </p>
1031   * <pre>{@code
1032   *
1033   *   String sql = "{call sp_order_modify(?,?,?)}";
1034   *
1035   *   CallableSql cs = Ebean.createCallableSql(sql);
1036   *   cs.setParameter(1, 27);
1037   *   cs.setParameter(2, "SHIPPED");
1038   *   cs.registerOut(3, Types.INTEGER);
1039   *
1040   *   Ebean.execute(cs);
1041   *
1042   *   // read the out parameter
1043   *   Integer returnValue = (Integer) cs.getObject(3);
1044   *
1045   * }</pre>
1046   *
1047   * @see CallableSql
1048   * @see Ebean#execute(SqlUpdate)
1049   */
1050  public static int execute(CallableSql callableSql) {
1051    return getDefault().execute(callableSql);
1052  }
1053
1054  /**
1055   * Execute a TxRunnable in a Transaction with an explicit scope.
1056   * <p>
1057   * The scope can control the transaction type, isolation and rollback
1058   * semantics.
1059   * </p>
1060   * <pre>{@code
1061   *
1062   *   // set specific transactional scope settings
1063   *   TxScope scope = TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE);
1064   *
1065   *   Ebean.execute(scope, new TxRunnable() {
1066   *       public void run() {
1067   *               User u1 = Ebean.find(User.class, 1);
1068   *               ...
1069   *     }
1070   *   });
1071   *
1072   * }</pre>
1073   */
1074  public static void execute(TxScope scope, Runnable r) {
1075    getDefault().execute(scope, r);
1076  }
1077
1078  /**
1079   * Execute a Runnable in a Transaction with the default scope.
1080   * <p>
1081   * The default scope runs with REQUIRED and by default will rollback on any
1082   * exception (checked or runtime).
1083   * </p>
1084   * <pre>{@code
1085   *
1086   *   Ebean.execute(() -> {
1087   *
1088   *       User u1 = Ebean.find(User.class, 1);
1089   *       User u2 = Ebean.find(User.class, 2);
1090   *
1091   *       u1.setName("u1 mod");
1092   *       u2.setName("u2 mod");
1093   *
1094   *       Ebean.save(u1);
1095   *       Ebean.save(u2);
1096   *
1097   *   });
1098   *
1099   * }</pre>
1100   */
1101  public static void execute(Runnable r) {
1102    getDefault().execute(r);
1103  }
1104
1105  /**
1106   * Execute a Callable in a Transaction with an explicit scope.
1107   * <p>
1108   * The scope can control the transaction type, isolation and rollback
1109   * semantics.
1110   * </p>
1111   * <pre>{@code
1112   *
1113   *   // set specific transactional scope settings
1114   *   TxScope scope = TxScope.requiresNew().setIsolation(TxIsolation.SERIALIZABLE);
1115   *
1116   *   Ebean.executeCall(scope, new Callable<String>() {
1117   *       public String call() {
1118   *               User u1 = Ebean.find(User.class, 1);
1119   *               ...
1120   *               return u1.getEmail();
1121   *     }
1122   *   });
1123   *
1124   * }</pre>
1125   */
1126  public static <T> T executeCall(TxScope scope, Callable<T> c) {
1127    return getDefault().executeCall(scope, c);
1128  }
1129
1130  /**
1131   * Execute a Callable in a Transaction with the default scope.
1132   * <p>
1133   * The default scope runs with REQUIRED and by default will rollback on any
1134   * exception (checked or runtime).
1135   * </p>
1136   * <p>
1137   * This is basically the same as TxRunnable except that it returns an Object
1138   * (and you specify the return type via generics).
1139   * </p>
1140   * <pre>{@code
1141   *
1142   *   Ebean.executeCall(() -> {
1143   *
1144   *       User u1 = Ebean.find(User.class, 1);
1145   *       User u2 = Ebean.find(User.class, 2);
1146   *
1147   *       u1.setName("u1 mod");
1148   *       u2.setName("u2 mod");
1149   *
1150   *       Ebean.save(u1);
1151   *       Ebean.save(u2);
1152   *
1153   *       return u1.getEmail();
1154   *
1155   *   });
1156   *
1157   * }</pre>
1158   */
1159  public static <T> T executeCall(Callable<T> c) {
1160    return getDefault().executeCall(c);
1161  }
1162
1163  /**
1164   * Inform Ebean that tables have been modified externally. These could be the
1165   * result of from calling a stored procedure, other JDBC calls or external
1166   * programs including other frameworks.
1167   * <p>
1168   * If you use Ebean.execute(UpdateSql) then the table modification information
1169   * is automatically deduced and you do not need to call this method yourself.
1170   * </p>
1171   * <p>
1172   * This information is used to invalidate objects out of the cache and
1173   * potentially text indexes. This information is also automatically broadcast
1174   * across the cluster.
1175   * </p>
1176   * <p>
1177   * If there is a transaction then this information is placed into the current
1178   * transactions event information. When the transaction is committed this
1179   * information is registered (with the transaction manager). If this
1180   * transaction is rolled back then none of the transaction event information
1181   * registers including the information you put in via this method.
1182   * </p>
1183   * <p>
1184   * If there is NO current transaction when you call this method then this
1185   * information is registered immediately (with the transaction manager).
1186   * </p>
1187   *
1188   * @param tableName the name of the table that was modified
1189   * @param inserts   true if rows where inserted into the table
1190   * @param updates   true if rows on the table where updated
1191   * @param deletes   true if rows on the table where deleted
1192   */
1193  public static void externalModification(String tableName, boolean inserts, boolean updates, boolean deletes) {
1194    getDefault().externalModification(tableName, inserts, updates, deletes);
1195  }
1196
1197  /**
1198   * Return the BeanState for a given entity bean.
1199   * <p>
1200   * This will return null if the bean is not an enhanced entity bean.
1201   * </p>
1202   */
1203  public static BeanState getBeanState(Object bean) {
1204    return getDefault().getBeanState(bean);
1205  }
1206
1207  /**
1208   * Return the manager of the server cache ("L2" cache).
1209   */
1210  public static ServerCacheManager getServerCacheManager() {
1211    return getDefault().getServerCacheManager();
1212  }
1213
1214  /**
1215   * Return the BackgroundExecutor service for asynchronous processing of
1216   * queries.
1217   */
1218  public static BackgroundExecutor getBackgroundExecutor() {
1219    return getDefault().getBackgroundExecutor();
1220  }
1221
1222  /**
1223   * Return the JsonContext for reading/writing JSON.
1224   */
1225  public static JsonContext json() {
1226    return getDefault().json();
1227  }
1228
1229}