No effective change - change newline char

This commit is contained in:
rbygrave committed 2015-05-09 01:09:57 +12:00
1 parent 4143c0de26
commit 4eaa6adf08
58 files changed
+7127 -7127

No files matched your search

@@ -1,56 +1,56 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.persistence.OptimisticLockException;
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* 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.
*/
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 = new DataBind(pstmt);
meta.bind(persistRequest, this);
logSql(sql);
}
/**
* Execute the delete non-batch.
*/
public void execute() throws SQLException, OptimisticLockException {
int rowCount = dataBind.executeUpdate();
checkRowCount(rowCount);
}
public void registerDerivedRelationship(DerivedRelationshipData assocBean) {
throw new RuntimeException("Never called on delete");
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.persistence.OptimisticLockException;
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* 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.
*/
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 = new DataBind(pstmt);
meta.bind(persistRequest, this);
logSql(sql);
}
/**
* Execute the delete non-batch.
*/
public void execute() throws SQLException, OptimisticLockException {
int rowCount = dataBind.executeUpdate();
checkRowCount(rowCount);
}
public void registerDerivedRelationship(DerivedRelationshipData assocBean) {
throw new RuntimeException("Never called on delete");
}
}
@@ -1,112 +1,112 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableId;
/**
* 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 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;
this.sqlNone = genSql(ConcurrencyMode.NONE);
this.sqlVersion = genSql(ConcurrencyMode.VERSION);
}
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) throws SQLException {
if (id.isEmpty()) {
throw new IllegalStateException("Can not deleteById on " + request.getFullName() + " as no @Id property");
}
switch (request.determineConcurrencyMode()) {
case NONE:
return sqlNone;
case VERSION:
return sqlVersion;
default:
throw new RuntimeException("Invalid mode " + request.determineConcurrencyMode());
}
}
private String genSql(ConcurrencyMode conMode) {
// delete ... where bcol=? and bc1=? and bc2 is null and ...
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringAsNull);
request.append("delete from ").append(tableName);
request.append(" where ");
request.setWhereIdMode();
id.dmlAppend(request);
if (ConcurrencyMode.VERSION.equals(conMode)) {
if (version == null) {
return null;
}
version.dmlAppend(request);
}
return request.toString();
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableId;
/**
* 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 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;
this.sqlNone = genSql(ConcurrencyMode.NONE);
this.sqlVersion = genSql(ConcurrencyMode.VERSION);
}
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) throws SQLException {
if (id.isEmpty()) {
throw new IllegalStateException("Can not deleteById on " + request.getFullName() + " as no @Id property");
}
switch (request.determineConcurrencyMode()) {
case NONE:
return sqlNone;
case VERSION:
return sqlVersion;
default:
throw new RuntimeException("Invalid mode " + request.determineConcurrencyMode());
}
}
private String genSql(ConcurrencyMode conMode) {
// delete ... where bcol=? and bc1=? and bc2 is null and ...
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringAsNull);
request.append("delete from ").append(tableName);
request.append(" where ");
request.setWhereIdMode();
id.dmlAppend(request);
if (ConcurrencyMode.VERSION.equals(conMode)) {
if (version == null) {
return null;
}
version.dmlAppend(request);
}
return request.toString();
}
}
@@ -1,103 +1,103 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.PersistRequest;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
import com.avaje.ebeaninternal.server.persist.BeanPersister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 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 static final Logger logger = LoggerFactory.getLogger(DmlBeanPersister.class);
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 void delete(PersistRequestBean<?> request) {
DeleteHandler delete = new DeleteHandler(request, deleteMeta);
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 void execute(PersistRequestBean<?> request, PersistHandler handler) {
boolean batched = request.isBatched();
try {
handler.bind();
if (batched) {
handler.addBatch();
} else {
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) {
try {
handler.close();
} catch (SQLException e) {
logger.error(null, e);
}
}
}
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.PersistRequest;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
import com.avaje.ebeaninternal.server.persist.BeanPersister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 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 static final Logger logger = LoggerFactory.getLogger(DmlBeanPersister.class);
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 void delete(PersistRequestBean<?> request) {
DeleteHandler delete = new DeleteHandler(request, deleteMeta);
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 void execute(PersistRequestBean<?> request, PersistHandler handler) {
boolean batched = request.isBatched();
try {
handler.bind();
if (batched) {
handler.addBatch();
} else {
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) {
try {
handler.close();
} catch (SQLException e) {
logger.error(null, e);
}
}
}
}
}
@@ -1,33 +1,33 @@
package com.avaje.ebeaninternal.server.persist.dml;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.persist.BeanPersister;
import com.avaje.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) {
UpdateMeta updMeta = metaFactory.createUpdate(desc);
DeleteMeta delMeta = metaFactory.createDelete(desc);
InsertMeta insMeta = metaFactory.createInsert(desc);
return new DmlBeanPersister(updMeta, insMeta, delMeta);
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.persist.BeanPersister;
import com.avaje.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) {
UpdateMeta updMeta = metaFactory.createUpdate(desc);
DeleteMeta delMeta = metaFactory.createDelete(desc);
InsertMeta insMeta = metaFactory.createInsert(desc);
return new DmlBeanPersister(updMeta, insMeta, delMeta);
}
}
@@ -1,307 +1,307 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.persistence.OptimisticLockException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.core.PstmtBatch;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.lib.util.Str;
import com.avaje.ebeaninternal.server.persist.BatchedPstmt;
import com.avaje.ebeaninternal.server.persist.BatchedPstmtHolder;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableRequest;
import com.avaje.ebeaninternal.server.transaction.TransactionManager;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* 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;
/**
* The PreparedStatement used for the dml.
*/
protected DataBind dataBind;
protected String sql;
protected ArrayList<UpdateGenValue> updateGenValues;
protected DmlHandler(PersistRequestBean<?> persistRequest, boolean emptyStringToNull) {
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;
}
}
public PersistRequestBean<?> getPersistRequest() {
return persistRequest;
}
/**
* Get the sql and bind the statement.
*/
public abstract void bind() throws SQLException;
/**
* Execute now for non-batch execution.
*/
public abstract void execute() throws SQLException;
/**
* Check the rowCount.
*/
protected void checkRowCount(int rowCount) throws SQLException, 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.
*/
public void addBatch() throws SQLException {
PstmtBatch pstmtBatch = persistRequest.getPstmtBatch();
if (pstmtBatch != null) {
pstmtBatch.addBatch(dataBind.getPstmt());
} else {
dataBind.getPstmt().addBatch();
}
}
/**
* Close the underlying statement.
*/
public void close() {
try {
if (dataBind != null) {
dataBind.close();
}
} catch (SQLException ex) {
logger.error(null, ex);
}
}
/**
* Return the bind log.
*/
public String getBindLog() {
return bindLog == null ? "" : bindLog.toString();
}
/**
* Set the Id value that was bound. This value is used for logging summary
* level information.
*/
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.
*/
public Object bind(String propName, Object value, int sqlType) throws SQLException {
if (logLevelSql) {
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);
}
}
bindLog.append(",");
}
dataBind.setObject(value, sqlType);
return value;
}
public Object bindNoLog(Object value, int sqlType, String logPlaceHolder) throws SQLException {
if (logLevelSql) {
bindLog.append(logPlaceHolder).append(" ");
}
dataBind.setObject(value, sqlType);
return value;
}
/**
* Bind the value to the preparedStatement.
*/
public Object bind(Object value, BeanProperty prop) throws SQLException {
return bindInternal(logLevelSql, value, prop);
}
/**
* Bind the value to the preparedStatement without logging.
*/
public Object bindNoLog(Object value, BeanProperty prop) throws SQLException {
return bindInternal(false, value, prop);
}
private Object bindInternal(boolean log, Object value, BeanProperty prop) throws SQLException {
if (log) {
if (prop.isLob()) {
bindLog.append("[LOB]");
} else {
String sv = String.valueOf(value);
if (sv.length() > 50) {
sv = sv.substring(0, 47) + "...";
}
bindLog.append(sv);
}
bindLog.append(",");
}
// do the actual binding to PreparedStatement
prop.bind(dataBind, value);
return 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>
*/
public void registerUpdateGenValue(BeanProperty prop, EntityBean bean, Object value) {
if (updateGenValues == null) {
updateGenValues = new ArrayList<UpdateGenValue>();
}
updateGenValues.add(new UpdateGenValue(prop, bean, value));
}
/**
* Set any update generated values to the bean. Must be called after where
* clause has been bound.
*/
public void setUpdateGenValues() {
if (updateGenValues != null) {
for (int i = 0; i < updateGenValues.size(); i++) {
UpdateGenValue updGenVal = updateGenValues.get(i);
updGenVal.setValue();
}
}
}
/**
* 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);
PstmtBatch pstmtBatch = request.getPstmtBatch();
if (pstmtBatch != null) {
pstmtBatch.setBatchSize(stmt, t.getBatchControl().getBatchSize());
}
BatchedPstmt bs = new BatchedPstmt(stmt, genKeys, sql, request.getPstmtBatch(), true);
batch.addStmt(bs, request);
return stmt;
}
/**
* Hold the values from GeneratedValue that need to be set to the bean
* property after the where clause has been built.
*/
private static final class UpdateGenValue {
private final BeanProperty property;
private final EntityBean bean;
private final Object value;
private UpdateGenValue(BeanProperty property, EntityBean bean, Object value) {
this.property = property;
this.bean = bean;
this.value = value;
}
/**
* Set the value to the bean property.
*/
private void setValue() {
// support PropertyChangeSupport
property.setValueIntercept(bean, value);
}
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.persistence.OptimisticLockException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.core.PstmtBatch;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.lib.util.Str;
import com.avaje.ebeaninternal.server.persist.BatchedPstmt;
import com.avaje.ebeaninternal.server.persist.BatchedPstmtHolder;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableRequest;
import com.avaje.ebeaninternal.server.transaction.TransactionManager;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* 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;
/**
* The PreparedStatement used for the dml.
*/
protected DataBind dataBind;
protected String sql;
protected ArrayList<UpdateGenValue> updateGenValues;
protected DmlHandler(PersistRequestBean<?> persistRequest, boolean emptyStringToNull) {
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;
}
}
public PersistRequestBean<?> getPersistRequest() {
return persistRequest;
}
/**
* Get the sql and bind the statement.
*/
public abstract void bind() throws SQLException;
/**
* Execute now for non-batch execution.
*/
public abstract void execute() throws SQLException;
/**
* Check the rowCount.
*/
protected void checkRowCount(int rowCount) throws SQLException, 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.
*/
public void addBatch() throws SQLException {
PstmtBatch pstmtBatch = persistRequest.getPstmtBatch();
if (pstmtBatch != null) {
pstmtBatch.addBatch(dataBind.getPstmt());
} else {
dataBind.getPstmt().addBatch();
}
}
/**
* Close the underlying statement.
*/
public void close() {
try {
if (dataBind != null) {
dataBind.close();
}
} catch (SQLException ex) {
logger.error(null, ex);
}
}
/**
* Return the bind log.
*/
public String getBindLog() {
return bindLog == null ? "" : bindLog.toString();
}
/**
* Set the Id value that was bound. This value is used for logging summary
* level information.
*/
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.
*/
public Object bind(String propName, Object value, int sqlType) throws SQLException {
if (logLevelSql) {
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);
}
}
bindLog.append(",");
}
dataBind.setObject(value, sqlType);
return value;
}
public Object bindNoLog(Object value, int sqlType, String logPlaceHolder) throws SQLException {
if (logLevelSql) {
bindLog.append(logPlaceHolder).append(" ");
}
dataBind.setObject(value, sqlType);
return value;
}
/**
* Bind the value to the preparedStatement.
*/
public Object bind(Object value, BeanProperty prop) throws SQLException {
return bindInternal(logLevelSql, value, prop);
}
/**
* Bind the value to the preparedStatement without logging.
*/
public Object bindNoLog(Object value, BeanProperty prop) throws SQLException {
return bindInternal(false, value, prop);
}
private Object bindInternal(boolean log, Object value, BeanProperty prop) throws SQLException {
if (log) {
if (prop.isLob()) {
bindLog.append("[LOB]");
} else {
String sv = String.valueOf(value);
if (sv.length() > 50) {
sv = sv.substring(0, 47) + "...";
}
bindLog.append(sv);
}
bindLog.append(",");
}
// do the actual binding to PreparedStatement
prop.bind(dataBind, value);
return 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>
*/
public void registerUpdateGenValue(BeanProperty prop, EntityBean bean, Object value) {
if (updateGenValues == null) {
updateGenValues = new ArrayList<UpdateGenValue>();
}
updateGenValues.add(new UpdateGenValue(prop, bean, value));
}
/**
* Set any update generated values to the bean. Must be called after where
* clause has been bound.
*/
public void setUpdateGenValues() {
if (updateGenValues != null) {
for (int i = 0; i < updateGenValues.size(); i++) {
UpdateGenValue updGenVal = updateGenValues.get(i);
updGenVal.setValue();
}
}
}
/**
* 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);
PstmtBatch pstmtBatch = request.getPstmtBatch();
if (pstmtBatch != null) {
pstmtBatch.setBatchSize(stmt, t.getBatchControl().getBatchSize());
}
BatchedPstmt bs = new BatchedPstmt(stmt, genKeys, sql, request.getPstmtBatch(), true);
batch.addStmt(bs, request);
return stmt;
}
/**
* Hold the values from GeneratedValue that need to be set to the bean
* property after the where clause has been built.
*/
private static final class UpdateGenValue {
private final BeanProperty property;
private final EntityBean bean;
private final Object value;
private UpdateGenValue(BeanProperty property, EntityBean bean, Object value) {
this.property = property;
this.bean = bean;
this.value = value;
}
/**
* Set the value to the bean property.
*/
private void setValue() {
// support PropertyChangeSupport
property.setValueIntercept(bean, value);
}
}
}
@@ -1,234 +1,234 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.Message;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.persist.DmlUtil;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* 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.isConcatinatedKey();
}
/**
* Generate and bind the insert statement.
*/
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);
PreparedStatement pstmt;
if (persistRequest.isBatched()) {
pstmt = getPstmt(t, sql, persistRequest, useGeneratedKeys);
} else {
pstmt = getPstmt(t, sql, useGeneratedKeys);
}
dataBind = new DataBind(pstmt);
// bind the bean property values
meta.bind(this, bean, withId);
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.
*/
public void execute() throws SQLException, OptimisticLockException {
int rc = 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(rc);
executeDerivedRelationships();
persistRequest.postInsert();
}
protected void executeDerivedRelationships() {
List<DerivedRelationshipData> derivedRelationships = persistRequest.getDerivedRelationships();
if (derivedRelationships != null) {
SpiEbeanServer ebeanServer = (SpiEbeanServer)persistRequest.getEbeanServer();
for (int i = 0; i < derivedRelationships.size(); i++) {
DerivedRelationshipData derivedRelationshipData = derivedRelationships.get(i);
BeanDescriptor<?> beanDescriptor = ebeanServer.getBeanDescriptor(derivedRelationshipData.getBean().getClass());
BeanProperty prop = beanDescriptor.getBeanProperty(derivedRelationshipData.getLogicalName());
EntityBean entityBean = (EntityBean)derivedRelationshipData.getBean();
entityBean._ebean_getIntercept().markPropertyAsChanged(prop.getPropertyIndex());
ebeanServer.update(entityBean, transaction);
}
}
}
/**
* For non batch insert with generated keys.
*/
private void getGeneratedKeys() throws SQLException {
ResultSet rset = dataBind.getPstmt().getGeneratedKeys();
try {
if (rset.next()) {
Object idValue = rset.getObject(1);
if (idValue != null) {
persistRequest.setGeneratedKey(idValue);
}
} else {
throw new PersistenceException(Message.msg("persist.autoinc.norows"));
}
} finally {
try {
rset.close();
} catch (SQLException ex) {
String msg = "Error closing rset for returning generatedKeys?";
logger.warn(msg, ex);
}
}
}
/**
* 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();
if (rset.next()) {
Object idValue = rset.getObject(1);
if (idValue != null) {
persistRequest.setGeneratedKey(idValue);
}
} else {
throw new PersistenceException(Message.msg("persist.autoinc.norows"));
}
} finally {
try {
if (rset != null) {
rset.close();
}
} catch (SQLException ex) {
String msg = "Error closing rset for fetchGeneratedKeyUsingSelect?";
logger.warn(msg, ex);
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException ex) {
String msg = "Error closing stmt for fetchGeneratedKeyUsingSelect?";
logger.warn(msg, ex);
}
}
}
public void registerDerivedRelationship(DerivedRelationshipData derivedRelationship) {
persistRequest.getTransaction().registerDerivedRelationship(derivedRelationship);
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.Message;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.persist.DmlUtil;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* 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.isConcatinatedKey();
}
/**
* Generate and bind the insert statement.
*/
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);
PreparedStatement pstmt;
if (persistRequest.isBatched()) {
pstmt = getPstmt(t, sql, persistRequest, useGeneratedKeys);
} else {
pstmt = getPstmt(t, sql, useGeneratedKeys);
}
dataBind = new DataBind(pstmt);
// bind the bean property values
meta.bind(this, bean, withId);
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.
*/
public void execute() throws SQLException, OptimisticLockException {
int rc = 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(rc);
executeDerivedRelationships();
persistRequest.postInsert();
}
protected void executeDerivedRelationships() {
List<DerivedRelationshipData> derivedRelationships = persistRequest.getDerivedRelationships();
if (derivedRelationships != null) {
SpiEbeanServer ebeanServer = (SpiEbeanServer)persistRequest.getEbeanServer();
for (int i = 0; i < derivedRelationships.size(); i++) {
DerivedRelationshipData derivedRelationshipData = derivedRelationships.get(i);
BeanDescriptor<?> beanDescriptor = ebeanServer.getBeanDescriptor(derivedRelationshipData.getBean().getClass());
BeanProperty prop = beanDescriptor.getBeanProperty(derivedRelationshipData.getLogicalName());
EntityBean entityBean = (EntityBean)derivedRelationshipData.getBean();
entityBean._ebean_getIntercept().markPropertyAsChanged(prop.getPropertyIndex());
ebeanServer.update(entityBean, transaction);
}
}
}
/**
* For non batch insert with generated keys.
*/
private void getGeneratedKeys() throws SQLException {
ResultSet rset = dataBind.getPstmt().getGeneratedKeys();
try {
if (rset.next()) {
Object idValue = rset.getObject(1);
if (idValue != null) {
persistRequest.setGeneratedKey(idValue);
}
} else {
throw new PersistenceException(Message.msg("persist.autoinc.norows"));
}
} finally {
try {
rset.close();
} catch (SQLException ex) {
String msg = "Error closing rset for returning generatedKeys?";
logger.warn(msg, ex);
}
}
}
/**
* 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();
if (rset.next()) {
Object idValue = rset.getObject(1);
if (idValue != null) {
persistRequest.setGeneratedKey(idValue);
}
} else {
throw new PersistenceException(Message.msg("persist.autoinc.norows"));
}
} finally {
try {
if (rset != null) {
rset.close();
}
} catch (SQLException ex) {
String msg = "Error closing rset for fetchGeneratedKeyUsingSelect?";
logger.warn(msg, ex);
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException ex) {
String msg = "Error closing stmt for fetchGeneratedKeyUsingSelect?";
logger.warn(msg, ex);
}
}
}
public void registerDerivedRelationship(DerivedRelationshipData derivedRelationship) {
persistRequest.getTransaction().registerDerivedRelationship(derivedRelationship);
}
}
@@ -1,195 +1,195 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.InheritInfo;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableDiscriminator;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableId;
/**
* 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 BindableId id;
private final Bindable discriminator;
private final Bindable all;
private final boolean supportsGetGeneratedKeys;
private final boolean concatinatedKey;
private final String tableName;
/**
* 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, Bindable all) {
this.emptyStringToNull = dbPlatform.isTreatEmptyStringsAsNull();
this.tableName = desc.getBaseTable();
this.discriminator = getDiscriminator(desc);
this.id = id;
this.all = all;
this.shadowFKey = shadowFKey;
this.sqlWithId = genSql(false);
// only available for single Id property
if (id.isConcatenated()) {
// concatenated key
this.concatinatedKey = true;
this.identityDbColumns = null;
this.sqlNullId = 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);
}
}
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 isConcatinatedKey() {
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) throws SQLException {
if (withId) {
id.dmlBind(request, bean);
}
if (shadowFKey != null){
shadowFKey.dmlBind(request, bean);
}
if (discriminator != null){
discriminator.dmlBind(request, bean);
}
all.dmlBind(request, bean);
}
/**
* get the sql based whether the id value(s) are null.
*/
public String getSql(boolean withId) {
if (withId) {
return sqlWithId;
} else {
return sqlNullId;
}
}
private String genSql(boolean nullId) {
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringToNull, null, true);
request.setInsertSetMode();
request.append("insert into ").append(tableName);
request.append(" (");
if (!nullId) {
id.dmlAppend(request);
}
if (shadowFKey != null){
shadowFKey.dmlAppend(request);
}
if (discriminator != null){
discriminator.dmlAppend(request);
}
all.dmlAppend(request);
request.append(") values (");
request.append(request.getInsertBindBuffer());
request.append(")");
return request.toString();
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.InheritInfo;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableDiscriminator;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableId;
/**
* 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 BindableId id;
private final Bindable discriminator;
private final Bindable all;
private final boolean supportsGetGeneratedKeys;
private final boolean concatinatedKey;
private final String tableName;
/**
* 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, Bindable all) {
this.emptyStringToNull = dbPlatform.isTreatEmptyStringsAsNull();
this.tableName = desc.getBaseTable();
this.discriminator = getDiscriminator(desc);
this.id = id;
this.all = all;
this.shadowFKey = shadowFKey;
this.sqlWithId = genSql(false);
// only available for single Id property
if (id.isConcatenated()) {
// concatenated key
this.concatinatedKey = true;
this.identityDbColumns = null;
this.sqlNullId = 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);
}
}
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 isConcatinatedKey() {
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) throws SQLException {
if (withId) {
id.dmlBind(request, bean);
}
if (shadowFKey != null){
shadowFKey.dmlBind(request, bean);
}
if (discriminator != null){
discriminator.dmlBind(request, bean);
}
all.dmlBind(request, bean);
}
/**
* get the sql based whether the id value(s) are null.
*/
public String getSql(boolean withId) {
if (withId) {
return sqlWithId;
} else {
return sqlNullId;
}
}
private String genSql(boolean nullId) {
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringToNull, null, true);
request.setInsertSetMode();
request.append("insert into ").append(tableName);
request.append(" (");
if (!nullId) {
id.dmlAppend(request);
}
if (shadowFKey != null){
shadowFKey.dmlAppend(request);
}
if (discriminator != null){
discriminator.dmlAppend(request);
}
all.dmlAppend(request);
request.append(") values (");
request.append(request.getInsertBindBuffer());
request.append(")");
return request.toString();
}
}
@@ -1,112 +1,112 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.util.ArrayList;
import java.util.List;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebean.config.dbplatform.DbEncrypt;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableId;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableList;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableUnidirectional;
import com.avaje.ebeaninternal.server.persist.dmlbind.FactoryAssocOnes;
import com.avaje.ebeaninternal.server.persist.dmlbind.FactoryBaseProperties;
import com.avaje.ebeaninternal.server.persist.dmlbind.FactoryEmbedded;
import com.avaje.ebeaninternal.server.persist.dmlbind.FactoryId;
import com.avaje.ebeaninternal.server.persist.dmlbind.FactoryVersion;
/**
* 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 ? true : 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<Bindable>();
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<Bindable>();
baseFact.create(allList, desc, DmlMode.INSERT, includeLobs);
embeddedFact.create(allList, desc, DmlMode.INSERT, includeLobs);
assocOneFact.create(allList, desc, DmlMode.INSERT);
Bindable 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);
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.util.ArrayList;
import java.util.List;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebean.config.dbplatform.DbEncrypt;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableId;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableList;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableUnidirectional;
import com.avaje.ebeaninternal.server.persist.dmlbind.FactoryAssocOnes;
import com.avaje.ebeaninternal.server.persist.dmlbind.FactoryBaseProperties;
import com.avaje.ebeaninternal.server.persist.dmlbind.FactoryEmbedded;
import com.avaje.ebeaninternal.server.persist.dmlbind.FactoryId;
import com.avaje.ebeaninternal.server.persist.dmlbind.FactoryVersion;
/**
* 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 ? true : 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<Bindable>();
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<Bindable>();
baseFact.create(allList, desc, DmlMode.INSERT, includeLobs);
embeddedFact.create(allList, desc, DmlMode.INSERT, includeLobs);
assocOneFact.create(allList, desc, DmlMode.INSERT);
Bindable 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);
}
}
@@ -1,34 +1,34 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
/**
* Implementation API for insert update and delete handlers.
*/
public interface PersistHandler {
/**
* Return the bind log.
*/
public String getBindLog();
/**
* Get the sql and bind the statement.
*/
public void bind() throws SQLException;
/**
* Add this for batch execution.
*/
public void addBatch() throws SQLException;
/**
* Execute now for non-batch execution.
*/
public void execute() throws SQLException;
/**
* Close resources including underlying preparedStatement.
*/
public void close() throws SQLException;
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
/**
* Implementation API for insert update and delete handlers.
*/
public interface PersistHandler {
/**
* Return the bind log.
*/
public String getBindLog();
/**
* Get the sql and bind the statement.
*/
public void bind() throws SQLException;
/**
* Add this for batch execution.
*/
public void addBatch() throws SQLException;
/**
* Execute now for non-batch execution.
*/
public void execute() throws SQLException;
/**
* Close resources including underlying preparedStatement.
*/
public void close() throws SQLException;
}
@@ -1,81 +1,81 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.persistence.OptimisticLockException;
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* 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.
*/
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 = new DataBind(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 void execute() throws SQLException, OptimisticLockException {
if (!emptySetClause){
int rowCount = dataBind.executeUpdate();
checkRowCount(rowCount);
}
}
public void registerDerivedRelationship(DerivedRelationshipData derivedRelationship) {
persistRequest.getTransaction().registerDerivedRelationship(derivedRelationship);
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.persistence.OptimisticLockException;
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* 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.
*/
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 = new DataBind(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 void execute() throws SQLException, OptimisticLockException {
if (!emptySetClause){
int rowCount = dataBind.executeUpdate();
checkRowCount(rowCount);
}
}
public void registerDerivedRelationship(DerivedRelationshipData derivedRelationship) {
persistRequest.getTransaction().registerDerivedRelationship(derivedRelationship);
}
}
@@ -1,191 +1,191 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableId;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableList;
/**
* 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 String sqlVersion;
private final String sqlNone;
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;
this.sqlNone = genSql(ConcurrencyMode.NONE, null, set);
this.sqlVersion = genSql(ConcurrencyMode.VERSION, null, set);
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) {
ConcurrencyMode mode = request.determineConcurrencyMode();
if (request.isDynamicUpdateSql()) {
return getDynamicUpdatePlan(mode, request);
}
// 'full bean' update...
switch (mode) {
case NONE:
return modeNoneUpdatePlan;
case VERSION:
return modeVersionUpdatePlan;
default:
throw new RuntimeException("Invalid mode " + mode);
}
}
private SpiUpdatePlan getDynamicUpdatePlan(ConcurrencyMode mode, PersistRequestBean<?> persistRequest) {
// we can use a cached UpdatePlan for the changed properties
EntityBeanIntercept ebi = persistRequest.getEntityBeanIntercept();
int hash = ebi.getDirtyPropertyHash();
BeanDescriptor<?> beanDescriptor = persistRequest.getBeanDescriptor();
BeanProperty versionProperty = beanDescriptor.getVersionProperty();
if (versionProperty != null) {
if (ebi.isLoadedProperty(versionProperty.getPropertyIndex())) {
hash = hash * 31 + 7;
}
}
Integer key = Integer.valueOf(hash);
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<Bindable>();
set.addToUpdate(persistRequest, list);
BindableList bindableList = new BindableList(list);
// build the SQL for this update statement
String sql = genSql(mode, persistRequest, bindableList);
updatePlan = new UpdatePlan(key, mode, sql, bindableList);
// add the UpdatePlan to the cache
beanDescriptor.putUpdatePlan(key, updatePlan);
return updatePlan;
}
private String genSql(ConcurrencyMode conMode, PersistRequestBean<?> persistRequest, BindableList bindableList) {
// update set col0=?, col1=?, col2=? where bcol=? and bc1=? and bc2=?
GenerateDmlRequest request;
if (persistRequest == null) {
// For generation of None and Version DML/SQL
request = new GenerateDmlRequest(emptyStringAsNull);
} else {
request = persistRequest.createGenerateDmlRequest(emptyStringAsNull);
}
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();
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableId;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableList;
/**
* 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 String sqlVersion;
private final String sqlNone;
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;
this.sqlNone = genSql(ConcurrencyMode.NONE, null, set);
this.sqlVersion = genSql(ConcurrencyMode.VERSION, null, set);
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) {
ConcurrencyMode mode = request.determineConcurrencyMode();
if (request.isDynamicUpdateSql()) {
return getDynamicUpdatePlan(mode, request);
}
// 'full bean' update...
switch (mode) {
case NONE:
return modeNoneUpdatePlan;
case VERSION:
return modeVersionUpdatePlan;
default:
throw new RuntimeException("Invalid mode " + mode);
}
}
private SpiUpdatePlan getDynamicUpdatePlan(ConcurrencyMode mode, PersistRequestBean<?> persistRequest) {
// we can use a cached UpdatePlan for the changed properties
EntityBeanIntercept ebi = persistRequest.getEntityBeanIntercept();
int hash = ebi.getDirtyPropertyHash();
BeanDescriptor<?> beanDescriptor = persistRequest.getBeanDescriptor();
BeanProperty versionProperty = beanDescriptor.getVersionProperty();
if (versionProperty != null) {
if (ebi.isLoadedProperty(versionProperty.getPropertyIndex())) {
hash = hash * 31 + 7;
}
}
Integer key = Integer.valueOf(hash);
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<Bindable>();
set.addToUpdate(persistRequest, list);
BindableList bindableList = new BindableList(list);
// build the SQL for this update statement
String sql = genSql(mode, persistRequest, bindableList);
updatePlan = new UpdatePlan(key, mode, sql, bindableList);
// add the UpdatePlan to the cache
beanDescriptor.putUpdatePlan(key, updatePlan);
return updatePlan;
}
private String genSql(ConcurrencyMode conMode, PersistRequestBean<?> persistRequest, BindableList bindableList) {
// update set col0=?, col1=?, col2=? where bcol=? and bc1=? and bc2=?
GenerateDmlRequest request;
if (persistRequest == null) {
// For generation of None and Version DML/SQL
request = new GenerateDmlRequest(emptyStringAsNull);
} else {
request = persistRequest.createGenerateDmlRequest(emptyStringAsNull);
}
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();
}
}
@@ -1,128 +1,128 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
/**
* Plan for executing bean updates for a given set of changed properties.
*/
public class UpdatePlan implements SpiUpdatePlan {
/**
* Special plan used when there is nothing in the set clause and the update should in fact be
* skipped. Occurs when the updated properties have updatable=false in their deployment.
*/
public static final UpdatePlan EMPTY_SET_CLAUSE = new UpdatePlan();
private final Integer 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.
*/
public UpdatePlan(ConcurrencyMode mode, String sql, Bindable set) {
this(null, mode, sql, set);
}
/**
* Create a UpdatePlan with a given key.
*/
public UpdatePlan(Integer 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();
}
/**
* Special constructor for emptySetClause=true instance.
*/
private UpdatePlan() {
this.emptySetClause = true;
this.key = Integer.valueOf(0);
this.mode = ConcurrencyMode.NONE;
this.sql = null;
this.set = null;
this.timeCreated = 0;
}
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);
// not strictly 'thread safe' but object assignment is atomic
Long touched = Long.valueOf(System.currentTimeMillis());
this.timeLastUsed = touched;
}
/**
* Return the time this plan was created.
*/
public long getTimeCreated() {
return timeCreated;
}
/**
* Return the time this plan was last used.
*/
public Long getTimeLastUsed() {
// not thread safe but atomic
return timeLastUsed;
}
/**
* Return the hash key.
*/
public Integer 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;
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
/**
* Plan for executing bean updates for a given set of changed properties.
*/
public class UpdatePlan implements SpiUpdatePlan {
/**
* Special plan used when there is nothing in the set clause and the update should in fact be
* skipped. Occurs when the updated properties have updatable=false in their deployment.
*/
public static final UpdatePlan EMPTY_SET_CLAUSE = new UpdatePlan();
private final Integer 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.
*/
public UpdatePlan(ConcurrencyMode mode, String sql, Bindable set) {
this(null, mode, sql, set);
}
/**
* Create a UpdatePlan with a given key.
*/
public UpdatePlan(Integer 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();
}
/**
* Special constructor for emptySetClause=true instance.
*/
private UpdatePlan() {
this.emptySetClause = true;
this.key = Integer.valueOf(0);
this.mode = ConcurrencyMode.NONE;
this.sql = null;
this.set = null;
this.timeCreated = 0;
}
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);
// not strictly 'thread safe' but object assignment is atomic
Long touched = Long.valueOf(System.currentTimeMillis());
this.timeLastUsed = touched;
}
/**
* Return the time this plan was created.
*/
public long getTimeCreated() {
return timeCreated;
}
/**
* Return the time this plan was last used.
*/
public Long getTimeLastUsed() {
// not thread safe but atomic
return timeLastUsed;
}
/**
* Return the hash key.
*/
public Integer 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;
}
}