mirror of
https://github.com/ebean-orm/ebean.git
synced 2026-11-17 22:56:28 +00:00
#919 - io.ebean package initial
This commit is contained in:
1 parent
5821dc96b9
commit
971e2dc91b
2134 files changed
+10721
-8652
No files matched your search
@@ -0,0 +1,310 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.server.core.PersistRequest;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* Controls the batch ordering of persist requests.
|
||||
* <p>
|
||||
* Persist requests include bean inserts updates deletes and UpdateSql and
|
||||
* CallableSql requests.
|
||||
* </p>
|
||||
* <p>
|
||||
* This object queues up the requests into appropriate entries according to the
|
||||
* 'depth' and the 'type' of the requests. The depth relates to how saves and
|
||||
* deletes cascade following the associations of a bean. For saving Associated
|
||||
* One cascades reduce the depth (-1) and associated many's increase the depth.
|
||||
* The initial depth of a request is 0.
|
||||
* </p>
|
||||
*/
|
||||
public final class BatchControl {
|
||||
|
||||
/**
|
||||
* Used to sort queue entries by depth.
|
||||
*/
|
||||
private static final BatchDepthComparator depthComparator = new BatchDepthComparator();
|
||||
|
||||
/**
|
||||
* Controls batching of the PreparedStatements. This should be flushed after
|
||||
* each 'depth'.
|
||||
*/
|
||||
private final BatchedPstmtHolder pstmtHolder = new BatchedPstmtHolder();
|
||||
|
||||
/**
|
||||
* Map of the BatchedBeanHolder objects. They each have a depth and are later
|
||||
* sorted by their depth to get the execution order.
|
||||
*/
|
||||
private final HashMap<String, BatchedBeanHolder> beanHoldMap = new HashMap<>();
|
||||
|
||||
private final SpiTransaction transaction;
|
||||
|
||||
/**
|
||||
* The size at which the batch queue will flush. This should be close to the
|
||||
* number of statements that are batched into a single PreparedStatement. This
|
||||
* size relates to the size of a list in a BatchQueueEntry and not the total
|
||||
* number of request which could be more than that.
|
||||
*/
|
||||
private int batchSize;
|
||||
|
||||
/**
|
||||
* If true try to get generated keys from inserts.
|
||||
*/
|
||||
private boolean getGeneratedKeys;
|
||||
|
||||
private boolean batchFlushOnMixed = true;
|
||||
|
||||
/**
|
||||
* Create for a given transaction, PersistExecute, default size and getGeneratedKeys.
|
||||
*/
|
||||
public BatchControl(SpiTransaction t, int batchSize, boolean getGenKeys) {
|
||||
this.transaction = t;
|
||||
this.batchSize = batchSize;
|
||||
this.getGeneratedKeys = getGenKeys;
|
||||
transaction.setBatchControl(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set this flag to false to allow batching of a mix of Beans and UpdateSql
|
||||
* (or CallableSql). Normally if you mix the two this will result in an
|
||||
* automatic flush.
|
||||
* <p>
|
||||
* Note that UpdateSql and CallableSql will ALWAYS flush first. This is due to
|
||||
* it already having been bound to a PreparedStatement where as the Beans go
|
||||
* through a 2 step process when they are flushed (delayed binding).
|
||||
* </p>
|
||||
*/
|
||||
public void setBatchFlushOnMixed(boolean flushBatchOnMixed) {
|
||||
this.batchFlushOnMixed = flushBatchOnMixed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the batchSize.
|
||||
*/
|
||||
public int getBatchSize() {
|
||||
return batchSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the size of batch execution.
|
||||
* <p>
|
||||
* The user can set this via the Transaction.
|
||||
* </p>
|
||||
*/
|
||||
public void setBatchSize(int batchSize) {
|
||||
if (batchSize > 1) {
|
||||
this.batchSize = batchSize;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether or not to use getGeneratedKeys for this batch execution.
|
||||
* <p>
|
||||
* The user can set this via the transaction
|
||||
* </p>
|
||||
*/
|
||||
public void setGetGeneratedKeys(Boolean getGeneratedKeys) {
|
||||
if (getGeneratedKeys != null) {
|
||||
this.getGeneratedKeys = getGeneratedKeys;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a Orm Update, SqlUpdate or CallableSql.
|
||||
* <p>
|
||||
* These all go straight to jdbc and use addBatch(). Entity beans goto a queue
|
||||
* and wait there so that the jdbc is executed in the correct order according
|
||||
* to the depth.
|
||||
* </p>
|
||||
*/
|
||||
public int executeStatementOrBatch(PersistRequest request, boolean batch) {
|
||||
if (!batch || (batchFlushOnMixed && !isBeansEmpty())) {
|
||||
// flush when mixing beans and updateSql
|
||||
flush();
|
||||
}
|
||||
if (!batch) {
|
||||
// execute the request immediately without batching
|
||||
return request.executeNow();
|
||||
}
|
||||
|
||||
if (pstmtHolder.getMaxSize() >= batchSize) {
|
||||
flush();
|
||||
}
|
||||
// for OrmUpdate, SqlUpdate, CallableSql there is no queue...
|
||||
// so straight to jdbc prepared statement and use addBatch().
|
||||
// aka executeNow() may use addBatch().
|
||||
request.executeNow();
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Entity Bean insert, update or delete. This will either execute the request
|
||||
* immediately or queue it for batch processing later. The queue is flushedIntercept
|
||||
* according to the depth (object graph depth).
|
||||
*/
|
||||
public int executeOrQueue(PersistRequestBean<?> request, boolean batch) {
|
||||
|
||||
if (!batch || (batchFlushOnMixed && !pstmtHolder.isEmpty())) {
|
||||
// flush when mixing beans and updateSql
|
||||
flush();
|
||||
}
|
||||
if (!batch) {
|
||||
return request.executeNow();
|
||||
}
|
||||
if (addToBatch(request)) {
|
||||
// flush as the top level has hit the batch size
|
||||
flush();
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the request to the batch and return true if we should flush.
|
||||
*/
|
||||
private boolean addToBatch(PersistRequestBean<?> request) {
|
||||
|
||||
BatchedBeanHolder beanHolder = getBeanHolder(request);
|
||||
int bufferSize = beanHolder.append(request);
|
||||
|
||||
// return true if top level has hit batch size
|
||||
return bufferSize == batchSize && beanHolder.getOrder() == 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the actual batch of PreparedStatements.
|
||||
*/
|
||||
public BatchedPstmtHolder getPstmtHolder() {
|
||||
return pstmtHolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the queue is empty.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return (isBeansEmpty() && pstmtHolder.isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush any batched PreparedStatements.
|
||||
*/
|
||||
protected void flushPstmtHolder() {
|
||||
pstmtHolder.flush(getGeneratedKeys);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute all the requests contained in the list.
|
||||
*/
|
||||
protected void executeNow(ArrayList<PersistRequest> list) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
if (i % batchSize == 0) {
|
||||
// hit the batch size so flush
|
||||
flushPstmtHolder();
|
||||
}
|
||||
list.get(i).executeNow();
|
||||
}
|
||||
flushPstmtHolder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush without resetting the topOrder (maintains the depth info).
|
||||
*/
|
||||
public void flush() throws PersistenceException {
|
||||
flush(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush with a reset the topOrder (fully empty the batch).
|
||||
*/
|
||||
public void flushReset() throws PersistenceException {
|
||||
flush(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the batch, discarding all batched statements.
|
||||
*/
|
||||
public void clear() {
|
||||
pstmtHolder.clear();
|
||||
beanHoldMap.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* execute all the requests currently queued or batched.
|
||||
*/
|
||||
private void flush(boolean resetTop) throws PersistenceException {
|
||||
|
||||
if (!pstmtHolder.isEmpty()) {
|
||||
// Flush existing pstmts (updateSql or callableSql)
|
||||
flushPstmtHolder();
|
||||
}
|
||||
if (isEmpty()) {
|
||||
// Nothing in queue to flush
|
||||
return;
|
||||
}
|
||||
|
||||
// convert entry map to array for sorting
|
||||
BatchedBeanHolder[] bsArray = getBeanHolderArray();
|
||||
// sort the entries by depth
|
||||
Arrays.sort(bsArray, depthComparator);
|
||||
|
||||
if (transaction.isLogSummary()) {
|
||||
transaction.logSummary("BatchControl flush " + Arrays.toString(bsArray));
|
||||
}
|
||||
for (BatchedBeanHolder aBsArray : bsArray) {
|
||||
aBsArray.executeNow();
|
||||
}
|
||||
|
||||
if (resetTop) {
|
||||
beanHoldMap.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an entry for the given type description. The type description is
|
||||
* typically the bean class name (or table name for MapBeans).
|
||||
*/
|
||||
private BatchedBeanHolder getBeanHolder(PersistRequestBean<?> request) {
|
||||
|
||||
BeanDescriptor<?> beanDescriptor = request.getBeanDescriptor();
|
||||
BatchedBeanHolder batchBeanHolder = beanHoldMap.get(beanDescriptor.getFullName());
|
||||
if (batchBeanHolder == null) {
|
||||
int relativeDepth = transaction.depth();
|
||||
if (relativeDepth == 0 && !beanHoldMap.isEmpty()) {
|
||||
// flush and reset the batch as we are changing the type of our top level
|
||||
// bean so just keep it simple and flush and reset the top
|
||||
flushReset();
|
||||
}
|
||||
|
||||
batchBeanHolder = new BatchedBeanHolder(this, beanDescriptor, 100 + relativeDepth);
|
||||
beanHoldMap.put(beanDescriptor.getFullName(), batchBeanHolder);
|
||||
}
|
||||
return batchBeanHolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this holds no persist requests.
|
||||
*/
|
||||
private boolean isBeansEmpty() {
|
||||
if (beanHoldMap.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
for (BatchedBeanHolder beanHolder : beanHoldMap.values()) {
|
||||
if (!beanHolder.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the BatchedBeanHolder's ready for sorting and executing.
|
||||
*/
|
||||
private BatchedBeanHolder[] getBeanHolderArray() {
|
||||
return beanHoldMap.values().toArray(new BatchedBeanHolder[beanHoldMap.size()]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Comparator;
|
||||
|
||||
/**
|
||||
* Used to sort BatchedBeanHolder by their depth.
|
||||
* <p>
|
||||
* Beans are queued and put into BatchedBeanHolder along with their depth. This
|
||||
* delays the actually binding to PreparedStatements until the
|
||||
* BatchedBeanHolder's are flushed. This is so that we can get the generated
|
||||
* keys from inserts. These values are required to persist the 'detail' beans.
|
||||
* </p>
|
||||
*/
|
||||
public class BatchDepthComparator implements Comparator<BatchedBeanHolder>, Serializable {
|
||||
|
||||
private static final long serialVersionUID = 264611821665757991L;
|
||||
|
||||
public int compare(BatchedBeanHolder b1, BatchedBeanHolder b2) {
|
||||
|
||||
if (b1.getOrder() < b2.getOrder()) {
|
||||
return -1;
|
||||
}
|
||||
if (b1.getOrder() == b2.getOrder()) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
/**
|
||||
* Handles the processing required after batch execution.
|
||||
* <p>
|
||||
* This includes concurrency checking, generated keys on inserts, transaction
|
||||
* logging, transaction event table modifcation and for beans resetting their
|
||||
* 'loaded' status.
|
||||
* </p>
|
||||
*/
|
||||
public interface BatchPostExecute {
|
||||
|
||||
/**
|
||||
* Check that the rowCount is correct for this execute. This is for
|
||||
* performing concurrency checking in batch execution.
|
||||
*/
|
||||
void checkRowCount(int rowCount);
|
||||
|
||||
/**
|
||||
* For inserts with generated keys. Otherwise not used.
|
||||
*/
|
||||
void setGeneratedKey(Object idValue);
|
||||
|
||||
/**
|
||||
* Execute the post execute processing.
|
||||
* <p>
|
||||
* This includes transaction logging, transaction event table modification
|
||||
* and for beans resetting their 'loaded' status.
|
||||
* </p>
|
||||
*/
|
||||
void postExecute();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebeaninternal.server.core.PersistRequest;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.IdentityHashMap;
|
||||
|
||||
/**
|
||||
* Holds lists of persist requests for beans of a given type.
|
||||
* <p>
|
||||
* This is used to delay the actual binding of the bean to PreparedStatements.
|
||||
* The reason is that we don't have all the bind values yet in the case of inserts
|
||||
* with getGeneratedKeys.
|
||||
* </p>
|
||||
* <p>
|
||||
* Has a depth which is used to determine the order in which it should be
|
||||
* executed. The lowest depth is executed first.
|
||||
* </p>
|
||||
*/
|
||||
public class BatchedBeanHolder {
|
||||
|
||||
private static final Object DUMMY = new Object();
|
||||
|
||||
/**
|
||||
* The owning queue.
|
||||
*/
|
||||
private final BatchControl control;
|
||||
|
||||
private final String shortDesc;
|
||||
|
||||
/**
|
||||
* The 'depth' which is used to determine the execution order.
|
||||
*/
|
||||
private final int order;
|
||||
|
||||
/**
|
||||
* The list of bean insert requests.
|
||||
*/
|
||||
private ArrayList<PersistRequest> inserts;
|
||||
|
||||
/**
|
||||
* The list of bean update requests.
|
||||
*/
|
||||
private ArrayList<PersistRequest> updates;
|
||||
|
||||
/**
|
||||
* The list of bean delete requests.
|
||||
*/
|
||||
private ArrayList<PersistRequest> deletes;
|
||||
|
||||
/**
|
||||
* Set of beans in this batch. This is used to ensure that a single bean instance is not included
|
||||
* in the batch twice (two separate insert requests etc).
|
||||
*/
|
||||
private final IdentityHashMap<Object, Object> persistedBeans = new IdentityHashMap<>();
|
||||
|
||||
/**
|
||||
* Create a new entry with a given type and depth.
|
||||
*/
|
||||
public BatchedBeanHolder(BatchControl control, BeanDescriptor<?> beanDescriptor, int order) {
|
||||
this.control = control;
|
||||
this.shortDesc = beanDescriptor.getName() + ":" + order;
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the depth.
|
||||
*/
|
||||
public int getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute all the persist requests in this entry.
|
||||
* <p>
|
||||
* This will Batch all the similar requests into one or more BatchStatements
|
||||
* and then execute them.
|
||||
* </p>
|
||||
*/
|
||||
public void executeNow() {
|
||||
// process the requests. Creates one or more PreparedStatements
|
||||
// with binding addBatch() for each request.
|
||||
// Note updates and deletes can result in many PreparedStatements
|
||||
// if their where clauses differ via use of IS NOT NULL.
|
||||
if (inserts != null && !inserts.isEmpty()) {
|
||||
control.executeNow(inserts);
|
||||
inserts.clear();
|
||||
}
|
||||
if (updates != null && !updates.isEmpty()) {
|
||||
control.executeNow(updates);
|
||||
updates.clear();
|
||||
}
|
||||
if (deletes != null && !deletes.isEmpty()) {
|
||||
control.executeNow(deletes);
|
||||
deletes.clear();
|
||||
}
|
||||
persistedBeans.clear();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder(shortDesc.length() + 18);
|
||||
sb.append(shortDesc);
|
||||
if (inserts != null) {
|
||||
sb.append(" i:").append(inserts.size());
|
||||
}
|
||||
if (updates != null) {
|
||||
sb.append(" u:").append(updates.size());
|
||||
}
|
||||
if (deletes != null) {
|
||||
sb.append(" d:").append(deletes.size());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the request to the appropriate persist list.
|
||||
*/
|
||||
public int append(PersistRequestBean<?> request) {
|
||||
|
||||
Object alreadyInBatch = persistedBeans.put(request.getEntityBean(), DUMMY);
|
||||
if (alreadyInBatch != null) {
|
||||
// special case where the same bean instance has already been
|
||||
// added to the batch (doesn't really occur with non-batching
|
||||
// as the bean gets changed from dirty to loaded earlier)
|
||||
return 0;
|
||||
}
|
||||
|
||||
request.setBatched();
|
||||
|
||||
switch (request.getType()) {
|
||||
case INSERT:
|
||||
if (inserts == null) {
|
||||
inserts = new ArrayList<>();
|
||||
}
|
||||
inserts.add(request);
|
||||
return inserts.size();
|
||||
|
||||
case UPDATE:
|
||||
case SOFT_DELETE:
|
||||
if (updates == null) {
|
||||
updates = new ArrayList<>();
|
||||
}
|
||||
updates.add(request);
|
||||
return updates.size();
|
||||
|
||||
case DELETE:
|
||||
if (deletes == null) {
|
||||
deletes = new ArrayList<>();
|
||||
}
|
||||
deletes.add(request);
|
||||
return deletes.size();
|
||||
|
||||
default:
|
||||
throw new RuntimeException("Invalid type code " + request.getType());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this is empty containing no batched beans.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return persistedBeans.isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* A batched statement that is held in BatchedPstmtHolder. It has a list of
|
||||
* BatchPostExecute which it will process after the statement is executed.
|
||||
* <p>
|
||||
* This can hold CallableStatements as well.
|
||||
* </p>
|
||||
*/
|
||||
public class BatchedPstmt {
|
||||
|
||||
/**
|
||||
* The underlying statement.
|
||||
*/
|
||||
private PreparedStatement pstmt;
|
||||
|
||||
/**
|
||||
* True if an insert that uses generated keys.
|
||||
*/
|
||||
private final boolean isGenKeys;
|
||||
|
||||
/**
|
||||
* The list of BatchPostExecute used to perform post processing.
|
||||
*/
|
||||
private final ArrayList<BatchPostExecute> list = new ArrayList<>();
|
||||
|
||||
private final String sql;
|
||||
|
||||
/**
|
||||
* Create with a given statement.
|
||||
*/
|
||||
public BatchedPstmt(PreparedStatement pstmt, boolean isGenKeys, String sql) {
|
||||
this.pstmt = pstmt;
|
||||
this.isGenKeys = isGenKeys;
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of batched statements.
|
||||
*/
|
||||
public int size() {
|
||||
return list.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the sql
|
||||
*/
|
||||
public String getSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the statement.
|
||||
*/
|
||||
public PreparedStatement getStatement() {
|
||||
return pstmt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the BatchPostExecute to the list for post execute processing.
|
||||
*/
|
||||
public void add(BatchPostExecute batchExecute) {
|
||||
list.add(batchExecute);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the statement using executeBatch().
|
||||
* Run any post processing including getGeneratedKeys.
|
||||
*/
|
||||
public void executeBatch(boolean getGeneratedKeys) throws SQLException {
|
||||
|
||||
executeAndCheckRowCounts();
|
||||
if (isGenKeys && getGeneratedKeys) {
|
||||
getGeneratedKeys();
|
||||
}
|
||||
postExecute();
|
||||
close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the underlying statement.
|
||||
*/
|
||||
public void close() throws SQLException {
|
||||
if (pstmt != null) {
|
||||
pstmt.close();
|
||||
pstmt = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void postExecute() {
|
||||
for (BatchPostExecute aList : list) {
|
||||
aList.postExecute();
|
||||
}
|
||||
}
|
||||
|
||||
private void executeAndCheckRowCounts() throws SQLException {
|
||||
|
||||
int[] results = pstmt.executeBatch();
|
||||
if (results.length != list.size()) {
|
||||
String s = "results array error " + results.length + " " + list.size();
|
||||
throw new SQLException(s);
|
||||
}
|
||||
|
||||
// check for concurrency exceptions...
|
||||
for (int i = 0; i < results.length; i++) {
|
||||
list.get(i).checkRowCount(results[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private void getGeneratedKeys() throws SQLException {
|
||||
|
||||
int index = 0;
|
||||
ResultSet rset = pstmt.getGeneratedKeys();
|
||||
try {
|
||||
while (rset.next()) {
|
||||
Object idValue = rset.getObject(1);
|
||||
list.get(index).setGeneratedKey(idValue);
|
||||
index++;
|
||||
}
|
||||
} finally {
|
||||
if (rset != null) {
|
||||
rset.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
/**
|
||||
* Used to hold BatchedPstmt objects for batch based execution.
|
||||
* <p>
|
||||
* The BatchControl 'front ends' the batching by queuing the persist requests
|
||||
* and ordering them according to depth and type. This object should only batch
|
||||
* statements of a single 'depth' at any given time.
|
||||
* </p>
|
||||
*/
|
||||
public class BatchedPstmtHolder {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(BatchedPstmtHolder.class);
|
||||
|
||||
/**
|
||||
* A Map of the statements using a String key. This is used so that the same
|
||||
* Statement,Prepared,Callable is reused.
|
||||
*/
|
||||
private final LinkedHashMap<String, BatchedPstmt> stmtMap = new LinkedHashMap<>();
|
||||
|
||||
/**
|
||||
* The Max size across all the BatchedPstmt.
|
||||
*/
|
||||
private int maxSize;
|
||||
|
||||
public BatchedPstmtHolder() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the PreparedStatement if it has already been used in this Batch.
|
||||
* This will return null if no matching PreparedStatement is found.
|
||||
*/
|
||||
public PreparedStatement getStmt(String stmtKey, BatchPostExecute postExecute) {
|
||||
BatchedPstmt bs = stmtMap.get(stmtKey);
|
||||
if (bs == null) {
|
||||
// the PreparedStatement has need been created
|
||||
return null;
|
||||
}
|
||||
// add the post execute processing for this bean/row
|
||||
bs.add(postExecute);
|
||||
|
||||
// maintain a max batch size for any given batched stmt.
|
||||
// Used to determine when to flush.
|
||||
int bsSize = bs.size();
|
||||
if (bsSize > maxSize) {
|
||||
maxSize = bsSize;
|
||||
}
|
||||
return bs.getStatement();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new PreparedStatement wrapped in the BatchStatement object.
|
||||
*/
|
||||
public void addStmt(BatchedPstmt bs, BatchPostExecute postExecute) {
|
||||
// add the batch post execute to the statement for POST processing
|
||||
bs.add(postExecute);
|
||||
|
||||
// cache so that getStmt() can find it for additional beans/rows
|
||||
stmtMap.put(bs.getSql(), bs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the batch has no statements to execute.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return stmtMap.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute all batched PreparedStatements.
|
||||
*
|
||||
* @param getGeneratedKeys if true try to get generated keys for inserts
|
||||
*/
|
||||
public void flush(boolean getGeneratedKeys) throws PersistenceException {
|
||||
|
||||
SQLException firstError = null;
|
||||
String errorSql = null;
|
||||
|
||||
// flag set if something fails. Will not execute
|
||||
// but still need to close PreparedStatements.
|
||||
boolean isError = false;
|
||||
|
||||
for (BatchedPstmt bs : stmtMap.values()) {
|
||||
try {
|
||||
if (!isError) {
|
||||
bs.executeBatch(getGeneratedKeys);
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
SQLException next = ex.getNextException();
|
||||
while (next != null) {
|
||||
logger.error("Next Exception during batch execution", next);
|
||||
next = next.getNextException();
|
||||
}
|
||||
|
||||
if (firstError == null) {
|
||||
firstError = ex;
|
||||
errorSql = bs.getSql();
|
||||
} else {
|
||||
logger.error("Error executing batched PreparedStatement", ex);
|
||||
}
|
||||
isError = true;
|
||||
|
||||
} finally {
|
||||
try {
|
||||
bs.close();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("Error closing batched PreparedStatement", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// clear the batch cache
|
||||
clear();
|
||||
|
||||
if (firstError != null) {
|
||||
String msg = "Error when batch flush on sql: " + errorSql;
|
||||
throw new PersistenceException(msg, firstError);
|
||||
}
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
stmtMap.clear();
|
||||
maxSize = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the size of the biggest batched statement.
|
||||
* <p>
|
||||
* Used to determine when to flush the batch.
|
||||
* </p>
|
||||
*/
|
||||
public int getMaxSize() {
|
||||
return maxSize;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
/**
|
||||
* Defines bean insert update and delete implementation.
|
||||
*/
|
||||
public interface BeanPersister {
|
||||
|
||||
/**
|
||||
* execute the insert bean request.
|
||||
*/
|
||||
void insert(PersistRequestBean<?> request) throws PersistenceException;
|
||||
|
||||
/**
|
||||
* execute the update bean request.
|
||||
*/
|
||||
void update(PersistRequestBean<?> request) throws PersistenceException;
|
||||
|
||||
/**
|
||||
* execute the delete bean request.
|
||||
*/
|
||||
int delete(PersistRequestBean<?> request) throws PersistenceException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
|
||||
/**
|
||||
* Factory for creating BeanPersister implementations.
|
||||
*/
|
||||
public interface BeanPersisterFactory {
|
||||
|
||||
/**
|
||||
* Create the BeanPersister implemenation for a given type.
|
||||
*/
|
||||
BeanPersister create(BeanDescriptor<?> desc);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* Holds a list of bind values for binding to a PreparedStatement.
|
||||
*/
|
||||
public class BindValues {
|
||||
|
||||
final ArrayList<Value> list = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Create with a Binder.
|
||||
*/
|
||||
public BindValues() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of bind values.
|
||||
*/
|
||||
public int size() {
|
||||
return list.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a bind value with its JDBC datatype.
|
||||
*
|
||||
* @param value the bind value
|
||||
* @param dbType the type as per java.sql.Types
|
||||
*/
|
||||
public void add(Object value, int dbType, String name) {
|
||||
list.add(new Value(value, dbType, name));
|
||||
}
|
||||
|
||||
/**
|
||||
* List of bind values.
|
||||
*/
|
||||
public ArrayList<Value> values() {
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Value has additionally the JDBC data type.
|
||||
*/
|
||||
public static class Value {
|
||||
|
||||
private final Object value;
|
||||
|
||||
private final int dbType;
|
||||
|
||||
private final String name;
|
||||
|
||||
/**
|
||||
* Create the value.
|
||||
*/
|
||||
public Value(Object value, int dbType, String name) {
|
||||
this.value = value;
|
||||
this.dbType = dbType;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the type as per java.sql.Types.
|
||||
*/
|
||||
public int getDbType() {
|
||||
return dbType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the value.
|
||||
*/
|
||||
public Object getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the property name.
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "" + value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebean.config.dbplatform.DbPlatformType;
|
||||
import io.ebeaninternal.api.BindParams;
|
||||
import io.ebeaninternal.server.core.DbExpressionHandler;
|
||||
import io.ebeaninternal.server.core.Message;
|
||||
import io.ebeaninternal.server.core.timezone.DataTimeZone;
|
||||
import io.ebeaninternal.server.type.DataBind;
|
||||
import io.ebeaninternal.server.type.ScalarType;
|
||||
import io.ebeaninternal.server.type.TypeManager;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Binds bean values to a PreparedStatement.
|
||||
*/
|
||||
public class Binder {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Binder.class);
|
||||
|
||||
private final TypeManager typeManager;
|
||||
|
||||
private final int asOfBindCount;
|
||||
|
||||
private final boolean asOfStandardsBased;
|
||||
|
||||
private final DbExpressionHandler dbExpressionHandler;
|
||||
|
||||
private final DataTimeZone dataTimeZone;
|
||||
|
||||
/**
|
||||
* Set the PreparedStatement with which to bind variables to.
|
||||
*/
|
||||
public Binder(TypeManager typeManager, int asOfBindCount, boolean asOfStandardsBased,
|
||||
DbExpressionHandler dbExpressionHandler, DataTimeZone dataTimeZone) {
|
||||
|
||||
this.typeManager = typeManager;
|
||||
this.asOfBindCount = asOfBindCount;
|
||||
this.asOfStandardsBased = asOfStandardsBased;
|
||||
this.dbExpressionHandler = dbExpressionHandler;
|
||||
this.dataTimeZone = dataTimeZone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the bind count per predicate for 'As Of' query predicates.
|
||||
*/
|
||||
public int getAsOfBindCount() {
|
||||
return asOfBindCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the 'as of' history support is SQL2011 standards based.
|
||||
*/
|
||||
public boolean isAsOfStandardsBased() {
|
||||
return asOfStandardsBased;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the values to the Prepared Statement.
|
||||
*/
|
||||
public void bind(BindValues bindValues, DataBind dataBind, StringBuilder bindBuf) throws SQLException {
|
||||
|
||||
String logPrefix = "";
|
||||
|
||||
ArrayList<BindValues.Value> list = bindValues.values();
|
||||
for (BindValues.Value bindValue : list) {
|
||||
Object val = bindValue.getValue();
|
||||
int dt = bindValue.getDbType();
|
||||
bindObject(dataBind, val, dt);
|
||||
|
||||
if (bindBuf != null) {
|
||||
bindBuf.append(logPrefix);
|
||||
if (logPrefix.equals("")) {
|
||||
logPrefix = ", ";
|
||||
}
|
||||
bindBuf.append(bindValue.getName());
|
||||
bindBuf.append("=");
|
||||
if (isLob(dt)) {
|
||||
bindBuf.append("[LOB]");
|
||||
} else {
|
||||
bindBuf.append(String.valueOf(val));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the parameters to the preparedStatement returning the bind log.
|
||||
*/
|
||||
public String bind(BindParams bindParams, PreparedStatement statement, Connection connection) throws SQLException {
|
||||
return bind(bindParams, new DataBind(dataTimeZone, statement, connection));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the list of positionedParameters in BindParams.
|
||||
*/
|
||||
public String bind(BindParams bindParams, DataBind dataBind) throws SQLException {
|
||||
|
||||
StringBuilder bindLog = new StringBuilder();
|
||||
bind(bindParams, dataBind, bindLog);
|
||||
return bindLog.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the list of positionedParameters in BindParams.
|
||||
*/
|
||||
public void bind(BindParams bindParams, DataBind dataBind, StringBuilder bindLog) throws SQLException {
|
||||
|
||||
bind(bindParams.positionedParameters(), dataBind, bindLog);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the list of parameters..
|
||||
*/
|
||||
public void bind(List<BindParams.Param> list, DataBind dataBind, StringBuilder bindLog) throws SQLException {
|
||||
|
||||
CallableStatement cstmt = null;
|
||||
|
||||
if (dataBind.getPstmt() instanceof CallableStatement) {
|
||||
cstmt = (CallableStatement) dataBind.getPstmt();
|
||||
}
|
||||
|
||||
// the iterator is assumed to be in the correct order
|
||||
Object value = null;
|
||||
try {
|
||||
for (BindParams.Param param : list) {
|
||||
|
||||
if (param.isOutParam() && cstmt != null) {
|
||||
cstmt.registerOutParameter(dataBind.nextPos(), param.getType());
|
||||
if (param.isInParam()) {
|
||||
dataBind.decrementPos();
|
||||
}
|
||||
}
|
||||
if (param.isInParam()) {
|
||||
value = param.getInValue();
|
||||
if (bindLog != null) {
|
||||
if (bindLog.length() > 0) {
|
||||
bindLog.append(", ");
|
||||
}
|
||||
if (param.isEncryptionKey()) {
|
||||
bindLog.append("****");
|
||||
} else {
|
||||
bindLog.append(value);
|
||||
}
|
||||
}
|
||||
if (value == null) {
|
||||
// this doesn't work for query predicates
|
||||
bindObject(dataBind, null, param.getType());
|
||||
} else {
|
||||
bindObject(dataBind, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (SQLException ex) {
|
||||
logger.warn(Message.msg("fetch.bind.error", "" + (dataBind.currentPos() - 1), value));
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind an Object with unknown data type.
|
||||
*/
|
||||
public Object bindObject(DataBind dataBind, Object value) throws SQLException {
|
||||
|
||||
if (value == null) {
|
||||
// null of unknown type
|
||||
bindObject(dataBind, null, Types.OTHER);
|
||||
return null;
|
||||
|
||||
} else {
|
||||
|
||||
ScalarType<?> type = typeManager.getScalarType(value.getClass());
|
||||
if (type == null) {
|
||||
// the type is not registered with the TypeManager.
|
||||
String msg = "No ScalarType registered for " + value.getClass();
|
||||
throw new PersistenceException(msg);
|
||||
|
||||
} else if (!type.isJdbcNative()) {
|
||||
// convert to a JDBC native type
|
||||
value = type.toJdbcType(value);
|
||||
}
|
||||
|
||||
int dbType = type.getJdbcType();
|
||||
bindObject(dataBind, value, dbType);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* bind a single value.
|
||||
* <p>
|
||||
* Note that java.math.BigInteger is supported by converting it to a Long.
|
||||
* </p>
|
||||
* <p>
|
||||
* Note if we get a java.util.Date or java.util.Calendar then these have
|
||||
* been anonymously passed in (UpdateSql etc). There is a global setting to
|
||||
* convert then to a java.sql.Date or java.sql.Timestamp for binding. The
|
||||
* default is that both are converted to java.sql.Timestamp.
|
||||
* </p>
|
||||
*/
|
||||
public void bindObject(DataBind dataBind, Object data, int dbType) throws SQLException {
|
||||
|
||||
if (data == null) {
|
||||
dataBind.setNull(dbType);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (dbType) {
|
||||
case java.sql.Types.LONGVARCHAR:
|
||||
bindLongVarChar(dataBind, data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.LONGVARBINARY:
|
||||
bindLongVarBinary(dataBind, data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.CLOB:
|
||||
bindClob(dataBind, data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.BLOB:
|
||||
bindBlob(dataBind, data);
|
||||
break;
|
||||
|
||||
default:
|
||||
bindSimpleData(dataBind, dbType, data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds the value to the statement according to the data type.
|
||||
*/
|
||||
private void bindSimpleData(DataBind b, int dataType, Object data) {
|
||||
|
||||
try {
|
||||
switch (dataType) {
|
||||
case java.sql.Types.BOOLEAN:
|
||||
b.setBoolean((Boolean) data);
|
||||
break;
|
||||
case java.sql.Types.BIT:
|
||||
// Types.BIT should map to Java Boolean
|
||||
b.setBoolean((Boolean) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.VARCHAR:
|
||||
b.setString((String) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.CHAR:
|
||||
b.setString(data.toString());
|
||||
break;
|
||||
|
||||
case java.sql.Types.TINYINT:
|
||||
b.setByte((Byte) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.SMALLINT:
|
||||
b.setShort((Short) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.INTEGER:
|
||||
b.setInt((Integer) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.BIGINT:
|
||||
b.setLong((Long) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.REAL:
|
||||
b.setFloat((Float) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.FLOAT:
|
||||
// DB Float in theory maps to Java Double type
|
||||
b.setDouble((Double) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.DOUBLE:
|
||||
b.setDouble((Double) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.NUMERIC:
|
||||
b.setBigDecimal((BigDecimal) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.DECIMAL:
|
||||
b.setBigDecimal((BigDecimal) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.TIME:
|
||||
b.setTime((java.sql.Time) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.DATE:
|
||||
b.setDate((java.sql.Date) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.TIMESTAMP:
|
||||
b.setTimestamp((java.sql.Timestamp) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.BINARY:
|
||||
b.setBytes((byte[]) data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.VARBINARY:
|
||||
b.setBytes((byte[]) data);
|
||||
break;
|
||||
|
||||
case DbPlatformType.UUID:
|
||||
// native UUID support in H2 and Postgres
|
||||
b.setObject(data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.OTHER:
|
||||
b.setObject(data);
|
||||
break;
|
||||
|
||||
case java.sql.Types.JAVA_OBJECT:
|
||||
// Not too sure about this.
|
||||
b.setObject(data);
|
||||
break;
|
||||
|
||||
default:
|
||||
String msg = Message.msg("persist.bind.datatype", "" + dataType, "" + b.currentPos());
|
||||
throw new SQLException(msg);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
String dataClass = "Data is null?";
|
||||
if (data != null) {
|
||||
dataClass = data.getClass().getName();
|
||||
}
|
||||
String m = "Error with property[" + b.currentPos() + "] dt[" + dataType + "]";
|
||||
m += "data[" + data + "][" + dataClass + "]";
|
||||
throw new PersistenceException(m, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind String data to a LONGVARCHAR column.
|
||||
*/
|
||||
private void bindLongVarChar(DataBind dataBind, Object data) throws SQLException {
|
||||
|
||||
dataBind.setClob((String) data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind byte[] data to a LONGVARBINARY column.
|
||||
*/
|
||||
private void bindLongVarBinary(DataBind dataBind, Object data) throws SQLException {
|
||||
|
||||
dataBind.setBlob((byte[]) data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind String data to a CLOB column.
|
||||
*/
|
||||
private void bindClob(DataBind dataBind, Object data) throws SQLException {
|
||||
|
||||
dataBind.setClob((String) data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind byte[] data to a BLOB column.
|
||||
*/
|
||||
private void bindBlob(DataBind dataBind, Object data) throws SQLException {
|
||||
|
||||
dataBind.setBlob((byte[]) data);
|
||||
}
|
||||
|
||||
private boolean isLob(int dbType) {
|
||||
switch (dbType) {
|
||||
case Types.CLOB:
|
||||
return true;
|
||||
case Types.LONGVARCHAR:
|
||||
return true;
|
||||
case Types.BLOB:
|
||||
return true;
|
||||
case Types.LONGVARBINARY:
|
||||
return true;
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the DB platform specific expression handler (for JSON and ARRAY types).
|
||||
*/
|
||||
public DbExpressionHandler getDbExpressionHandler() {
|
||||
return dbExpressionHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and return a DataBind for the statement.
|
||||
*/
|
||||
public DataBind dataBind(PreparedStatement stmt, Connection connection) {
|
||||
return new DataBind(dataTimeZone, stmt, connection);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.server.core.PersistRequestCallableSql;
|
||||
import io.ebeaninternal.server.core.PersistRequestOrmUpdate;
|
||||
import io.ebeaninternal.server.core.PersistRequestUpdateSql;
|
||||
|
||||
/**
|
||||
* Default PersistExecute implementation using DML statements.
|
||||
* <p>
|
||||
* Supports the use of PreparedStatement batching.
|
||||
* </p>
|
||||
*/
|
||||
final class DefaultPersistExecute implements PersistExecute {
|
||||
|
||||
private final ExeCallableSql exeCallableSql;
|
||||
|
||||
private final ExeUpdateSql exeUpdateSql;
|
||||
|
||||
private final ExeOrmUpdate exeOrmUpdate;
|
||||
|
||||
/**
|
||||
* The default batch size.
|
||||
*/
|
||||
private final int defaultBatchSize;
|
||||
|
||||
/**
|
||||
* Construct this DmlPersistExecute.
|
||||
*/
|
||||
DefaultPersistExecute(Binder binder, int defaultBatchSize) {
|
||||
|
||||
this.exeOrmUpdate = new ExeOrmUpdate(binder);
|
||||
this.exeUpdateSql = new ExeUpdateSql(binder);
|
||||
this.exeCallableSql = new ExeCallableSql(binder);
|
||||
this.defaultBatchSize = defaultBatchSize;
|
||||
}
|
||||
|
||||
public BatchControl createBatchControl(SpiTransaction t) {
|
||||
|
||||
// create a BatchControl and set its defaults
|
||||
return new BatchControl(t, defaultBatchSize, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the updateSqlRequest
|
||||
*/
|
||||
public int executeOrmUpdate(PersistRequestOrmUpdate request) {
|
||||
return exeOrmUpdate.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the updateSqlRequest
|
||||
*/
|
||||
public int executeSqlUpdate(PersistRequestUpdateSql request) {
|
||||
return exeUpdateSql.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the CallableSqlRequest.
|
||||
*/
|
||||
public int executeSqlCallable(PersistRequestCallableSql request) {
|
||||
return exeCallableSql.execute(request);
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,100 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebean.PersistenceContextScope;
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import io.ebeaninternal.api.SpiQuery;
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import io.ebeaninternal.server.transaction.DefaultPersistenceContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Used for deletion of a partially populated bean where some cascade delete
|
||||
* properties where not loaded.
|
||||
* <p>
|
||||
* This bean effectively holds the foreign properties that where not loaded, and
|
||||
* helps fetch the foreign keys and delete the appropriate rows.
|
||||
* </p>
|
||||
*/
|
||||
class DeleteUnloadedForeignKeys {
|
||||
|
||||
private final List<BeanPropertyAssocOne<?>> propList = new ArrayList<>(4);
|
||||
|
||||
private final SpiEbeanServer server;
|
||||
|
||||
private final PersistRequestBean<?> request;
|
||||
|
||||
private final boolean deletePermanent;
|
||||
|
||||
private EntityBean beanWithForeignKeys;
|
||||
|
||||
DeleteUnloadedForeignKeys(SpiEbeanServer server, PersistRequestBean<?> request) {
|
||||
this.server = server;
|
||||
this.request = request;
|
||||
this.deletePermanent = request.isHardDeleteCascade();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return propList.isEmpty();
|
||||
}
|
||||
|
||||
public void add(BeanPropertyAssocOne<?> prop) {
|
||||
propList.add(prop);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a query fetching the missing (unloaded) foreign keys. We need to
|
||||
* fetch these key values before the parent bean is deleted.
|
||||
*/
|
||||
void queryForeignKeys() {
|
||||
|
||||
BeanDescriptor<?> descriptor = request.getBeanDescriptor();
|
||||
SpiQuery<?> q = (SpiQuery<?>) server.createQuery(descriptor.getBeanType());
|
||||
|
||||
Object id = request.getBeanId();
|
||||
|
||||
StringBuilder sb = new StringBuilder(30);
|
||||
for (BeanPropertyAssocOne<?> aPropList : propList) {
|
||||
sb.append(aPropList.getName()).append(",");
|
||||
}
|
||||
|
||||
// run query in a separate persistence context
|
||||
q.setPersistenceContext(new DefaultPersistenceContext());
|
||||
q.setPersistenceContextScope(PersistenceContextScope.QUERY);
|
||||
q.setAutoTune(false);
|
||||
q.select(sb.toString());
|
||||
q.setIncludeSoftDeletes();
|
||||
q.where().idEq(id);
|
||||
|
||||
SpiTransaction t = request.getTransaction();
|
||||
if (t.isLogSummary()) {
|
||||
t.logSummary("-- Ebean fetching foreign key values for delete of " + descriptor.getName() + " id:" + id);
|
||||
}
|
||||
beanWithForeignKeys = (EntityBean) server.findUnique(q, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the rows relating to the foreign keys. These deletions occur after
|
||||
* the parent bean has been deleted.
|
||||
*/
|
||||
void deleteCascade() {
|
||||
|
||||
for (BeanPropertyAssocOne<?> prop : propList) {
|
||||
Object detailBean = prop.getValue(beanWithForeignKeys);
|
||||
|
||||
// if bean exists with a unique id then delete it
|
||||
if (detailBean != null && prop.hasId((EntityBean) detailBean)) {
|
||||
if (deletePermanent) {
|
||||
server.deletePermanent(detailBean, request.getTransaction());
|
||||
} else {
|
||||
server.delete(detailBean, request.getTransaction());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
|
||||
/**
|
||||
* Utility object with helper methods for DML.
|
||||
*/
|
||||
public class DmlUtil {
|
||||
|
||||
/**
|
||||
* Return true if the value is null or a Numeric 0 (for primitive int's and long's) or Option empty.
|
||||
*/
|
||||
public static boolean isNullOrZero(Object value) {
|
||||
return value == null || value instanceof Number && ((Number) value).longValue() == 0L;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebeaninternal.api.BindParams;
|
||||
import io.ebeaninternal.api.SpiCallableSql;
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.server.core.PersistRequestCallableSql;
|
||||
import io.ebeaninternal.server.util.BindParamsParser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Handles the execution of CallableSql requests.
|
||||
*/
|
||||
public class ExeCallableSql {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ExeCallableSql.class);
|
||||
|
||||
private final Binder binder;
|
||||
|
||||
private final PstmtFactory pstmtFactory;
|
||||
|
||||
public ExeCallableSql(Binder binder) {
|
||||
this.binder = binder;
|
||||
this.pstmtFactory = new PstmtFactory();
|
||||
}
|
||||
|
||||
/**
|
||||
* execute the CallableSql requests.
|
||||
*/
|
||||
public int execute(PersistRequestCallableSql request) {
|
||||
|
||||
boolean batchThisRequest = request.isBatchThisRequest();
|
||||
|
||||
CallableStatement cstmt = null;
|
||||
try {
|
||||
cstmt = bindStmt(request, batchThisRequest);
|
||||
if (batchThisRequest) {
|
||||
cstmt.addBatch();
|
||||
// return -1 to indicate batch mode
|
||||
return -1;
|
||||
} else {
|
||||
// handles executeOverride() and also
|
||||
// reading of registered OUT parameters
|
||||
int rowCount = request.executeUpdate();
|
||||
request.postExecute();
|
||||
return rowCount;
|
||||
}
|
||||
|
||||
} catch (SQLException ex) {
|
||||
throw new PersistenceException(ex);
|
||||
|
||||
} finally {
|
||||
if (!batchThisRequest && cstmt != null) {
|
||||
try {
|
||||
cstmt.close();
|
||||
} catch (SQLException e) {
|
||||
logger.error(null, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private CallableStatement bindStmt(PersistRequestCallableSql request, boolean batchThisRequest) throws SQLException {
|
||||
|
||||
SpiCallableSql callableSql = request.getCallableSql();
|
||||
SpiTransaction t = request.getTransaction();
|
||||
|
||||
String sql = callableSql.getSql();
|
||||
|
||||
BindParams bindParams = callableSql.getBindParams();
|
||||
|
||||
// process named parameters if required
|
||||
sql = BindParamsParser.parse(bindParams, sql);
|
||||
|
||||
boolean logSql = request.isLogSql();
|
||||
|
||||
CallableStatement cstmt;
|
||||
if (batchThisRequest) {
|
||||
cstmt = pstmtFactory.getCstmt(t, logSql, sql, request);
|
||||
} else {
|
||||
if (logSql) {
|
||||
t.logSql(sql);
|
||||
}
|
||||
cstmt = pstmtFactory.getCstmt(t, sql);
|
||||
}
|
||||
|
||||
if (callableSql.getTimeout() > 0) {
|
||||
cstmt.setQueryTimeout(callableSql.getTimeout());
|
||||
}
|
||||
|
||||
String bindLog = null;
|
||||
if (!bindParams.isEmpty()) {
|
||||
bindLog = binder.bind(bindParams, cstmt, t.getInternalConnection());
|
||||
}
|
||||
|
||||
request.setBindLog(bindLog);
|
||||
|
||||
// required to read OUT params later
|
||||
request.setBound(bindParams, cstmt);
|
||||
return cstmt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebeaninternal.api.BindParams;
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.api.SpiUpdate;
|
||||
import io.ebeaninternal.server.core.PersistRequestOrmUpdate;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.util.BindParamsParser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Executes the UpdateSql requests.
|
||||
*/
|
||||
public class ExeOrmUpdate {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ExeOrmUpdate.class);
|
||||
|
||||
private final Binder binder;
|
||||
|
||||
private final PstmtFactory pstmtFactory;
|
||||
|
||||
/**
|
||||
* Create with a given binder.
|
||||
*/
|
||||
public ExeOrmUpdate(Binder binder) {
|
||||
this.pstmtFactory = new PstmtFactory();
|
||||
this.binder = binder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the orm update request.
|
||||
*/
|
||||
public int execute(PersistRequestOrmUpdate request) {
|
||||
|
||||
boolean batchThisRequest = request.isBatchThisRequest();
|
||||
|
||||
PreparedStatement pstmt = null;
|
||||
try {
|
||||
pstmt = bindStmt(request, batchThisRequest);
|
||||
if (batchThisRequest) {
|
||||
pstmt.addBatch();
|
||||
// return -1 to indicate batch mode
|
||||
return -1;
|
||||
} else {
|
||||
SpiUpdate<?> ormUpdate = request.getOrmUpdate();
|
||||
if (ormUpdate.getTimeout() > 0) {
|
||||
pstmt.setQueryTimeout(ormUpdate.getTimeout());
|
||||
}
|
||||
int rowCount = pstmt.executeUpdate();
|
||||
request.checkRowCount(rowCount);
|
||||
request.postExecute();
|
||||
return rowCount;
|
||||
}
|
||||
|
||||
} catch (SQLException ex) {
|
||||
throw new PersistenceException("Error executing: " + request.getOrmUpdate().getGeneratedSql(), ex);
|
||||
|
||||
} finally {
|
||||
if (!batchThisRequest && pstmt != null) {
|
||||
try {
|
||||
pstmt.close();
|
||||
} catch (SQLException e) {
|
||||
logger.error(null, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert bean and property names to db table and columns.
|
||||
*/
|
||||
private String translate(PersistRequestOrmUpdate request, String sql) {
|
||||
|
||||
BeanDescriptor<?> descriptor = request.getBeanDescriptor();
|
||||
return descriptor.convertOrmUpdateToSql(sql);
|
||||
}
|
||||
|
||||
private PreparedStatement bindStmt(PersistRequestOrmUpdate request, boolean batchThisRequest) throws SQLException {
|
||||
|
||||
SpiUpdate<?> ormUpdate = request.getOrmUpdate();
|
||||
SpiTransaction t = request.getTransaction();
|
||||
|
||||
String sql = ormUpdate.getUpdateStatement();
|
||||
|
||||
// convert bean and property names to table and
|
||||
// column names if required
|
||||
sql = translate(request, sql);
|
||||
|
||||
BindParams bindParams = ormUpdate.getBindParams();
|
||||
|
||||
// process named parameters if required
|
||||
sql = BindParamsParser.parse(bindParams, sql);
|
||||
|
||||
ormUpdate.setGeneratedSql(sql);
|
||||
|
||||
boolean logSql = request.isLogSql();
|
||||
|
||||
PreparedStatement pstmt;
|
||||
if (batchThisRequest) {
|
||||
pstmt = pstmtFactory.getPstmt(t, logSql, sql, request);
|
||||
} else {
|
||||
if (logSql) {
|
||||
t.logSql(sql);
|
||||
}
|
||||
pstmt = pstmtFactory.getPstmt(t, sql);
|
||||
}
|
||||
|
||||
String bindLog = null;
|
||||
if (!bindParams.isEmpty()) {
|
||||
bindLog = binder.bind(bindParams, pstmt, t.getInternalConnection());
|
||||
}
|
||||
|
||||
request.setBindLog(bindLog);
|
||||
return pstmt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebeaninternal.api.BindParams;
|
||||
import io.ebeaninternal.api.SpiSqlUpdate;
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.server.core.PersistRequestUpdateSql;
|
||||
import io.ebeaninternal.server.core.PersistRequestUpdateSql.SqlType;
|
||||
import io.ebeaninternal.server.util.BindParamsParser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Executes the UpdateSql requests.
|
||||
*/
|
||||
public class ExeUpdateSql {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ExeUpdateSql.class);
|
||||
|
||||
private final Binder binder;
|
||||
|
||||
private final PstmtFactory pstmtFactory;
|
||||
|
||||
/**
|
||||
* Create with a given binder.
|
||||
*/
|
||||
public ExeUpdateSql(Binder binder) {
|
||||
this.binder = binder;
|
||||
this.pstmtFactory = new PstmtFactory();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the UpdateSql request.
|
||||
*/
|
||||
public int execute(PersistRequestUpdateSql request) {
|
||||
|
||||
boolean batchThisRequest = request.isBatchThisRequest();
|
||||
|
||||
PreparedStatement pstmt = null;
|
||||
try {
|
||||
|
||||
pstmt = bindStmt(request, batchThisRequest);
|
||||
|
||||
if (batchThisRequest) {
|
||||
pstmt.addBatch();
|
||||
// return -1 to indicate batch mode
|
||||
return -1;
|
||||
} else {
|
||||
int rowCount = pstmt.executeUpdate();
|
||||
request.checkRowCount(rowCount);
|
||||
request.postExecute();
|
||||
return rowCount;
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
throw new PersistenceException(ex);
|
||||
|
||||
} finally {
|
||||
if (!batchThisRequest && pstmt != null) {
|
||||
try {
|
||||
pstmt.close();
|
||||
} catch (SQLException e) {
|
||||
logger.error(null, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PreparedStatement bindStmt(PersistRequestUpdateSql request, boolean batchThisRequest) throws SQLException {
|
||||
|
||||
SpiSqlUpdate updateSql = request.getUpdateSql();
|
||||
SpiTransaction t = request.getTransaction();
|
||||
|
||||
String sql = updateSql.getSql();
|
||||
|
||||
BindParams bindParams = updateSql.getBindParams();
|
||||
|
||||
// process named parameters if required
|
||||
sql = BindParamsParser.parse(bindParams, sql);
|
||||
updateSql.setGeneratedSql(sql);
|
||||
|
||||
boolean logSql = request.isLogSql();
|
||||
|
||||
PreparedStatement pstmt;
|
||||
if (batchThisRequest) {
|
||||
pstmt = pstmtFactory.getPstmt(t, logSql, sql, request);
|
||||
} else {
|
||||
if (logSql) {
|
||||
t.logSql(sql);
|
||||
}
|
||||
pstmt = pstmtFactory.getPstmt(t, sql);
|
||||
}
|
||||
|
||||
if (updateSql.getTimeout() > 0) {
|
||||
pstmt.setQueryTimeout(updateSql.getTimeout());
|
||||
}
|
||||
|
||||
String bindLog = null;
|
||||
if (!bindParams.isEmpty()) {
|
||||
bindLog = binder.bind(bindParams, pstmt, t.getInternalConnection());
|
||||
}
|
||||
|
||||
request.setBindLog(bindLog);
|
||||
|
||||
// derive the statement type (for TransactionEvent)
|
||||
parseUpdate(sql, request);
|
||||
return pstmt;
|
||||
}
|
||||
|
||||
|
||||
private void determineType(String word1, String word2, String word3, PersistRequestUpdateSql request) {
|
||||
|
||||
if (word1.equalsIgnoreCase("UPDATE")) {
|
||||
request.setType(SqlType.SQL_UPDATE, word2, "UpdateSql");
|
||||
|
||||
} else if (word1.equalsIgnoreCase("DELETE")) {
|
||||
request.setType(SqlType.SQL_DELETE, word3, "DeleteSql");
|
||||
|
||||
} else if (word1.equalsIgnoreCase("INSERT")) {
|
||||
request.setType(SqlType.SQL_INSERT, word3, "InsertSql");
|
||||
|
||||
} else {
|
||||
request.setType(SqlType.SQL_UNKNOWN, null, "UnknownSql");
|
||||
}
|
||||
}
|
||||
|
||||
private void parseUpdate(String sql, PersistRequestUpdateSql request) {
|
||||
|
||||
int start = leadingTrim(sql);
|
||||
|
||||
int[] pos = new int[3];
|
||||
int spaceCount = 0;
|
||||
|
||||
int len = sql.length();
|
||||
for (int i = start; i < len; i++) {
|
||||
char c = sql.charAt(i);
|
||||
if (Character.isWhitespace(c)) {
|
||||
pos[spaceCount] = i;
|
||||
spaceCount++;
|
||||
if (spaceCount > 2) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String firstWord = sql.substring(0, pos[0]);
|
||||
String secWord = sql.substring(pos[0] + 1, pos[1]);
|
||||
String thirdWord;
|
||||
if (pos[2] == 0) {
|
||||
// there is nothing after the table name
|
||||
thirdWord = sql.substring(pos[1] + 1);
|
||||
} else {
|
||||
thirdWord = sql.substring(pos[1] + 1, pos[2]);
|
||||
}
|
||||
|
||||
determineType(firstWord, secWord, thirdWord, request);
|
||||
}
|
||||
|
||||
private int leadingTrim(String s) {
|
||||
int len = s.length();
|
||||
int i;
|
||||
for (i = 0; i < len; i++) {
|
||||
if (!Character.isWhitespace(s.charAt(i))) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.server.core.PersistRequestCallableSql;
|
||||
import io.ebeaninternal.server.core.PersistRequestOrmUpdate;
|
||||
import io.ebeaninternal.server.core.PersistRequestUpdateSql;
|
||||
|
||||
/**
|
||||
* The actual execution of persist requests.
|
||||
* <p>
|
||||
* A Persister 'front-ends' this object and handles the
|
||||
* batching, cascading, concurrency mode detection etc.
|
||||
* </p>
|
||||
*/
|
||||
public interface PersistExecute {
|
||||
|
||||
/**
|
||||
* Create a BatchControl for the current transaction.
|
||||
*/
|
||||
BatchControl createBatchControl(SpiTransaction t);
|
||||
|
||||
/**
|
||||
* Execute a Update.
|
||||
*/
|
||||
int executeOrmUpdate(PersistRequestOrmUpdate request);
|
||||
|
||||
/**
|
||||
* Execute a CallableSql.
|
||||
*/
|
||||
int executeSqlCallable(PersistRequestCallableSql request);
|
||||
|
||||
/**
|
||||
* Execute a UpdateSql.
|
||||
*/
|
||||
int executeSqlUpdate(PersistRequestUpdateSql request);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package io.ebeaninternal.server.persist;
|
||||
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Factory for creating Statements.
|
||||
* <p>
|
||||
* This is only used by CallableSql and UpdateSql requests and does not support
|
||||
* getGeneratedKeys.
|
||||
* </p>
|
||||
*/
|
||||
public class PstmtFactory {
|
||||
|
||||
public PstmtFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a callable statement without any batching.
|
||||
*/
|
||||
public CallableStatement getCstmt(SpiTransaction t, String sql) throws SQLException {
|
||||
Connection conn = t.getInternalConnection();
|
||||
return conn.prepareCall(sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a prepared statement without any batching.
|
||||
*/
|
||||
public PreparedStatement getPstmt(SpiTransaction t, String sql) throws SQLException {
|
||||
Connection conn = t.getInternalConnection();
|
||||
return conn.prepareStatement(sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a prepared statement taking into account batch requirements.
|
||||
*/
|
||||
public PreparedStatement getPstmt(SpiTransaction t, boolean logSql, String sql, BatchPostExecute batchExe) throws SQLException {
|
||||
|
||||
BatchedPstmtHolder batch = t.getBatchControl().getPstmtHolder();
|
||||
PreparedStatement stmt = batch.getStmt(sql, batchExe);
|
||||
|
||||
if (stmt != null) {
|
||||
return stmt;
|
||||
}
|
||||
|
||||
if (logSql) {
|
||||
t.logSql(sql);
|
||||
}
|
||||
|
||||
Connection conn = t.getInternalConnection();
|
||||
stmt = conn.prepareStatement(sql);
|
||||
|
||||
BatchedPstmt bs = new BatchedPstmt(stmt, false, sql);
|
||||
batch.addStmt(bs, batchExe);
|
||||
return stmt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a callable statement taking into account batch requirements.
|
||||
*/
|
||||
public CallableStatement getCstmt(SpiTransaction t, boolean logSql, String sql, BatchPostExecute batchExe) throws SQLException {
|
||||
|
||||
BatchedPstmtHolder batch = t.getBatchControl().getPstmtHolder();
|
||||
CallableStatement stmt = (CallableStatement) batch.getStmt(sql, batchExe);
|
||||
|
||||
if (stmt != null) {
|
||||
return stmt;
|
||||
}
|
||||
|
||||
if (logSql) {
|
||||
t.logSql(sql);
|
||||
}
|
||||
|
||||
Connection conn = t.getInternalConnection();
|
||||
stmt = conn.prepareCall(sql);
|
||||
|
||||
BatchedPstmt bs = new BatchedPstmt(stmt, false, sql);
|
||||
batch.addStmt(bs, batchExe);
|
||||
return stmt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
|
||||
import javax.persistence.OptimisticLockException;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Delete bean handler.
|
||||
*/
|
||||
public class DeleteHandler extends DmlHandler {
|
||||
|
||||
private final DeleteMeta meta;
|
||||
|
||||
public DeleteHandler(PersistRequestBean<?> persist, DeleteMeta meta) {
|
||||
super(persist, meta.isEmptyStringAsNull());
|
||||
this.meta = meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and bind the delete statement.
|
||||
*/
|
||||
@Override
|
||||
public void bind() throws SQLException {
|
||||
|
||||
sql = meta.getSql(persistRequest);
|
||||
SpiTransaction t = persistRequest.getTransaction();
|
||||
|
||||
PreparedStatement pstmt;
|
||||
if (persistRequest.isBatched()) {
|
||||
pstmt = getPstmt(t, sql, persistRequest, false);
|
||||
} else {
|
||||
pstmt = getPstmt(t, sql, false);
|
||||
}
|
||||
dataBind = bind(pstmt);
|
||||
meta.bind(persistRequest, this);
|
||||
logSql(sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the delete non-batch.
|
||||
*/
|
||||
@Override
|
||||
public int execute() throws SQLException, OptimisticLockException {
|
||||
int rowCount = dataBind.executeUpdate();
|
||||
checkRowCount(rowCount);
|
||||
return rowCount;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.api.ConcurrencyMode;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.persist.dmlbind.Bindable;
|
||||
import io.ebeaninternal.server.persist.dmlbind.BindableId;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Meta data for delete handler. The meta data is for a particular bean type. It
|
||||
* is considered immutable and is thread safe.
|
||||
*/
|
||||
public final class DeleteMeta {
|
||||
|
||||
private final String sqlVersion;
|
||||
private final String sqlNone;
|
||||
private final String sqlDraftVersion;
|
||||
private final String sqlDraftNone;
|
||||
|
||||
private final BindableId id;
|
||||
|
||||
private final Bindable version;
|
||||
|
||||
private final String tableName;
|
||||
|
||||
private final boolean emptyStringAsNull;
|
||||
|
||||
public DeleteMeta(boolean emptyStringAsNull, BeanDescriptor<?> desc, BindableId id, Bindable version) {
|
||||
this.emptyStringAsNull = emptyStringAsNull;
|
||||
this.tableName = desc.getBaseTable();
|
||||
this.id = id;
|
||||
this.version = version;
|
||||
|
||||
String tableName = desc.getBaseTable();
|
||||
this.sqlNone = genSql(ConcurrencyMode.NONE, tableName);
|
||||
this.sqlVersion = genSql(ConcurrencyMode.VERSION, tableName);
|
||||
if (desc.isDraftable()) {
|
||||
String draftTableName = desc.getDraftTable();
|
||||
this.sqlDraftNone = genSql(ConcurrencyMode.NONE, draftTableName);
|
||||
this.sqlDraftVersion = genSql(ConcurrencyMode.VERSION, draftTableName);
|
||||
|
||||
} else {
|
||||
this.sqlDraftNone = sqlNone;
|
||||
this.sqlDraftVersion = sqlVersion;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEmptyStringAsNull() {
|
||||
return emptyStringAsNull;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the table name.
|
||||
*/
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the request based on the concurrency mode.
|
||||
*/
|
||||
public void bind(PersistRequestBean<?> persist, DmlHandler bind) throws SQLException {
|
||||
|
||||
EntityBean bean = persist.getEntityBean();
|
||||
|
||||
id.dmlBind(bind, bean);
|
||||
|
||||
switch (persist.getConcurrencyMode()) {
|
||||
case VERSION:
|
||||
version.dmlBind(bind, bean);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* get or generate the sql based on the concurrency mode.
|
||||
*/
|
||||
public String getSql(PersistRequestBean<?> request) {
|
||||
|
||||
if (id.isEmpty()) {
|
||||
throw new IllegalStateException("Can not deleteById on " + request.getFullName() + " as no @Id property");
|
||||
}
|
||||
|
||||
boolean publish = request.isPublish();
|
||||
switch (request.determineConcurrencyMode()) {
|
||||
case NONE:
|
||||
return publish ? sqlNone : sqlDraftNone;
|
||||
|
||||
case VERSION:
|
||||
return publish ? sqlVersion : sqlDraftVersion;
|
||||
|
||||
default:
|
||||
throw new RuntimeException("Invalid mode " + request.determineConcurrencyMode());
|
||||
}
|
||||
}
|
||||
|
||||
private String genSql(ConcurrencyMode conMode, String table) {
|
||||
|
||||
// delete ... where bcol=? and bc1=? and bc2 is null and ...
|
||||
|
||||
GenerateDmlRequest request = new GenerateDmlRequest();
|
||||
|
||||
request.append("delete from ").append(table);
|
||||
request.append(" where ");
|
||||
|
||||
request.setWhereIdMode();
|
||||
id.dmlAppend(request);
|
||||
|
||||
if (ConcurrencyMode.VERSION.equals(conMode)) {
|
||||
if (version == null) {
|
||||
return null;
|
||||
}
|
||||
version.dmlAppend(request);
|
||||
}
|
||||
|
||||
return request.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.lib.util.StringHelper;
|
||||
import io.ebeaninternal.server.persist.BeanPersister;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Bean persister that uses the Handler and Meta objects.
|
||||
* <p>
|
||||
* The design of this is based on the immutable Meta objects. They hold a
|
||||
* information in the form of lists of Bindable objects. This effectively
|
||||
* flattens the structure of the bean with embedded and associated objects into
|
||||
* a flat list of Bindable objects.
|
||||
* </p>
|
||||
*/
|
||||
public final class DmlBeanPersister implements BeanPersister {
|
||||
|
||||
private final UpdateMeta updateMeta;
|
||||
|
||||
private final InsertMeta insertMeta;
|
||||
|
||||
private final DeleteMeta deleteMeta;
|
||||
|
||||
|
||||
public DmlBeanPersister(UpdateMeta updateMeta, InsertMeta insertMeta, DeleteMeta deleteMeta) {
|
||||
|
||||
this.updateMeta = updateMeta;
|
||||
this.insertMeta = insertMeta;
|
||||
this.deleteMeta = deleteMeta;
|
||||
}
|
||||
|
||||
/**
|
||||
* execute the bean delete request.
|
||||
*/
|
||||
public int delete(PersistRequestBean<?> request) {
|
||||
|
||||
DeleteHandler delete = new DeleteHandler(request, deleteMeta);
|
||||
return execute(request, delete);
|
||||
}
|
||||
|
||||
/**
|
||||
* execute the bean insert request.
|
||||
*/
|
||||
public void insert(PersistRequestBean<?> request) {
|
||||
|
||||
InsertHandler insert = new InsertHandler(request, insertMeta);
|
||||
execute(request, insert);
|
||||
}
|
||||
|
||||
/**
|
||||
* execute the bean update request.
|
||||
*/
|
||||
public void update(PersistRequestBean<?> request) {
|
||||
|
||||
UpdateHandler update = new UpdateHandler(request, updateMeta);
|
||||
execute(request, update);
|
||||
}
|
||||
|
||||
/**
|
||||
* execute request taking batching into account.
|
||||
*/
|
||||
private int execute(PersistRequestBean<?> request, PersistHandler handler) {
|
||||
|
||||
boolean batched = request.isBatched();
|
||||
try {
|
||||
handler.bind();
|
||||
if (batched) {
|
||||
handler.addBatch();
|
||||
return -1;
|
||||
|
||||
} else {
|
||||
return handler.execute();
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
// log the error to the transaction log
|
||||
String errMsg = StringHelper.replaceStringMulti(e.getMessage(), new String[]{"\r", "\n"}, "\\n ");
|
||||
String msg = "ERROR executing DML bindLog[" + handler.getBindLog() + "] error[" + errMsg + "]";
|
||||
if (request.getTransaction().isLogSummary()) {
|
||||
request.getTransaction().logSummary(msg);
|
||||
}
|
||||
throw new PersistenceException(msg, e);
|
||||
|
||||
} finally {
|
||||
if (!batched && handler != null) {
|
||||
handler.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebean.config.dbplatform.DatabasePlatform;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.persist.BeanPersister;
|
||||
import io.ebeaninternal.server.persist.BeanPersisterFactory;
|
||||
|
||||
/**
|
||||
* Factory for creating a DmlBeanPersister for a bean type.
|
||||
*/
|
||||
public class DmlBeanPersisterFactory implements BeanPersisterFactory {
|
||||
|
||||
private final MetaFactory metaFactory;
|
||||
|
||||
public DmlBeanPersisterFactory(DatabasePlatform dbPlatform) {
|
||||
this.metaFactory = new MetaFactory(dbPlatform);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a DmlBeanPersister for the given bean type.
|
||||
*/
|
||||
public BeanPersister create(BeanDescriptor<?> desc) {
|
||||
|
||||
if (desc.isDocStoreOnly()) {
|
||||
return new DocStoreBeanPersister(GeneratedProperties.of(desc));
|
||||
}
|
||||
|
||||
UpdateMeta updMeta = metaFactory.createUpdate(desc);
|
||||
DeleteMeta delMeta = metaFactory.createDelete(desc);
|
||||
InsertMeta insMeta = metaFactory.createInsert(desc);
|
||||
return new DmlBeanPersister(updMeta, insMeta, delMeta);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.lib.util.Str;
|
||||
import io.ebeaninternal.server.persist.BatchedPstmt;
|
||||
import io.ebeaninternal.server.persist.BatchedPstmtHolder;
|
||||
import io.ebeaninternal.server.persist.dmlbind.BindableRequest;
|
||||
import io.ebeaninternal.server.transaction.TransactionManager;
|
||||
import io.ebeaninternal.server.type.DataBind;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.persistence.OptimisticLockException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Base class for Handler implementations.
|
||||
*/
|
||||
public abstract class DmlHandler implements PersistHandler, BindableRequest {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DmlHandler.class);
|
||||
|
||||
/**
|
||||
* The originating request.
|
||||
*/
|
||||
protected final PersistRequestBean<?> persistRequest;
|
||||
|
||||
protected final StringBuilder bindLog;
|
||||
|
||||
protected final SpiTransaction transaction;
|
||||
|
||||
protected final boolean emptyStringToNull;
|
||||
|
||||
protected final boolean logLevelSql;
|
||||
|
||||
protected final long now;
|
||||
|
||||
/**
|
||||
* The PreparedStatement used for the dml.
|
||||
*/
|
||||
protected DataBind dataBind;
|
||||
|
||||
protected String sql;
|
||||
|
||||
/**
|
||||
* The generated value for the @Version property. Must be set after where clause is bound.
|
||||
*/
|
||||
protected Object versionValue;
|
||||
|
||||
protected DmlHandler(PersistRequestBean<?> persistRequest, boolean emptyStringToNull) {
|
||||
this.now = System.currentTimeMillis();
|
||||
this.persistRequest = persistRequest;
|
||||
this.emptyStringToNull = emptyStringToNull;
|
||||
this.transaction = persistRequest.getTransaction();
|
||||
this.logLevelSql = transaction.isLogSql();
|
||||
if (logLevelSql) {
|
||||
this.bindLog = new StringBuilder(50);
|
||||
} else {
|
||||
this.bindLog = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long now() {
|
||||
return now;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PersistRequestBean<?> getPersistRequest() {
|
||||
return persistRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind to the statement returning the DataBind.
|
||||
*/
|
||||
protected DataBind bind(PreparedStatement stmt) {
|
||||
return new DataBind(persistRequest.getDataTimeZone(), stmt, transaction.getInternalConnection());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the sql and bind the statement.
|
||||
*/
|
||||
@Override
|
||||
public abstract void bind() throws SQLException;
|
||||
|
||||
/**
|
||||
* Execute now for non-batch execution.
|
||||
*/
|
||||
@Override
|
||||
public abstract int execute() throws SQLException;
|
||||
|
||||
/**
|
||||
* Check the rowCount.
|
||||
*/
|
||||
protected void checkRowCount(int rowCount) throws OptimisticLockException {
|
||||
try {
|
||||
persistRequest.checkRowCount(rowCount);
|
||||
persistRequest.postExecute();
|
||||
} catch (OptimisticLockException e) {
|
||||
// add the SQL and bind values to error message
|
||||
String m = e.getMessage() + " sql[" + sql + "] bind[" + bindLog + "]";
|
||||
persistRequest.getTransaction().logSummary("OptimisticLockException:" + m);
|
||||
throw new OptimisticLockException(m, null, e.getEntity());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add this for batch execution.
|
||||
*/
|
||||
@Override
|
||||
public void addBatch() throws SQLException {
|
||||
dataBind.getPstmt().addBatch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the underlying statement.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
if (dataBind != null) {
|
||||
dataBind.close();
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
logger.error(null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the bind log.
|
||||
*/
|
||||
@Override
|
||||
public String getBindLog() {
|
||||
return bindLog == null ? "" : bindLog.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Id value that was bound. This value is used for logging summary
|
||||
* level information.
|
||||
*/
|
||||
@Override
|
||||
public void setIdValue(Object idValue) {
|
||||
persistRequest.setBoundId(idValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the sql to the transaction log.
|
||||
*/
|
||||
protected void logSql(String sql) {
|
||||
if (logLevelSql) {
|
||||
if (TransactionManager.SQL_LOGGER.isTraceEnabled()) {
|
||||
sql = Str.add(sql, "; --bind(", bindLog.toString(), ")");
|
||||
}
|
||||
transaction.logSql(sql);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind a raw value. Used to bind the discriminator column.
|
||||
*/
|
||||
@Override
|
||||
public void bind(Object value, int sqlType) throws SQLException {
|
||||
if (logLevelSql) {
|
||||
if (bindLog.length() > 0) {
|
||||
bindLog.append(",");
|
||||
}
|
||||
if (value == null) {
|
||||
bindLog.append("null");
|
||||
} else {
|
||||
String sval = value.toString();
|
||||
if (sval.length() > 50) {
|
||||
bindLog.append(sval.substring(0, 47)).append("...");
|
||||
} else {
|
||||
bindLog.append(sval);
|
||||
}
|
||||
}
|
||||
}
|
||||
dataBind.setObject(value, sqlType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void bindNoLog(Object value, int sqlType, String logPlaceHolder) throws SQLException {
|
||||
if (logLevelSql) {
|
||||
bindLog.append(logPlaceHolder).append(" ");
|
||||
}
|
||||
dataBind.setObject(value, sqlType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the value to the preparedStatement.
|
||||
*/
|
||||
@Override
|
||||
public void bind(Object value, BeanProperty prop) throws SQLException {
|
||||
bindInternal(logLevelSql, value, prop);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the value to the preparedStatement without logging.
|
||||
*/
|
||||
@Override
|
||||
public void bindNoLog(Object value, BeanProperty prop) throws SQLException {
|
||||
bindInternal(false, value, prop);
|
||||
}
|
||||
|
||||
private void bindInternal(boolean log, Object value, BeanProperty prop) throws SQLException {
|
||||
|
||||
if (log) {
|
||||
if (bindLog.length() > 0) {
|
||||
bindLog.append(",");
|
||||
}
|
||||
if (prop.isLob()) {
|
||||
bindLog.append("[LOB]");
|
||||
} else {
|
||||
String sv = String.valueOf(value);
|
||||
if (sv.length() > 50) {
|
||||
sv = sv.substring(0, 47) + "...";
|
||||
}
|
||||
bindLog.append(sv);
|
||||
}
|
||||
}
|
||||
// do the actual binding to PreparedStatement
|
||||
prop.bind(dataBind, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a generated value on a update. This can not be set to the bean
|
||||
* until after the where clause has been bound for concurrency checking.
|
||||
* <p>
|
||||
* GeneratedProperty values are likely going to be used for optimistic
|
||||
* concurrency checking. This includes 'counter' and 'update timestamp'
|
||||
* generation.
|
||||
* </p>
|
||||
*/
|
||||
@Override
|
||||
public void registerGeneratedVersion(Object versionValue) {
|
||||
this.versionValue = versionValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set any update generated values to the bean. Must be called after where
|
||||
* clause has been bound.
|
||||
*/
|
||||
public void setUpdateGenValues() {
|
||||
if (versionValue != null) {
|
||||
persistRequest.setVersionValue(versionValue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check with useGeneratedKeys to get appropriate PreparedStatement.
|
||||
*/
|
||||
protected PreparedStatement getPstmt(SpiTransaction t, String sql, boolean genKeys) throws SQLException {
|
||||
|
||||
Connection conn = t.getInternalConnection();
|
||||
if (genKeys) {
|
||||
// the Id generated is always the first column
|
||||
// Required to stop Oracle10 giving us Oracle rowId??
|
||||
// Other jdbc drivers seem fine without this hint.
|
||||
int[] columns = {1};
|
||||
return conn.prepareStatement(sql, columns);
|
||||
|
||||
} else {
|
||||
return conn.prepareStatement(sql);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a prepared statement taking into account batch requirements.
|
||||
*/
|
||||
protected PreparedStatement getPstmt(SpiTransaction t, String sql, PersistRequestBean<?> request,
|
||||
boolean genKeys) throws SQLException {
|
||||
|
||||
BatchedPstmtHolder batch = t.getBatchControl().getPstmtHolder();
|
||||
PreparedStatement stmt = batch.getStmt(sql, request);
|
||||
|
||||
if (stmt != null) {
|
||||
return stmt;
|
||||
}
|
||||
|
||||
stmt = getPstmt(t, sql, genKeys);
|
||||
|
||||
BatchedPstmt bs = new BatchedPstmt(stmt, genKeys, sql);
|
||||
batch.addStmt(bs, request);
|
||||
return stmt;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
/**
|
||||
* Used to indicate the part of DML being processed.
|
||||
*/
|
||||
public enum DmlMode {
|
||||
|
||||
/**
|
||||
* The Insert SET.
|
||||
*/
|
||||
INSERT,
|
||||
|
||||
/**
|
||||
* The Update SET.
|
||||
*/
|
||||
UPDATE,
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.persist.BeanPersister;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
/**
|
||||
* Document store based BeanPersister.
|
||||
*/
|
||||
class DocStoreBeanPersister implements BeanPersister {
|
||||
|
||||
private final GeneratedProperties generatedProperties;
|
||||
|
||||
DocStoreBeanPersister(GeneratedProperties generatedProperties) {
|
||||
this.generatedProperties = generatedProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insert(PersistRequestBean<?> request) throws PersistenceException {
|
||||
//request.setIdValueForDocStore();
|
||||
generatedProperties.preInsert(request.getEntityBean(), request.now());
|
||||
request.docStorePersist();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(PersistRequestBean<?> request) throws PersistenceException {
|
||||
generatedProperties.preUpdate(request.getEntityBean(), request.now());
|
||||
request.docStorePersist();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int delete(PersistRequestBean<?> request) throws PersistenceException {
|
||||
request.docStorePersist();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
/**
|
||||
* Helper to support the generation of DML statements.
|
||||
*/
|
||||
public class GenerateDmlRequest {
|
||||
|
||||
private static final String IS_NULL = " is null";
|
||||
|
||||
private final StringBuilder sb = new StringBuilder(100);
|
||||
|
||||
private StringBuilder insertBindBuffer;
|
||||
|
||||
private String prefix;
|
||||
private String prefix2;
|
||||
|
||||
private int insertMode;
|
||||
|
||||
private int bindColumnCount;
|
||||
|
||||
/**
|
||||
* Create from a PersistRequestBean.
|
||||
*/
|
||||
public GenerateDmlRequest() {
|
||||
}
|
||||
|
||||
public GenerateDmlRequest append(String s) {
|
||||
sb.append(s);
|
||||
return this;
|
||||
}
|
||||
|
||||
public void appendColumnIsNull(String column) {
|
||||
appendColumn(column, IS_NULL);
|
||||
}
|
||||
|
||||
public void appendColumn(String column) {
|
||||
//String bind = (insertMode > 0) ? "?" : "=?";
|
||||
appendColumn(column, "?");
|
||||
}
|
||||
|
||||
public void appendColumn(String column, String bind) {
|
||||
|
||||
++bindColumnCount;
|
||||
|
||||
sb.append(prefix);
|
||||
sb.append(column);
|
||||
//sb.append(expr);
|
||||
if (insertMode > 0) {
|
||||
if (insertMode++ > 1) {
|
||||
insertBindBuffer.append(",");
|
||||
}
|
||||
insertBindBuffer.append(bind);
|
||||
} else {
|
||||
sb.append("=");
|
||||
sb.append(bind);
|
||||
}
|
||||
|
||||
if (prefix2 != null) {
|
||||
prefix = prefix2;
|
||||
prefix2 = null;
|
||||
}
|
||||
}
|
||||
|
||||
public int getBindColumnCount() {
|
||||
return bindColumnCount;
|
||||
}
|
||||
|
||||
public String getInsertBindBuffer() {
|
||||
return insertBindBuffer.toString();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void setWhereIdMode() {
|
||||
this.prefix = "";
|
||||
this.prefix2 = " and ";
|
||||
}
|
||||
|
||||
public void setInsertSetMode() {
|
||||
this.insertBindBuffer = new StringBuilder(100);
|
||||
this.insertMode = 1;
|
||||
this.prefix = "";
|
||||
this.prefix2 = ", ";
|
||||
}
|
||||
|
||||
public void setUpdateSetMode() {
|
||||
this.prefix = "";
|
||||
this.prefix2 = ", ";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.deploy.generatedproperty.GeneratedProperty;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Executes the generated property (like WhenCreated, WhoCreated etc) for doc store persisting.
|
||||
*/
|
||||
class GeneratedProperties {
|
||||
|
||||
/**
|
||||
* Create the GeneratedProperties for the given bean type.
|
||||
*/
|
||||
static GeneratedProperties of(BeanDescriptor<?> desc) {
|
||||
return new GeneratedPropertyCollector(desc).generatedProperties();
|
||||
}
|
||||
|
||||
private final SetValue[] onInsert;
|
||||
private final SetValue[] onUpdate;
|
||||
|
||||
GeneratedProperties(List<BeanProperty> inserts, List<BeanProperty> updates) {
|
||||
this.onInsert = adapt(inserts);
|
||||
this.onUpdate = adapt(updates);
|
||||
}
|
||||
|
||||
private SetValue[] adapt(List<BeanProperty> inserts) {
|
||||
SetValue[] setters = new SetValue[inserts.size()];
|
||||
for (int i = 0; i < inserts.size(); i++) {
|
||||
setters[i] = new SetValue(inserts.get(i));
|
||||
}
|
||||
return setters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set all the generated on insert values.
|
||||
*/
|
||||
public void preInsert(EntityBean bean, long now) {
|
||||
for (SetValue setter : onInsert) {
|
||||
setter.preInsert(bean, now);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set all the generated on update values.
|
||||
*/
|
||||
public void preUpdate(EntityBean bean, long now) {
|
||||
for (SetValue setter : onUpdate) {
|
||||
setter.preUpdate(bean, now);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class SetValue {
|
||||
|
||||
private final BeanProperty property;
|
||||
private final GeneratedProperty generatedProperty;
|
||||
|
||||
SetValue(BeanProperty property) {
|
||||
this.property = property;
|
||||
this.generatedProperty = property.getGeneratedProperty();
|
||||
}
|
||||
|
||||
public void preInsert(EntityBean bean, long now) {
|
||||
Object value = generatedProperty.getInsertValue(property, bean, now);
|
||||
property.setValue(bean, value);
|
||||
}
|
||||
|
||||
public void preUpdate(EntityBean bean, long now) {
|
||||
Object value = generatedProperty.getUpdateValue(property, bean, now);
|
||||
property.setValue(bean, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.deploy.generatedproperty.GeneratedProperty;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Collects the generated properties for inserts and updates for a given bean type.
|
||||
*/
|
||||
class GeneratedPropertyCollector {
|
||||
|
||||
private final List<BeanProperty> preInsert = new ArrayList<>();
|
||||
private final List<BeanProperty> preUpdate = new ArrayList<>();
|
||||
|
||||
GeneratedPropertyCollector(BeanDescriptor<?> desc) {
|
||||
for (BeanProperty beanProperty : desc.propertiesBaseScalar()) {
|
||||
add(beanProperty);
|
||||
}
|
||||
}
|
||||
|
||||
GeneratedProperties generatedProperties() {
|
||||
return new GeneratedProperties(preInsert, preUpdate);
|
||||
}
|
||||
|
||||
void add(BeanProperty prop) {
|
||||
GeneratedProperty gen = prop.getGeneratedProperty();
|
||||
if (gen != null) {
|
||||
if (gen.includeInInsert()) {
|
||||
preInsert.add(prop);
|
||||
}
|
||||
if (gen.includeInUpdate()) {
|
||||
preUpdate.add(prop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.server.core.Message;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.persist.DmlUtil;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.persistence.OptimisticLockException;
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Insert bean handler.
|
||||
*/
|
||||
public class InsertHandler extends DmlHandler {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(InsertHandler.class);
|
||||
|
||||
/**
|
||||
* The associated InsertMeta data.
|
||||
*/
|
||||
private final InsertMeta meta;
|
||||
|
||||
/**
|
||||
* Set to true when the key is concatenated.
|
||||
*/
|
||||
private final boolean concatinatedKey;
|
||||
|
||||
/**
|
||||
* Flag set when using getGeneratedKeys.
|
||||
*/
|
||||
private boolean useGeneratedKeys;
|
||||
|
||||
/**
|
||||
* A SQL Select used to fetch back the Id where generatedKeys is not
|
||||
* supported.
|
||||
*/
|
||||
private String selectLastInsertedId;
|
||||
|
||||
/**
|
||||
* Create to handle the insert execution.
|
||||
*/
|
||||
public InsertHandler(PersistRequestBean<?> persist, InsertMeta meta) {
|
||||
super(persist, meta.isEmptyStringToNull());
|
||||
this.meta = meta;
|
||||
this.concatinatedKey = meta.isConcatenatedKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and bind the insert statement.
|
||||
*/
|
||||
@Override
|
||||
public void bind() throws SQLException {
|
||||
|
||||
BeanDescriptor<?> desc = persistRequest.getBeanDescriptor();
|
||||
EntityBean bean = persistRequest.getEntityBean();
|
||||
|
||||
Object idValue = desc.getId(bean);
|
||||
|
||||
boolean withId = !DmlUtil.isNullOrZero(idValue);
|
||||
|
||||
// check to see if we are going to use generated keys
|
||||
if (!withId) {
|
||||
if (concatinatedKey) {
|
||||
// expecting a concatenated key that can
|
||||
// be built from supplied AssocOne beans
|
||||
withId = meta.deriveConcatenatedId(persistRequest);
|
||||
|
||||
} else if (meta.supportsGetGeneratedKeys()) {
|
||||
// Identity with getGeneratedKeys
|
||||
useGeneratedKeys = true;
|
||||
} else {
|
||||
// use a query to get the last inserted id
|
||||
selectLastInsertedId = meta.getSelectLastInsertedId();
|
||||
}
|
||||
}
|
||||
|
||||
SpiTransaction t = persistRequest.getTransaction();
|
||||
|
||||
// get the appropriate sql
|
||||
sql = meta.getSql(withId, persistRequest.isPublish());
|
||||
|
||||
PreparedStatement pstmt;
|
||||
if (persistRequest.isBatched()) {
|
||||
pstmt = getPstmt(t, sql, persistRequest, useGeneratedKeys);
|
||||
} else {
|
||||
pstmt = getPstmt(t, sql, useGeneratedKeys);
|
||||
}
|
||||
dataBind = bind(pstmt);
|
||||
meta.bind(this, bean, withId, persistRequest.isPublish());
|
||||
|
||||
logSql(sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check with useGeneratedKeys to get appropriate PreparedStatement.
|
||||
*/
|
||||
@Override
|
||||
protected PreparedStatement getPstmt(SpiTransaction t, String sql, boolean useGeneratedKeys) throws SQLException {
|
||||
Connection conn = t.getInternalConnection();
|
||||
if (useGeneratedKeys) {
|
||||
return conn.prepareStatement(sql, meta.getIdentityDbColumns());
|
||||
|
||||
} else {
|
||||
return conn.prepareStatement(sql);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the insert in a normal non batch fashion. Additionally using
|
||||
* getGeneratedKeys if required.
|
||||
*/
|
||||
@Override
|
||||
public int execute() throws SQLException, OptimisticLockException {
|
||||
int rowCount = dataBind.executeUpdate();
|
||||
if (useGeneratedKeys) {
|
||||
// get the auto-increment value back and set into the bean
|
||||
getGeneratedKeys();
|
||||
|
||||
} else if (selectLastInsertedId != null) {
|
||||
// fetch back the Id using a query
|
||||
fetchGeneratedKeyUsingSelect();
|
||||
}
|
||||
|
||||
checkRowCount(rowCount);
|
||||
return rowCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* For non batch insert with generated keys.
|
||||
*/
|
||||
private void getGeneratedKeys() throws SQLException {
|
||||
|
||||
ResultSet rset = dataBind.getPstmt().getGeneratedKeys();
|
||||
try {
|
||||
setGeneratedKey(rset);
|
||||
} finally {
|
||||
try {
|
||||
rset.close();
|
||||
} catch (SQLException ex) {
|
||||
String msg = "Error closing rset for returning generatedKeys?";
|
||||
logger.warn(msg, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setGeneratedKey(ResultSet rset) throws SQLException {
|
||||
if (rset.next()) {
|
||||
Object idValue = rset.getObject(1);
|
||||
if (idValue != null) {
|
||||
persistRequest.setGeneratedKey(idValue);
|
||||
}
|
||||
|
||||
} else {
|
||||
throw new PersistenceException(Message.msg("persist.autoinc.norows"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* For non batch insert with DBs that do not support getGeneratedKeys. Use a
|
||||
* SQL select to fetch back the Id value.
|
||||
*/
|
||||
private void fetchGeneratedKeyUsingSelect() throws SQLException {
|
||||
|
||||
Connection conn = transaction.getConnection();
|
||||
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rset = null;
|
||||
try {
|
||||
stmt = conn.prepareStatement(selectLastInsertedId);
|
||||
rset = stmt.executeQuery();
|
||||
setGeneratedKey(rset);
|
||||
} finally {
|
||||
try {
|
||||
if (rset != null) {
|
||||
rset.close();
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
logger.warn("Error closing ResultSet for fetchGeneratedKeyUsingSelect?", ex);
|
||||
}
|
||||
try {
|
||||
if (stmt != null) {
|
||||
stmt.close();
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
logger.warn("Error closing Statement for fetchGeneratedKeyUsingSelect?", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebean.config.dbplatform.DatabasePlatform;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.InheritInfo;
|
||||
import io.ebeaninternal.server.persist.dmlbind.Bindable;
|
||||
import io.ebeaninternal.server.persist.dmlbind.BindableDiscriminator;
|
||||
import io.ebeaninternal.server.persist.dmlbind.BindableId;
|
||||
import io.ebeaninternal.server.persist.dmlbind.BindableList;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Meta data for insert handler. The meta data is for a particular bean type. It
|
||||
* is considered immutable and is thread safe.
|
||||
*/
|
||||
public final class InsertMeta {
|
||||
|
||||
private final String sqlNullId;
|
||||
private final String sqlWithId;
|
||||
private final String sqlDraftNullId;
|
||||
private final String sqlDraftWithId;
|
||||
|
||||
private final BindableId id;
|
||||
|
||||
private final Bindable discriminator;
|
||||
|
||||
private final BindableList all;
|
||||
|
||||
private final BindableList allExcludeDraftOnly;
|
||||
|
||||
private final boolean supportsGetGeneratedKeys;
|
||||
|
||||
private final boolean concatinatedKey;
|
||||
|
||||
/**
|
||||
* Used for DB that do not support getGeneratedKeys.
|
||||
*/
|
||||
private final String selectLastInsertedId;
|
||||
|
||||
private final Bindable shadowFKey;
|
||||
|
||||
private final String[] identityDbColumns;
|
||||
|
||||
private final boolean emptyStringToNull;
|
||||
|
||||
public InsertMeta(DatabasePlatform dbPlatform, BeanDescriptor<?> desc, Bindable shadowFKey, BindableId id, BindableList all) {
|
||||
|
||||
this.emptyStringToNull = dbPlatform.isTreatEmptyStringsAsNull();
|
||||
this.discriminator = getDiscriminator(desc);
|
||||
this.id = id;
|
||||
this.all = all;
|
||||
this.allExcludeDraftOnly = all.excludeDraftOnly();
|
||||
this.shadowFKey = shadowFKey;
|
||||
|
||||
String tableName = desc.getBaseTable();
|
||||
String draftTableName = desc.getDraftTable();
|
||||
|
||||
this.sqlWithId = genSql(false, tableName, false);
|
||||
this.sqlDraftWithId = desc.isDraftable() ? genSql(false, draftTableName, true) : sqlWithId;
|
||||
|
||||
// only available for single Id property
|
||||
if (id.isConcatenated()) {
|
||||
// concatenated key
|
||||
this.concatinatedKey = true;
|
||||
this.identityDbColumns = null;
|
||||
this.sqlNullId = null;
|
||||
this.sqlDraftNullId = null;
|
||||
this.supportsGetGeneratedKeys = false;
|
||||
this.selectLastInsertedId = null;
|
||||
|
||||
} else {
|
||||
// insert sql for db identity or sequence insert
|
||||
this.concatinatedKey = false;
|
||||
if (id.getIdentityColumn() == null) {
|
||||
this.identityDbColumns = new String[]{};
|
||||
this.supportsGetGeneratedKeys = false;
|
||||
this.selectLastInsertedId = null;
|
||||
} else {
|
||||
this.identityDbColumns = new String[]{id.getIdentityColumn()};
|
||||
this.supportsGetGeneratedKeys = dbPlatform.getDbIdentity().isSupportsGetGeneratedKeys();
|
||||
this.selectLastInsertedId = desc.getSelectLastInsertedId();
|
||||
}
|
||||
this.sqlNullId = genSql(true, tableName, false);
|
||||
this.sqlDraftNullId = desc.isDraftable() ? genSql(true, draftTableName, true) : sqlNullId;
|
||||
}
|
||||
}
|
||||
|
||||
private static Bindable getDiscriminator(BeanDescriptor<?> desc) {
|
||||
InheritInfo inheritInfo = desc.getInheritInfo();
|
||||
if (inheritInfo != null) {
|
||||
return new BindableDiscriminator(inheritInfo);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if empty strings should be treated as null.
|
||||
*/
|
||||
public boolean isEmptyStringToNull() {
|
||||
return emptyStringToNull;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this is a concatenated key.
|
||||
*/
|
||||
public boolean isConcatenatedKey() {
|
||||
return concatinatedKey;
|
||||
}
|
||||
|
||||
public String[] getIdentityDbColumns() {
|
||||
return identityDbColumns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns sql that is used to fetch back the last inserted id. This will
|
||||
* return null if it should not be used.
|
||||
* <p>
|
||||
* This is only for DB's that do not support getGeneratedKeys. For MS
|
||||
* SQLServer 2000 this could return "SELECT (at)(at)IDENTITY as id".
|
||||
* </p>
|
||||
*/
|
||||
public String getSelectLastInsertedId() {
|
||||
return selectLastInsertedId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if getGeneratedKeys is supported by the underlying jdbc
|
||||
* driver and database.
|
||||
*/
|
||||
public boolean supportsGetGeneratedKeys() {
|
||||
return supportsGetGeneratedKeys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the Id can be derived from other property values.
|
||||
*/
|
||||
public boolean deriveConcatenatedId(PersistRequestBean<?> persist) {
|
||||
return id.deriveConcatenatedId(persist);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the request based on whether the id value(s) are null.
|
||||
*/
|
||||
public void bind(DmlHandler request, EntityBean bean, boolean withId, boolean publish) throws SQLException {
|
||||
|
||||
if (withId) {
|
||||
id.dmlBind(request, bean);
|
||||
}
|
||||
if (shadowFKey != null) {
|
||||
shadowFKey.dmlBind(request, bean);
|
||||
}
|
||||
if (discriminator != null) {
|
||||
discriminator.dmlBind(request, bean);
|
||||
}
|
||||
if (publish) {
|
||||
allExcludeDraftOnly.dmlBind(request, bean);
|
||||
} else {
|
||||
all.dmlBind(request, bean);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* get the sql based whether the id value(s) are null.
|
||||
*/
|
||||
public String getSql(boolean withId, boolean publish) {
|
||||
|
||||
if (withId) {
|
||||
return publish ? sqlWithId : sqlDraftWithId;
|
||||
} else {
|
||||
return publish ? sqlNullId : sqlDraftNullId;
|
||||
}
|
||||
}
|
||||
|
||||
private String genSql(boolean nullId, String table, boolean draftTable) {
|
||||
|
||||
GenerateDmlRequest request = new GenerateDmlRequest();
|
||||
request.setInsertSetMode();
|
||||
|
||||
request.append("insert into ").append(table);
|
||||
request.append(" (");
|
||||
|
||||
if (!nullId) {
|
||||
id.dmlAppend(request);
|
||||
}
|
||||
|
||||
if (shadowFKey != null) {
|
||||
shadowFKey.dmlAppend(request);
|
||||
}
|
||||
|
||||
if (discriminator != null) {
|
||||
discriminator.dmlAppend(request);
|
||||
}
|
||||
|
||||
if (draftTable) {
|
||||
all.dmlAppend(request);
|
||||
} else {
|
||||
allExcludeDraftOnly.dmlAppend(request);
|
||||
}
|
||||
|
||||
request.append(") values (");
|
||||
request.append(request.getInsertBindBuffer());
|
||||
request.append(")");
|
||||
|
||||
return request.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebean.config.dbplatform.DatabasePlatform;
|
||||
import io.ebean.config.dbplatform.DbEncrypt;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import io.ebeaninternal.server.persist.dmlbind.Bindable;
|
||||
import io.ebeaninternal.server.persist.dmlbind.BindableId;
|
||||
import io.ebeaninternal.server.persist.dmlbind.BindableList;
|
||||
import io.ebeaninternal.server.persist.dmlbind.BindableUnidirectional;
|
||||
import io.ebeaninternal.server.persist.dmlbind.FactoryAssocOnes;
|
||||
import io.ebeaninternal.server.persist.dmlbind.FactoryBaseProperties;
|
||||
import io.ebeaninternal.server.persist.dmlbind.FactoryEmbedded;
|
||||
import io.ebeaninternal.server.persist.dmlbind.FactoryId;
|
||||
import io.ebeaninternal.server.persist.dmlbind.FactoryVersion;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Factory for creating InsertMeta UpdateMeta and DeleteMeta.
|
||||
*/
|
||||
public class MetaFactory {
|
||||
|
||||
private final FactoryBaseProperties baseFact;
|
||||
private final FactoryEmbedded embeddedFact;
|
||||
private final FactoryVersion versionFact = new FactoryVersion();
|
||||
private final FactoryAssocOnes assocOneFact = new FactoryAssocOnes();
|
||||
|
||||
private final FactoryId idFact = new FactoryId();
|
||||
|
||||
/**
|
||||
* Include Lobs in the base statement. Generally true. Oracle9 used to require
|
||||
* a separate statement for Clobs and Blobs.
|
||||
*/
|
||||
private static final boolean includeLobs = true;
|
||||
|
||||
private final DatabasePlatform dbPlatform;
|
||||
|
||||
private final boolean emptyStringAsNull;
|
||||
|
||||
public MetaFactory(DatabasePlatform dbPlatform) {
|
||||
this.dbPlatform = dbPlatform;
|
||||
this.emptyStringAsNull = dbPlatform.isTreatEmptyStringsAsNull();
|
||||
|
||||
// to bind encryption data before or after the encryption key
|
||||
DbEncrypt dbEncrypt = dbPlatform.getDbEncrypt();
|
||||
boolean bindEncryptDataFirst = dbEncrypt == null || dbEncrypt.isBindEncryptDataFirst();
|
||||
|
||||
this.baseFact = new FactoryBaseProperties(bindEncryptDataFirst);
|
||||
this.embeddedFact = new FactoryEmbedded(bindEncryptDataFirst);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the UpdateMeta for the given bean type.
|
||||
*/
|
||||
public UpdateMeta createUpdate(BeanDescriptor<?> desc) {
|
||||
|
||||
List<Bindable> setList = new ArrayList<>();
|
||||
|
||||
baseFact.create(setList, desc, DmlMode.UPDATE, includeLobs);
|
||||
embeddedFact.create(setList, desc, DmlMode.UPDATE, includeLobs);
|
||||
assocOneFact.create(setList, desc, DmlMode.UPDATE);
|
||||
|
||||
BindableId id = idFact.createId(desc);
|
||||
|
||||
Bindable ver = versionFact.create(desc);
|
||||
|
||||
BindableList setBindable = new BindableList(setList);
|
||||
|
||||
return new UpdateMeta(emptyStringAsNull, desc, setBindable, id, ver);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the DeleteMeta for the given bean type.
|
||||
*/
|
||||
public DeleteMeta createDelete(BeanDescriptor<?> desc) {
|
||||
|
||||
BindableId id = idFact.createId(desc);
|
||||
|
||||
Bindable ver = versionFact.create(desc);
|
||||
|
||||
return new DeleteMeta(emptyStringAsNull, desc, id, ver);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the InsertMeta for the given bean type.
|
||||
*/
|
||||
public InsertMeta createInsert(BeanDescriptor<?> desc) {
|
||||
|
||||
BindableId id = idFact.createId(desc);
|
||||
|
||||
List<Bindable> allList = new ArrayList<>();
|
||||
|
||||
baseFact.create(allList, desc, DmlMode.INSERT, includeLobs);
|
||||
embeddedFact.create(allList, desc, DmlMode.INSERT, includeLobs);
|
||||
assocOneFact.create(allList, desc, DmlMode.INSERT);
|
||||
|
||||
BindableList allBindable = new BindableList(allList);
|
||||
|
||||
BeanPropertyAssocOne<?> unidirectional = desc.getUnidirectional();
|
||||
|
||||
Bindable shadowFkey;
|
||||
if (unidirectional == null) {
|
||||
shadowFkey = null;
|
||||
} else {
|
||||
shadowFkey = new BindableUnidirectional(desc, unidirectional);
|
||||
}
|
||||
|
||||
return new InsertMeta(dbPlatform, desc, shadowFkey, id, allBindable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Implementation API for insert update and delete handlers.
|
||||
*/
|
||||
public interface PersistHandler {
|
||||
|
||||
/**
|
||||
* Return the bind log.
|
||||
*/
|
||||
String getBindLog();
|
||||
|
||||
/**
|
||||
* Get the sql and bind the statement.
|
||||
*/
|
||||
void bind() throws SQLException;
|
||||
|
||||
/**
|
||||
* Add this for batch execution.
|
||||
*/
|
||||
void addBatch() throws SQLException;
|
||||
|
||||
/**
|
||||
* Execute now for non-batch execution.
|
||||
*/
|
||||
int execute() throws SQLException;
|
||||
|
||||
/**
|
||||
* Close resources including underlying preparedStatement.
|
||||
*/
|
||||
void close();
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import io.ebeaninternal.api.SpiUpdatePlan;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
|
||||
import javax.persistence.OptimisticLockException;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Update bean handler.
|
||||
*/
|
||||
public class UpdateHandler extends DmlHandler {
|
||||
|
||||
private final UpdateMeta meta;
|
||||
|
||||
private boolean emptySetClause;
|
||||
|
||||
public UpdateHandler(PersistRequestBean<?> persist, UpdateMeta meta) {
|
||||
super(persist, meta.isEmptyStringAsNull());
|
||||
this.meta = meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and bind the update statement.
|
||||
*/
|
||||
@Override
|
||||
public void bind() throws SQLException {
|
||||
|
||||
SpiUpdatePlan updatePlan = meta.getUpdatePlan(persistRequest);
|
||||
|
||||
if (updatePlan.isEmptySetClause()) {
|
||||
emptySetClause = true;
|
||||
return;
|
||||
}
|
||||
|
||||
sql = updatePlan.getSql();
|
||||
|
||||
SpiTransaction t = persistRequest.getTransaction();
|
||||
|
||||
PreparedStatement pstmt;
|
||||
if (persistRequest.isBatched()) {
|
||||
pstmt = getPstmt(t, sql, persistRequest, false);
|
||||
} else {
|
||||
pstmt = getPstmt(t, sql, false);
|
||||
}
|
||||
dataBind = bind(pstmt);
|
||||
meta.bind(persistRequest, this, updatePlan);
|
||||
|
||||
setUpdateGenValues();
|
||||
|
||||
logSql(sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addBatch() throws SQLException {
|
||||
if (!emptySetClause) {
|
||||
super.addBatch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the update in non-batch.
|
||||
*/
|
||||
@Override
|
||||
public int execute() throws SQLException, OptimisticLockException {
|
||||
if (!emptySetClause) {
|
||||
int rowCount = dataBind.executeUpdate();
|
||||
checkRowCount(rowCount);
|
||||
return rowCount;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.api.ConcurrencyMode;
|
||||
import io.ebeaninternal.api.SpiUpdatePlan;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.persist.dmlbind.Bindable;
|
||||
import io.ebeaninternal.server.persist.dmlbind.BindableId;
|
||||
import io.ebeaninternal.server.persist.dmlbind.BindableList;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Meta data for update handler. The meta data is for a particular bean type. It
|
||||
* is considered immutable and is thread safe.
|
||||
*/
|
||||
public final class UpdateMeta {
|
||||
|
||||
private final BindableList set;
|
||||
private final BindableId id;
|
||||
private final Bindable version;
|
||||
|
||||
private final String tableName;
|
||||
|
||||
private final UpdatePlan modeNoneUpdatePlan;
|
||||
private final UpdatePlan modeVersionUpdatePlan;
|
||||
|
||||
private final boolean emptyStringAsNull;
|
||||
|
||||
public UpdateMeta(boolean emptyStringAsNull, BeanDescriptor<?> desc, BindableList set, BindableId id, Bindable version) {
|
||||
this.emptyStringAsNull = emptyStringAsNull;
|
||||
this.tableName = desc.getBaseTable();
|
||||
this.set = set;
|
||||
this.id = id;
|
||||
this.version = version;
|
||||
|
||||
String sqlNone = genSql(ConcurrencyMode.NONE, set, desc.getBaseTable());
|
||||
String sqlVersion = genSql(ConcurrencyMode.VERSION, set, desc.getBaseTable());
|
||||
|
||||
this.modeNoneUpdatePlan = new UpdatePlan(ConcurrencyMode.NONE, sqlNone, set);
|
||||
this.modeVersionUpdatePlan = new UpdatePlan(ConcurrencyMode.VERSION, sqlVersion, set);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if empty strings should be treated as null.
|
||||
*/
|
||||
public boolean isEmptyStringAsNull() {
|
||||
return emptyStringAsNull;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the base table name.
|
||||
*/
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the request based on the concurrency mode.
|
||||
*/
|
||||
public void bind(PersistRequestBean<?> persist, DmlHandler bind, SpiUpdatePlan updatePlan) throws SQLException {
|
||||
|
||||
EntityBean bean = persist.getEntityBean();
|
||||
|
||||
updatePlan.bindSet(bind, bean);
|
||||
|
||||
id.dmlBind(bind, bean);
|
||||
|
||||
switch (persist.getConcurrencyMode()) {
|
||||
case VERSION:
|
||||
version.dmlBind(bind, bean);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* get or generate the sql based on the concurrency mode.
|
||||
*/
|
||||
public SpiUpdatePlan getUpdatePlan(PersistRequestBean<?> request) {
|
||||
|
||||
if (request.isDynamicUpdateSql()) {
|
||||
return getDynamicUpdatePlan(request);
|
||||
}
|
||||
|
||||
// 'full bean' update...
|
||||
ConcurrencyMode mode = request.determineConcurrencyMode();
|
||||
switch (mode) {
|
||||
case NONE:
|
||||
return modeNoneUpdatePlan;
|
||||
|
||||
case VERSION:
|
||||
return modeVersionUpdatePlan;
|
||||
|
||||
default:
|
||||
throw new RuntimeException("Invalid mode " + mode);
|
||||
}
|
||||
}
|
||||
|
||||
private SpiUpdatePlan getDynamicUpdatePlan(PersistRequestBean<?> persistRequest) {
|
||||
|
||||
String key = persistRequest.getUpdatePlanHash();
|
||||
|
||||
// check if we can use a cached UpdatePlan
|
||||
BeanDescriptor<?> beanDescriptor = persistRequest.getBeanDescriptor();
|
||||
SpiUpdatePlan updatePlan = beanDescriptor.getUpdatePlan(key);
|
||||
if (updatePlan != null) {
|
||||
return updatePlan;
|
||||
}
|
||||
|
||||
// build a new UpdatePlan and cache it
|
||||
|
||||
// build a bindableList that only contains the changed properties
|
||||
List<Bindable> list = new ArrayList<>();
|
||||
set.addToUpdate(persistRequest, list);
|
||||
BindableList bindableList = new BindableList(list);
|
||||
|
||||
ConcurrencyMode mode = persistRequest.determineConcurrencyMode();
|
||||
|
||||
// build the SQL for this update statement
|
||||
String sql = genSql(mode, bindableList, persistRequest.getUpdateTable());
|
||||
|
||||
updatePlan = new UpdatePlan(key, mode, sql, bindableList);
|
||||
|
||||
// add the UpdatePlan to the cache
|
||||
beanDescriptor.putUpdatePlan(key, updatePlan);
|
||||
|
||||
return updatePlan;
|
||||
}
|
||||
|
||||
private String genSql(ConcurrencyMode conMode, BindableList bindableList, String tableName) {
|
||||
|
||||
// update set col0=?, col1=?, col2=? where bcol=? and bc1=? and bc2=?
|
||||
|
||||
GenerateDmlRequest request = new GenerateDmlRequest();
|
||||
request.append("update ").append(tableName).append(" set ");
|
||||
|
||||
request.setUpdateSetMode();
|
||||
bindableList.dmlAppend(request);
|
||||
|
||||
if (request.getBindColumnCount() == 0) {
|
||||
// update properties must have been updatable=false
|
||||
// with the result that nothing is in the set clause
|
||||
return null;
|
||||
}
|
||||
|
||||
request.append(" where ");
|
||||
|
||||
request.setWhereIdMode();
|
||||
id.dmlAppend(request);
|
||||
|
||||
if (ConcurrencyMode.VERSION.equals(conMode)) {
|
||||
if (version == null) {
|
||||
return null;
|
||||
}
|
||||
version.dmlAppend(request);
|
||||
}
|
||||
|
||||
return request.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package io.ebeaninternal.server.persist.dml;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.api.ConcurrencyMode;
|
||||
import io.ebeaninternal.api.SpiUpdatePlan;
|
||||
import io.ebeaninternal.server.persist.dmlbind.Bindable;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Plan for executing bean updates for a given set of changed properties.
|
||||
*/
|
||||
public class UpdatePlan implements SpiUpdatePlan {
|
||||
|
||||
private final String key;
|
||||
|
||||
private final ConcurrencyMode mode;
|
||||
|
||||
private final String sql;
|
||||
|
||||
private final Bindable set;
|
||||
|
||||
private final long timeCreated;
|
||||
|
||||
private final boolean emptySetClause;
|
||||
|
||||
private long timeLastUsed;
|
||||
|
||||
/**
|
||||
* Create a non cached UpdatePlan.
|
||||
*/
|
||||
UpdatePlan(ConcurrencyMode mode, String sql, Bindable set) {
|
||||
this(null, mode, sql, set);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a UpdatePlan with a given key.
|
||||
*/
|
||||
UpdatePlan(String key, ConcurrencyMode mode, String sql, Bindable set) {
|
||||
this.emptySetClause = (sql == null);
|
||||
this.key = key;
|
||||
this.mode = mode;
|
||||
this.sql = sql;
|
||||
this.set = set;
|
||||
this.timeCreated = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public boolean isEmptySetClause() {
|
||||
return emptySetClause;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the prepared statement binding for the 'update set' properties.
|
||||
*/
|
||||
public void bindSet(DmlHandler bind, EntityBean bean) throws SQLException {
|
||||
set.dmlBind(bind, bean);
|
||||
// atomic on 64 bit jvm
|
||||
this.timeLastUsed = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time this plan was created.
|
||||
*/
|
||||
public long getTimeCreated() {
|
||||
return timeCreated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time this plan was last used.
|
||||
*/
|
||||
public long getTimeLastUsed() {
|
||||
return timeLastUsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the key.
|
||||
*/
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the concurrency mode for this plan.
|
||||
*/
|
||||
public ConcurrencyMode getMode() {
|
||||
return mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the DML statement.
|
||||
*/
|
||||
public String getSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the Bindable properties for the update set.
|
||||
*/
|
||||
public Bindable getSet() {
|
||||
return set;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
|
||||
<TITLE>Bean DML persistence implementation</TITLE>
|
||||
</HEAD>
|
||||
<Body BGCOLOR="#ffffff">
|
||||
Bean DML persistence implementation
|
||||
|
||||
</Body>
|
||||
</HTML>
|
||||
@@ -0,0 +1,46 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Item held by Meta objects used to generate and bind bean insert update and
|
||||
* delete statements.
|
||||
* <p>
|
||||
* An implementation is expected to be immutable and thread safe.
|
||||
* </p>
|
||||
* <p>
|
||||
* The design is to take a bean structure with embedded and associated objects
|
||||
* etc and flatten that into lists of Bindable objects. These are put into
|
||||
* InsertMeta UpdateMeta and DeleteMeta objects to support the generation of DML
|
||||
* and binding of statements in a fast and painless manor.
|
||||
* </p>
|
||||
*/
|
||||
public interface Bindable {
|
||||
|
||||
/**
|
||||
* For Updates including only changed properties add the Bindable to the
|
||||
* list if it should be included in the 'update set'.
|
||||
*/
|
||||
void addToUpdate(PersistRequestBean<?> request, List<Bindable> list);
|
||||
|
||||
/**
|
||||
* append sql to the buffer with prefix and suffix options.
|
||||
*/
|
||||
void dmlAppend(GenerateDmlRequest request);
|
||||
|
||||
/**
|
||||
* Bind given the request and bean. The bean could be the oldValues bean
|
||||
* when binding a update or delete where clause with ALL concurrency mode.
|
||||
*/
|
||||
void dmlBind(BindableRequest request, EntityBean bean) throws SQLException;
|
||||
|
||||
/**
|
||||
* Return true if the underlying property is 'draft only'.
|
||||
*/
|
||||
boolean isDraftOnly();
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import io.ebeaninternal.server.deploy.id.ImportedId;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Bindable for an ManyToOne or OneToOne associated bean.
|
||||
*/
|
||||
public class BindableAssocOne implements Bindable {
|
||||
|
||||
private final BeanPropertyAssocOne<?> assocOne;
|
||||
|
||||
private final ImportedId importedId;
|
||||
|
||||
public BindableAssocOne(BeanPropertyAssocOne<?> assocOne) {
|
||||
this.assocOne = assocOne;
|
||||
this.importedId = assocOne.getImportedId();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "BindableAssocOne " + assocOne;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDraftOnly() {
|
||||
return assocOne.isDraftOnly();
|
||||
}
|
||||
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
if (request.isAddToUpdate(assocOne)) {
|
||||
list.add(this);
|
||||
}
|
||||
}
|
||||
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
importedId.dmlAppend(request);
|
||||
}
|
||||
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
|
||||
EntityBean assocBean = (EntityBean) assocOne.getValue(bean);
|
||||
Object boundValue = importedId.bind(request, assocBean);
|
||||
if (boundValue == null && assocBean != null) {
|
||||
// this is the scenario for a derived foreign key
|
||||
// which will require an additional update
|
||||
// register for post insert of assocBean
|
||||
// update of bean set importedId
|
||||
request.getPersistRequest().deferredRelationship(assocBean, importedId, bean);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.InheritInfo;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Bindable for inserting a discriminator value.
|
||||
*/
|
||||
public class BindableDiscriminator implements Bindable {
|
||||
|
||||
private final String columnName;
|
||||
private final Object discValue;
|
||||
private final int sqlType;
|
||||
|
||||
public BindableDiscriminator(InheritInfo inheritInfo) {
|
||||
this.columnName = inheritInfo.getDiscriminatorColumn();
|
||||
this.discValue = inheritInfo.getDiscriminatorValue();
|
||||
this.sqlType = inheritInfo.getDiscriminatorType();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return columnName + " = " + discValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDraftOnly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
throw new PersistenceException("Never called (only for inserts)");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
request.appendColumn(columnName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dmlBind(BindableRequest bindRequest, EntityBean bean) throws SQLException {
|
||||
|
||||
bindRequest.bind(discValue, sqlType);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Bindable for a Embedded bean.
|
||||
*/
|
||||
public class BindableEmbedded implements Bindable {
|
||||
|
||||
private final Bindable[] items;
|
||||
|
||||
private final BeanPropertyAssocOne<?> embProp;
|
||||
|
||||
public BindableEmbedded(BeanPropertyAssocOne<?> embProp, List<Bindable> bindList) {
|
||||
this.embProp = embProp;
|
||||
this.items = bindList.toArray(new Bindable[bindList.size()]); //this.props = propList.toArray(new BeanProperty[propList.size()]);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "BindableEmbedded " + embProp + " items:" + Arrays.toString(items);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDraftOnly() {
|
||||
return embProp.isDraftOnly();
|
||||
}
|
||||
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
|
||||
for (Bindable item : items) {
|
||||
item.dmlAppend(request);
|
||||
}
|
||||
}
|
||||
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
if (request.isAddToUpdate(embProp)) {
|
||||
list.add(this);
|
||||
}
|
||||
}
|
||||
|
||||
public void dmlBind(BindableRequest bindRequest, EntityBean bean) throws SQLException {
|
||||
|
||||
// get the embedded bean
|
||||
EntityBean embBean = (EntityBean) embProp.getValue(bean);
|
||||
if (embBean == null) {
|
||||
for (Bindable item : items) {
|
||||
item.dmlBind(bindRequest, null);
|
||||
}
|
||||
} else {
|
||||
//EntityBeanIntercept ebi = embBean._ebean_getIntercept();
|
||||
for (Bindable item : items) {
|
||||
//if (ebi.isLoadedProperty(props[i].getPropertyIndex())) {
|
||||
item.dmlBind(bindRequest, embBean);
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Bindable for a DB encrypted BeanProperty.
|
||||
*/
|
||||
public class BindableEncryptedProperty implements Bindable {
|
||||
|
||||
private final BeanProperty prop;
|
||||
|
||||
private final boolean bindEncryptDataFirst;
|
||||
|
||||
public BindableEncryptedProperty(BeanProperty prop, boolean bindEncryptDataFirst) {
|
||||
this.prop = prop;
|
||||
this.bindEncryptDataFirst = bindEncryptDataFirst;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return prop.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDraftOnly() {
|
||||
return prop.isDraftOnly();
|
||||
}
|
||||
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
if (request.isAddToUpdate(prop)) {
|
||||
list.add(this);
|
||||
}
|
||||
}
|
||||
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
|
||||
// columnName = AES_ENCRYPT(?,?)
|
||||
request.appendColumn(prop.getDbColumn(), prop.getDbBind());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Bind a value in a Insert SET clause.
|
||||
*/
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
|
||||
Object value = null;
|
||||
if (bean != null) {
|
||||
value = prop.getValue(bean);
|
||||
}
|
||||
|
||||
// get Encrypt key
|
||||
String encryptKeyValue = prop.getEncryptKey().getStringValue();
|
||||
|
||||
if (!bindEncryptDataFirst) {
|
||||
// H2 encrypt function ... different parameter order
|
||||
request.bindNoLog(encryptKeyValue, Types.VARCHAR, prop.getName() + "=****");
|
||||
}
|
||||
request.bindNoLog(value, prop);
|
||||
|
||||
if (bindEncryptDataFirst) {
|
||||
// MySql, Postgres, Oracle
|
||||
request.bindNoLog(encryptKeyValue, Types.VARCHAR, prop.getName() + "=****");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
|
||||
/**
|
||||
* Adds support for id creation for concatenated ids on intersection tables.
|
||||
* <p>
|
||||
* Specifically if the concatenated id object is null on insert this can be
|
||||
* built from the matching ManyToOne associated beans. For example RoleUserId
|
||||
* embeddedId object could be built from the associated Role and User beans.
|
||||
* </p>
|
||||
* <p>
|
||||
* This is only attempted if the id is null when it gets to the insert.
|
||||
* </p>
|
||||
*/
|
||||
public interface BindableId extends Bindable {
|
||||
|
||||
/**
|
||||
* Return true if there is no Id properties at all.
|
||||
*/
|
||||
boolean isEmpty();
|
||||
|
||||
/**
|
||||
* Return true if this is a concatenated key.
|
||||
*/
|
||||
boolean isConcatenated();
|
||||
|
||||
/**
|
||||
* Return the DB Column to use with genGeneratedKeys.
|
||||
*/
|
||||
String getIdentityColumn();
|
||||
|
||||
/**
|
||||
* Create the concatenated id for inserts with PFK relationships.
|
||||
* <p>
|
||||
* Really only where there are ManyToOne assoc beans that make up the
|
||||
* primary key and the values can be got from those.
|
||||
* </p>
|
||||
*/
|
||||
boolean deriveConcatenatedId(PersistRequestBean<?> persist);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Bindable for a EmbeddedId.
|
||||
*/
|
||||
public final class BindableIdEmbedded implements BindableId {
|
||||
|
||||
private final BeanPropertyAssocOne<?> embId;
|
||||
|
||||
private final BeanProperty[] props;
|
||||
|
||||
private final MatchedImportedProperty[] matches;
|
||||
|
||||
public BindableIdEmbedded(BeanPropertyAssocOne<?> embId, BeanDescriptor<?> desc) {
|
||||
this.embId = embId;
|
||||
this.props = embId.getProperties();
|
||||
matches = MatchedImportedProperty.build(props, desc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDraftOnly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isConcatenated() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getIdentityColumn() {
|
||||
// return null for concatenated keys
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return embId + " props:" + Arrays.toString(props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Does nothing for BindableId.
|
||||
*/
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
// do nothing (id not changing)
|
||||
}
|
||||
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
|
||||
EntityBean idValue = (EntityBean) embId.getValue(bean);
|
||||
|
||||
for (BeanProperty prop : props) {
|
||||
|
||||
Object value = prop.getValue(idValue);
|
||||
request.bind(value, prop);
|
||||
}
|
||||
|
||||
request.setIdValue(idValue);
|
||||
}
|
||||
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
for (BeanProperty prop : props) {
|
||||
request.appendColumn(prop.getDbColumn());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean deriveConcatenatedId(PersistRequestBean<?> persist) {
|
||||
|
||||
if (matches == null) {
|
||||
String m = "Matches for the concatenated key columns where not found?"
|
||||
+ " I expect that the concatenated key was null, and this bean does"
|
||||
+ " not have ManyToOne assoc beans matching the primary key columns?";
|
||||
throw new PersistenceException(m);
|
||||
}
|
||||
|
||||
EntityBean bean = persist.getEntityBean();
|
||||
|
||||
// create the new id
|
||||
EntityBean newId = (EntityBean) embId.createEmbeddedId();
|
||||
|
||||
// populate it from the assoc one id values...
|
||||
for (MatchedImportedProperty matche : matches) {
|
||||
matche.populate(bean, newId);
|
||||
}
|
||||
|
||||
// support PropertyChangeSupport
|
||||
embId.setValueIntercept(bean, newId);
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public class BindableIdEmpty implements BindableId {
|
||||
|
||||
public boolean isEmpty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDraftOnly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
// nothing
|
||||
}
|
||||
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
// nothing
|
||||
}
|
||||
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
// nothing
|
||||
}
|
||||
|
||||
public boolean isConcatenated() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public String getIdentityColumn() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean deriveConcatenatedId(PersistRequestBean<?> persist) {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Bindable for a single scalar id property.
|
||||
*/
|
||||
public final class BindableIdScalar implements BindableId {
|
||||
|
||||
private final BeanProperty uidProp;
|
||||
|
||||
public BindableIdScalar(BeanProperty uidProp) {
|
||||
this.uidProp = uidProp;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isConcatenated() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public String getIdentityColumn() {
|
||||
return uidProp.getDbColumn();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return uidProp.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDraftOnly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does nothing for BindableId.
|
||||
*/
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
// do nothing (id not changing)
|
||||
}
|
||||
|
||||
/**
|
||||
* Should not be called as this is really only for concatenated keys.
|
||||
*/
|
||||
public boolean deriveConcatenatedId(PersistRequestBean<?> persist) {
|
||||
throw new PersistenceException("Should not be called? only for concatinated keys");
|
||||
}
|
||||
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
|
||||
request.appendColumn(uidProp.getDbColumn());
|
||||
}
|
||||
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
|
||||
Object value = uidProp.getValue(bean);
|
||||
|
||||
request.bind(value, uidProp);
|
||||
|
||||
// used for summary logging
|
||||
request.setIdValue(value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* List of Bindable items.
|
||||
*/
|
||||
public class BindableList implements Bindable {
|
||||
|
||||
private final Bindable[] items;
|
||||
|
||||
public BindableList(List<Bindable> list) {
|
||||
items = list.toArray(new Bindable[list.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a bindable list that excludes @DraftOnly properties.
|
||||
*/
|
||||
public BindableList excludeDraftOnly() {
|
||||
List<Bindable> copy = new ArrayList<>(items.length);
|
||||
for (Bindable b : items) {
|
||||
if (!b.isDraftOnly()) {
|
||||
copy.add(b);
|
||||
}
|
||||
}
|
||||
return new BindableList(copy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDraftOnly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void addAll(List<Bindable> list) {
|
||||
Collections.addAll(list, items);
|
||||
}
|
||||
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
for (Bindable item : items) {
|
||||
item.addToUpdate(request, list);
|
||||
}
|
||||
}
|
||||
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
for (Bindable item : items) {
|
||||
item.dmlAppend(request);
|
||||
}
|
||||
}
|
||||
|
||||
public void dmlBind(BindableRequest bindRequest, EntityBean bean) throws SQLException {
|
||||
for (Bindable item : items) {
|
||||
item.dmlBind(bindRequest, bean);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Bindable for a single BeanProperty.
|
||||
*/
|
||||
public class BindableProperty implements Bindable {
|
||||
|
||||
protected final BeanProperty prop;
|
||||
|
||||
public BindableProperty(BeanProperty prop) {
|
||||
this.prop = prop;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return prop.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDraftOnly() {
|
||||
return prop.isDraftOnly();
|
||||
}
|
||||
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
if (request.isAddToUpdate(prop)) {
|
||||
list.add(this);
|
||||
}
|
||||
}
|
||||
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
request.appendColumn(prop.getDbColumn());
|
||||
}
|
||||
|
||||
/**
|
||||
* Normal binding of a property value from the bean.
|
||||
*/
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
|
||||
Object value = null;
|
||||
if (bean != null) {
|
||||
value = prop.getValue(bean);
|
||||
}
|
||||
request.bind(value, prop);
|
||||
}
|
||||
|
||||
/**
|
||||
* For compound types bind one of the underlying scalar values for a compound type.
|
||||
*/
|
||||
public void dmlBindObject(BindableRequest request, Object bean) throws SQLException {
|
||||
|
||||
Object value = null;
|
||||
if (bean != null) {
|
||||
value = prop.getValueObject(bean);
|
||||
}
|
||||
request.bind(value, prop);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.deploy.generatedproperty.GeneratedProperty;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Bindable for insert on a property with a GeneratedProperty.
|
||||
* <p>
|
||||
* This is typically a 'insert timestamp', 'update timestamp' or 'counter'.
|
||||
* </p>
|
||||
*/
|
||||
public class BindablePropertyInsertGenerated extends BindableProperty {
|
||||
|
||||
private final GeneratedProperty gen;
|
||||
|
||||
public BindablePropertyInsertGenerated(BeanProperty prop, GeneratedProperty gen) {
|
||||
super(prop);
|
||||
this.gen = gen;
|
||||
}
|
||||
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
|
||||
Object value = gen.getInsertValue(prop, bean, request.now());
|
||||
|
||||
// generated value should be the correct type
|
||||
if (bean != null) {
|
||||
// support PropertyChangeSupport
|
||||
//prop.setValueIntercept(bean, value);
|
||||
prop.setValue(bean, value);
|
||||
}
|
||||
request.bind(value, prop);
|
||||
}
|
||||
|
||||
/**
|
||||
* Always bind on Insert SET.
|
||||
*/
|
||||
@Override
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
request.appendColumn(prop.getDbColumn());
|
||||
}
|
||||
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.deploy.generatedproperty.GeneratedProperty;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Bindable for update on a property with a GeneratedProperty.
|
||||
* <p>
|
||||
* This is typically a 'update timestamp' or 'counter'.
|
||||
* </p>
|
||||
*/
|
||||
public class BindablePropertyUpdateGenerated extends BindableProperty {
|
||||
|
||||
private final GeneratedProperty gen;
|
||||
|
||||
public BindablePropertyUpdateGenerated(BeanProperty prop, GeneratedProperty gen) {
|
||||
super(prop);
|
||||
this.gen = gen;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add BindablePropertyUpdateGenerated if the property is loaded.
|
||||
*/
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
if (gen.includeInAllUpdates()) {
|
||||
list.add(this);
|
||||
} else if (request.isLoadedProperty(prop)) {
|
||||
list.add(this);
|
||||
}
|
||||
}
|
||||
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
|
||||
Object value = gen.getUpdateValue(prop, bean, request.now());
|
||||
|
||||
// generated value should be the correct type
|
||||
request.bind(value, prop);
|
||||
|
||||
if (prop.isVersion()) {
|
||||
if (request.getPersistRequest().isLoadedProperty(prop)) {
|
||||
// set to the bean after the where clause has been generated
|
||||
request.registerGeneratedVersion(value);
|
||||
}
|
||||
} else {
|
||||
// @WhenModified set without invoking interception
|
||||
prop.setValueChanged(bean, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Always bind on Insert SET.
|
||||
*/
|
||||
@Override
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
request.appendColumn(prop.getDbColumn());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Request object passed to bindables.
|
||||
*/
|
||||
public interface BindableRequest {
|
||||
|
||||
/**
|
||||
* Set the id for use with summary level logging.
|
||||
*/
|
||||
void setIdValue(Object idValue);
|
||||
|
||||
/**
|
||||
* Bind the value to a PreparedStatement.
|
||||
* <p>
|
||||
* Takes into account logicalType to dbType conversion if required.
|
||||
* </p>
|
||||
* <p>
|
||||
* Returns the value that was bound (and was potentially converted from
|
||||
* logicalType to dbType.
|
||||
* </p>
|
||||
*/
|
||||
void bind(Object value, BeanProperty prop) throws SQLException;
|
||||
|
||||
/**
|
||||
* Bind a raw value. Used to bind the discriminator column.
|
||||
*/
|
||||
void bind(Object value, int sqlType) throws SQLException;
|
||||
|
||||
/**
|
||||
* Bind a raw value with a placeHolder to put into the transaction log.
|
||||
*/
|
||||
void bindNoLog(Object value, int sqlType, String logPlaceHolder) throws SQLException;
|
||||
|
||||
/**
|
||||
* Bind the value to the preparedStatement without logging.
|
||||
*/
|
||||
void bindNoLog(Object value, BeanProperty prop) throws SQLException;
|
||||
|
||||
/**
|
||||
* Register the value from a update GeneratedValue. This can only be set to
|
||||
* the bean property after the where clause has bean built.
|
||||
*/
|
||||
void registerGeneratedVersion(Object value);
|
||||
|
||||
/**
|
||||
* Return the original PersistRequest.
|
||||
*/
|
||||
PersistRequestBean<?> getPersistRequest();
|
||||
|
||||
/**
|
||||
* Return the system current time in millis. This is expected to the same time used
|
||||
* by multiple generated properties for a single request.
|
||||
*/
|
||||
long now();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.core.PersistRequestBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import io.ebeaninternal.server.deploy.id.ImportedId;
|
||||
import io.ebeaninternal.server.persist.dml.GenerateDmlRequest;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Bindable for a unidirectional relationship.
|
||||
* <p>
|
||||
* This inserts the foreign key value that is retrieved from the id of the
|
||||
* parentBean.
|
||||
* </p>
|
||||
*/
|
||||
public class BindableUnidirectional implements Bindable {
|
||||
|
||||
private final BeanPropertyAssocOne<?> unidirectional;
|
||||
|
||||
private final ImportedId importedId;
|
||||
|
||||
private final BeanDescriptor<?> desc;
|
||||
|
||||
public BindableUnidirectional(BeanDescriptor<?> desc, BeanPropertyAssocOne<?> unidirectional) {
|
||||
this.desc = desc;
|
||||
this.unidirectional = unidirectional;
|
||||
this.importedId = unidirectional.getImportedId();
|
||||
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "BindableShadowFKey " + unidirectional;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDraftOnly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
|
||||
throw new PersistenceException("Never called (for insert only)");
|
||||
}
|
||||
|
||||
public void dmlAppend(GenerateDmlRequest request) {
|
||||
// always included (in insert)
|
||||
importedId.dmlAppend(request);
|
||||
}
|
||||
|
||||
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
|
||||
PersistRequestBean<?> persistRequest = request.getPersistRequest();
|
||||
Object parentBean = persistRequest.getParentBean();
|
||||
|
||||
if (parentBean == null) {
|
||||
Class<?> localType = desc.getBeanType();
|
||||
Class<?> targetType = unidirectional.getTargetType();
|
||||
|
||||
String msg = "Error inserting bean [" + localType + "] with unidirectional relationship. ";
|
||||
msg += "For inserts you must use cascade save on the master bean [" + targetType + "].";
|
||||
throw new PersistenceException(msg);
|
||||
}
|
||||
|
||||
importedId.bind(request, (EntityBean) parentBean);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import io.ebeaninternal.server.persist.dml.DmlMode;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A factory that builds Bindable for BeanPropertyAssocOne properties.
|
||||
*/
|
||||
public class FactoryAssocOnes {
|
||||
|
||||
public FactoryAssocOnes() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add foreign key columns from associated one beans.
|
||||
*/
|
||||
public void create(List<Bindable> list, BeanDescriptor<?> desc, DmlMode mode) {
|
||||
|
||||
BeanPropertyAssocOne<?>[] ones = desc.propertiesOneImported();
|
||||
|
||||
for (BeanPropertyAssocOne<?> one : ones) {
|
||||
if (!one.isImportedPrimaryKey()) {
|
||||
switch (mode) {
|
||||
case INSERT:
|
||||
if (!one.isInsertable()) {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
case UPDATE:
|
||||
if (!one.isUpdateable()) {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
list.add(new BindableAssocOne(one));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.persist.dml.DmlMode;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Add base properties to the BindableList for a bean type.
|
||||
* <p>
|
||||
* This excludes unique embedded and associated properties.
|
||||
* </p>
|
||||
*/
|
||||
public class FactoryBaseProperties {
|
||||
|
||||
private final FactoryProperty factoryProperty;
|
||||
|
||||
|
||||
public FactoryBaseProperties(boolean bindEncryptDataFirst) {
|
||||
factoryProperty = new FactoryProperty(bindEncryptDataFirst);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add Bindable for the base properties to the list.
|
||||
*/
|
||||
public void create(List<Bindable> list, BeanDescriptor<?> desc, DmlMode mode, boolean withLobs) {
|
||||
|
||||
for (BeanProperty prop : desc.propertiesBaseScalar()) {
|
||||
Bindable item = factoryProperty.create(prop, mode, withLobs);
|
||||
if (item != null) {
|
||||
list.add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import io.ebeaninternal.server.persist.dml.DmlMode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A factory that builds Bindable for embedded bean properties.
|
||||
*/
|
||||
public class FactoryEmbedded {
|
||||
|
||||
private final FactoryProperty factoryProperty;
|
||||
|
||||
public FactoryEmbedded(boolean bindEncryptDataFirst) {
|
||||
factoryProperty = new FactoryProperty(bindEncryptDataFirst);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add bindable for the embedded properties to the list.
|
||||
*/
|
||||
public void create(List<Bindable> list, BeanDescriptor<?> desc, DmlMode mode, boolean withLobs) {
|
||||
|
||||
BeanPropertyAssocOne<?>[] embedded = desc.propertiesEmbedded();
|
||||
|
||||
for (BeanPropertyAssocOne<?> anEmbedded : embedded) {
|
||||
|
||||
BeanProperty[] props = anEmbedded.getProperties();
|
||||
|
||||
List<Bindable> bindList = new ArrayList<>(props.length);
|
||||
|
||||
for (BeanProperty prop : props) {
|
||||
Bindable item = factoryProperty.create(prop, mode, withLobs);
|
||||
if (item != null) {
|
||||
bindList.add(item);
|
||||
}
|
||||
}
|
||||
|
||||
list.add(new BindableEmbedded(anEmbedded, bindList));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
|
||||
/**
|
||||
* Create a Bindable for the ids of a bean type.
|
||||
*/
|
||||
public class FactoryId {
|
||||
|
||||
public FactoryId() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add uniqueId properties.
|
||||
*/
|
||||
public BindableId createId(BeanDescriptor<?> desc) {
|
||||
|
||||
BeanProperty id = desc.getIdProperty();
|
||||
if (id == null) {
|
||||
return new BindableIdEmpty();
|
||||
|
||||
}
|
||||
if (!id.isEmbedded()) {
|
||||
return new BindableIdScalar(id);
|
||||
|
||||
} else {
|
||||
BeanPropertyAssocOne<?> embId = (BeanPropertyAssocOne<?>) id;
|
||||
return new BindableIdEmbedded(embId, desc);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.deploy.generatedproperty.GeneratedProperty;
|
||||
import io.ebeaninternal.server.persist.dml.DmlMode;
|
||||
|
||||
/**
|
||||
* Creates the appropriate Bindable for a BeanProperty.
|
||||
* <p>
|
||||
* Lob properties can be excluded and it creates BindablePropertyInsertGenerated
|
||||
* and BindablePropertyUpdateGenerated as required.
|
||||
* </p>
|
||||
*/
|
||||
public class FactoryProperty {
|
||||
|
||||
private final boolean bindEncryptDataFirst;
|
||||
|
||||
public FactoryProperty(boolean bindEncryptDataFirst) {
|
||||
this.bindEncryptDataFirst = bindEncryptDataFirst;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Bindable for the property given the mode and withLobs flag.
|
||||
*/
|
||||
public Bindable create(BeanProperty prop, DmlMode mode, boolean withLobs) {
|
||||
|
||||
if (DmlMode.INSERT.equals(mode) && !prop.isDbInsertable()) {
|
||||
return null;
|
||||
}
|
||||
if (DmlMode.UPDATE.equals(mode) && !prop.isDbUpdatable()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (prop.isLob()) {
|
||||
if (!withLobs) {
|
||||
// Lob exclusion
|
||||
return null;
|
||||
} else {
|
||||
return prop.isDbEncrypted() ? new BindableEncryptedProperty(prop, bindEncryptDataFirst) : new BindableProperty(prop);
|
||||
}
|
||||
}
|
||||
|
||||
GeneratedProperty gen = prop.getGeneratedProperty();
|
||||
if (gen != null) {
|
||||
if (DmlMode.INSERT.equals(mode)) {
|
||||
if (gen.includeInInsert()) {
|
||||
return new BindablePropertyInsertGenerated(prop, gen);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
if (DmlMode.UPDATE.equals(mode)) {
|
||||
if (gen.includeInUpdate()) {
|
||||
return new BindablePropertyUpdateGenerated(prop, gen);
|
||||
} else {
|
||||
// An 'Insert Timestamp' is never updated
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return prop.isDbEncrypted() ? new BindableEncryptedProperty(prop, bindEncryptDataFirst) : new BindableProperty(prop);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
/**
|
||||
* Creates a Bindable to support version concurrency where clauses.
|
||||
*/
|
||||
public class FactoryVersion {
|
||||
|
||||
|
||||
public FactoryVersion() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Bindable for the version property(s) for a bean type.
|
||||
*/
|
||||
public Bindable create(BeanDescriptor<?> desc) {
|
||||
|
||||
BeanProperty versionProperty = desc.getVersionProperty();
|
||||
if (versionProperty == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new BindableProperty(versionProperty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package io.ebeaninternal.server.persist.dmlbind;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanProperty;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
|
||||
/**
|
||||
* Matches local embedded id properties to 'matching' properties from a
|
||||
* ManyToOne associated bean that is a 'imported primary key'.
|
||||
* <p>
|
||||
* This object is designed to help BindableIdEmbedded and BindableIdMap to
|
||||
* create a concatenated id from the id values from ManyToOne associated beans.
|
||||
* This can be done when those ManyToOne associated beans make up the primary
|
||||
* key. This typically means the BindableIdEmbedded is for a intersection table
|
||||
* of a Many to Many relationship.
|
||||
* </p>
|
||||
*/
|
||||
class MatchedImportedProperty {
|
||||
|
||||
private final BeanPropertyAssocOne<?> assocOne;
|
||||
|
||||
private final BeanProperty foreignProp;
|
||||
|
||||
private final BeanProperty localProp;
|
||||
|
||||
protected MatchedImportedProperty(BeanPropertyAssocOne<?> assocOne, BeanProperty foreignProp,
|
||||
BeanProperty localProp) {
|
||||
this.assocOne = assocOne;
|
||||
this.foreignProp = foreignProp;
|
||||
this.localProp = localProp;
|
||||
}
|
||||
|
||||
protected void populate(EntityBean sourceBean, EntityBean destBean) {
|
||||
Object assocBean = assocOne.getValue(sourceBean);
|
||||
if (assocBean == null) {
|
||||
String msg = "The assoc bean for " + assocOne + " is null?";
|
||||
throw new NullPointerException(msg);
|
||||
}
|
||||
|
||||
Object value = foreignProp.getValue((EntityBean) assocBean);
|
||||
localProp.setValue(destBean, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the array of matchedImportedProperty based on the properties and descriptor.
|
||||
*/
|
||||
protected static MatchedImportedProperty[] build(BeanProperty[] props, BeanDescriptor<?> desc) {
|
||||
|
||||
MatchedImportedProperty[] matches = new MatchedImportedProperty[props.length];
|
||||
|
||||
for (int i = 0; i < props.length; i++) {
|
||||
// find matching assoc one property for dbColumn
|
||||
matches[i] = MatchedImportedProperty.findMatch(props[i], desc);
|
||||
if (matches[i] == null) {
|
||||
// ok, the assoc ones are not on the bean?
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
private static MatchedImportedProperty findMatch(BeanProperty prop, BeanDescriptor<?> desc) {
|
||||
|
||||
// find matching against the local database column
|
||||
String dbColumn = prop.getDbColumn();
|
||||
|
||||
BeanPropertyAssocOne<?>[] assocOnes = desc.propertiesOne();
|
||||
for (BeanPropertyAssocOne<?> assocOne1 : assocOnes) {
|
||||
if (assocOne1.isImportedPrimaryKey()) {
|
||||
|
||||
// search using the ImportedId from the assoc one
|
||||
BeanProperty foreignMatch = assocOne1.getImportedId().findMatchImport(dbColumn);
|
||||
|
||||
if (foreignMatch != null) {
|
||||
return new MatchedImportedProperty(assocOne1, foreignMatch, prop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// there was no matching assoc one property.
|
||||
// example UserRole bean missing assoc one to User?
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
|
||||
<TITLE>Bindable objects to support Bean DML</TITLE>
|
||||
</HEAD>
|
||||
<Body BGCOLOR="#ffffff">
|
||||
Bindable objects to support Bean DML
|
||||
|
||||
</Body>
|
||||
</HTML>
|
||||
@@ -0,0 +1,15 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
|
||||
<TITLE>Persistence Implementation</TITLE>
|
||||
</HEAD>
|
||||
<Body BGCOLOR="#ffffff">
|
||||
Persistence Implementation
|
||||
|
||||
<p>
|
||||
Implementing the saving and deleting of beans, and the executing of
|
||||
updateable and callable sql.
|
||||
</p>
|
||||
|
||||
</Body>
|
||||
</HTML>
|
||||
Reference in new issue
Block a user