Change license to Apache2 and reformat

This commit is contained in:
rbygrave committed 2012-09-15 00:00:08 +12:00
1 parent 96ce4c0ddf
commit 7aae897def
560 files changed
+73292 -85907

No files matched your search

@@ -1,99 +1,80 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
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.deploy.BeanProperty;
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();
boolean isBatch = t.isBatchThisRequest();
PreparedStatement pstmt;
if (isBatch) {
pstmt = getPstmt(t, sql, persistRequest, false);
} else {
logSql(sql);
pstmt = getPstmt(t, sql, false);
}
dataBind = new DataBind(pstmt);
bindLogAppend("Binding Delete [");
bindLogAppend(meta.getTableName());
bindLogAppend("] where[");
meta.bind(persistRequest, this);
bindLogAppend("]");
// log the binding to transaction log if requested
logBinding();
}
/**
* Execute the delete non-batch.
*/
public void execute() throws SQLException, OptimisticLockException {
int rowCount = dataBind.executeUpdate();
checkRowCount(rowCount);
}
@Override
public boolean isIncluded(BeanProperty prop) {
return prop.isDbUpdatable() && super.isIncluded(prop);
}
@Override
public boolean isIncludedWhere(BeanProperty prop) {
return prop.isDbUpdatable() && (loadedProps == null || loadedProps.contains(prop.getName()));
}
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.deploy.BeanProperty;
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();
boolean isBatch = t.isBatchThisRequest();
PreparedStatement pstmt;
if (isBatch) {
pstmt = getPstmt(t, sql, persistRequest, false);
} else {
logSql(sql);
pstmt = getPstmt(t, sql, false);
}
dataBind = new DataBind(pstmt);
bindLogAppend("Binding Delete [");
bindLogAppend(meta.getTableName());
bindLogAppend("] where[");
meta.bind(persistRequest, this);
bindLogAppend("]");
// log the binding to transaction log if requested
logBinding();
}
/**
* Execute the delete non-batch.
*/
public void execute() throws SQLException, OptimisticLockException {
int rowCount = dataBind.executeUpdate();
checkRowCount(rowCount);
}
@Override
public boolean isIncluded(BeanProperty prop) {
return prop.isDbUpdatable() && super.isIncluded(prop);
}
@Override
public boolean isIncludedWhere(BeanProperty prop) {
return prop.isDbUpdatable() && (loadedProps == null || loadedProps.contains(prop.getName()));
}
public void registerDerivedRelationship(DerivedRelationshipData assocBean) {
throw new RuntimeException("Never called on delete");
}
}
@@ -1,165 +1,146 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.Set;
import com.avaje.ebeaninternal.server.core.ConcurrencyMode;
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 Bindable all;
private final String tableName;
private final boolean emptyStringAsNull;
public DeleteMeta(boolean emptyStringAsNull, BeanDescriptor<?> desc, BindableId id, Bindable version, Bindable all) {
this.emptyStringAsNull = emptyStringAsNull;
this.tableName = desc.getBaseTable();
this.id = id;
this.version = version;
this.all = all;
sqlNone = genSql(ConcurrencyMode.NONE);
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 {
Object bean = persist.getBean();
id.dmlBind(bind, false, bean);
switch (persist.getConcurrencyMode()) {
case VERSION:
version.dmlBind(bind, false, bean);
break;
case ALL:
Object oldBean = persist.getOldValues();
all.dmlBindWhere(bind, true, oldBean);
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;
case ALL:
return genDynamicWhere(request.getLoadedProperties(), request.getOldValues());
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, false);
if (ConcurrencyMode.VERSION.equals(conMode)) {
if (version == null) {
return null;
}
version.dmlAppend(request, false);
} else if (ConcurrencyMode.ALL.equals(conMode)) {
throw new RuntimeException("Never called for ConcurrencyMode.ALL");
}
return request.toString();
}
/**
* Generate the sql dynamically for where using IS NULL for binding null
* values.
*/
private String genDynamicWhere(Set<String> includedProps, Object oldBean) throws SQLException {
// always has a preceding id property(s) so the first
// option is always ' and ' and not blank.
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringAsNull, includedProps, oldBean);
request.append(sqlNone);
request.setWhereMode();
all.dmlWhere(request, true, oldBean);
return request.toString();
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.Set;
import com.avaje.ebeaninternal.server.core.ConcurrencyMode;
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 Bindable all;
private final String tableName;
private final boolean emptyStringAsNull;
public DeleteMeta(boolean emptyStringAsNull, BeanDescriptor<?> desc, BindableId id, Bindable version, Bindable all) {
this.emptyStringAsNull = emptyStringAsNull;
this.tableName = desc.getBaseTable();
this.id = id;
this.version = version;
this.all = all;
sqlNone = genSql(ConcurrencyMode.NONE);
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 {
Object bean = persist.getBean();
id.dmlBind(bind, false, bean);
switch (persist.getConcurrencyMode()) {
case VERSION:
version.dmlBind(bind, false, bean);
break;
case ALL:
Object oldBean = persist.getOldValues();
all.dmlBindWhere(bind, true, oldBean);
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;
case ALL:
return genDynamicWhere(request.getLoadedProperties(), request.getOldValues());
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, false);
if (ConcurrencyMode.VERSION.equals(conMode)) {
if (version == null) {
return null;
}
version.dmlAppend(request, false);
} else if (ConcurrencyMode.ALL.equals(conMode)) {
throw new RuntimeException("Never called for ConcurrencyMode.ALL");
}
return request.toString();
}
/**
* Generate the sql dynamically for where using IS NULL for binding null
* values.
*/
private String genDynamicWhere(Set<String> includedProps, Object oldBean) throws SQLException {
// always has a preceding id property(s) so the first
// option is always ' and ' and not blank.
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringAsNull, includedProps, oldBean);
request.append(sqlNone);
request.setWhereMode();
all.dmlWhere(request, true, oldBean);
return request.toString();
}
}
@@ -1,129 +1,110 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
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;
/**
* 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 = Logger.getLogger(DmlBeanPersister.class.getName());
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(PersistRequest request, PersistHandler handler) {
SpiTransaction trans = request.getTransaction();
boolean batchThisRequest = trans.isBatchThisRequest();
try {
handler.bind();
if (batchThisRequest) {
handler.addBatch();
} else {
// immediate insert
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().logInternal(msg);
}
throw new PersistenceException(msg, e);
} finally {
if (!batchThisRequest && handler != null) {
try {
handler.close();
} catch (SQLException e) {
logger.log(Level.SEVERE, null, e);
}
}
}
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
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;
/**
* 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 = Logger.getLogger(DmlBeanPersister.class.getName());
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(PersistRequest request, PersistHandler handler) {
SpiTransaction trans = request.getTransaction();
boolean batchThisRequest = trans.isBatchThisRequest();
try {
handler.bind();
if (batchThisRequest) {
handler.addBatch();
} else {
// immediate insert
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().logInternal(msg);
}
throw new PersistenceException(msg, e);
} finally {
if (!batchThisRequest && handler != null) {
try {
handler.close();
} catch (SQLException e) {
logger.log(Level.SEVERE, null, e);
}
}
}
}
}
@@ -1,52 +1,33 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
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,418 +1,399 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.OptimisticLockException;
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.persist.BatchedPstmt;
import com.avaje.ebeaninternal.server.persist.BatchedPstmtHolder;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableRequest;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* Base class for Handler implementations.
*/
public abstract class DmlHandler implements PersistHandler, BindableRequest {
protected static final Logger logger = Logger.getLogger(DmlHandler.class.getName());
/**
* The originating request.
*/
protected final PersistRequestBean<?> persistRequest;
protected final StringBuilder bindLog;
protected final Set<String> loadedProps;
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;
private Set<String> additionalProps;
// private boolean checkDelta;
//
// private BeanDelta deltaBean;
protected DmlHandler(PersistRequestBean<?> persistRequest, boolean emptyStringToNull) {
this.persistRequest = persistRequest;
this.emptyStringToNull = emptyStringToNull;
this.loadedProps = persistRequest.getLoadedProperties();
this.transaction = persistRequest.getTransaction();
this.logLevelSql = transaction.isLogSql();
if (logLevelSql) {
this.bindLog = new StringBuilder();
} else {
this.bindLog = null;
}
}
// protected void setCheckDelta(boolean checkDelta) {
// this.checkDelta = checkDelta;
// }
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().log("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.log(Level.SEVERE, 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 bind information to the transaction log.
*/
protected void logBinding() {
if (logLevelSql) {
transaction.logInternal(bindLog.toString());
}
}
/**
* Log the sql to the transaction log.
*/
protected void logSql(String sql) {
if (logLevelSql) {
transaction.logInternal(sql);
}
}
public boolean isIncluded(BeanProperty prop) {
return (loadedProps == null || loadedProps.contains(prop.getName()));
}
public boolean isIncludedWhere(BeanProperty prop) {
if (prop.isDbEncrypted()){
// update without a version property ...
// for encrypted properties only include if it was
// also an updated/modified property
return isIncluded(prop);
}
return prop.isDbUpdatable() && (loadedProps == null || loadedProps.contains(prop.getName()));
}
/**
* Bind a raw value. Used to bind the discriminator column.
*/
public Object bind(String propName, Object value, int sqlType) throws SQLException {
if (logLevelSql) {
bindLog.append(propName).append("=");
bindLog.append(value).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, String propName, boolean bindNull) throws SQLException {
return bindInternal(logLevelSql, value, prop, propName, bindNull);
}
/**
* Bind the value to the preparedStatement without logging.
*/
public Object bindNoLog(Object value, BeanProperty prop, String propName, boolean bindNull) throws SQLException {
return bindInternal(false, value, prop, propName, bindNull);
}
private Object bindInternal(boolean log, Object value, BeanProperty prop, String propName, boolean bindNull) throws SQLException {
if (!bindNull){
if (emptyStringToNull && (value instanceof String) && ((String)value).length() == 0){
// support Oracle conversion of empty string to null
//value = prop.getDbNullValue(value);
value = null;
}
}
if (!bindNull && value == null) {
// where will have IS NULL clause so don't actually bind
if (log) {
bindLog.append(propName).append("=");
bindLog.append("null, ");
}
} else {
if (log) {
bindLog.append(propName).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);
}
bindLog.append(", ");
}
// do the actual binding to PreparedStatement
prop.bind(dataBind, value);
// if (checkDelta) {
// if (!prop.isId() && prop.isDeltaRequired()){
// if (deltaBean == null){
// deltaBean = persistRequest.createDeltaBean();
// transaction.getEvent().addBeanDelta(deltaBean);
// }
// deltaBean.add(prop, value);
// }
// }
}
return value;
}
/**
* Add the comment to the bind information log.
*/
protected void bindLogAppend(String comment) {
if (logLevelSql) {
bindLog.append(comment);
}
}
/**
* For generated properties set on insert register as additional
* loaded properties if required.
*/
public final void registerAdditionalProperty(String propertyName) {
if (loadedProps != null && !loadedProps.contains(propertyName)){
if (additionalProps == null){
additionalProps = new HashSet<String>();
}
additionalProps.add(propertyName);
}
}
/**
* Set any additional (generated) properties to the set of loaded properties
* if required.
*/
protected void setAdditionalProperties() {
if (additionalProps != null){
// additional generated properties set on insert
// added to the set of loaded properties
additionalProps.addAll(loadedProps);
persistRequest.setLoadedProps(additionalProps);
}
}
/**
* 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, Object bean, Object value) {
if (updateGenValues == null) {
updateGenValues = new ArrayList<UpdateGenValue>();
}
updateGenValues.add(new UpdateGenValue(prop, bean, value));
registerAdditionalProperty(prop.getName());
}
/**
* 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;
}
if (logLevelSql){
t.logInternal(sql);
}
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 Object bean;
private final Object value;
private UpdateGenValue(BeanProperty property, Object 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 java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.OptimisticLockException;
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.persist.BatchedPstmt;
import com.avaje.ebeaninternal.server.persist.BatchedPstmtHolder;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableRequest;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* Base class for Handler implementations.
*/
public abstract class DmlHandler implements PersistHandler, BindableRequest {
protected static final Logger logger = Logger.getLogger(DmlHandler.class.getName());
/**
* The originating request.
*/
protected final PersistRequestBean<?> persistRequest;
protected final StringBuilder bindLog;
protected final Set<String> loadedProps;
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;
private Set<String> additionalProps;
// private boolean checkDelta;
//
// private BeanDelta deltaBean;
protected DmlHandler(PersistRequestBean<?> persistRequest, boolean emptyStringToNull) {
this.persistRequest = persistRequest;
this.emptyStringToNull = emptyStringToNull;
this.loadedProps = persistRequest.getLoadedProperties();
this.transaction = persistRequest.getTransaction();
this.logLevelSql = transaction.isLogSql();
if (logLevelSql) {
this.bindLog = new StringBuilder();
} else {
this.bindLog = null;
}
}
// protected void setCheckDelta(boolean checkDelta) {
// this.checkDelta = checkDelta;
// }
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().log("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.log(Level.SEVERE, 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 bind information to the transaction log.
*/
protected void logBinding() {
if (logLevelSql) {
transaction.logInternal(bindLog.toString());
}
}
/**
* Log the sql to the transaction log.
*/
protected void logSql(String sql) {
if (logLevelSql) {
transaction.logInternal(sql);
}
}
public boolean isIncluded(BeanProperty prop) {
return (loadedProps == null || loadedProps.contains(prop.getName()));
}
public boolean isIncludedWhere(BeanProperty prop) {
if (prop.isDbEncrypted()){
// update without a version property ...
// for encrypted properties only include if it was
// also an updated/modified property
return isIncluded(prop);
}
return prop.isDbUpdatable() && (loadedProps == null || loadedProps.contains(prop.getName()));
}
/**
* Bind a raw value. Used to bind the discriminator column.
*/
public Object bind(String propName, Object value, int sqlType) throws SQLException {
if (logLevelSql) {
bindLog.append(propName).append("=");
bindLog.append(value).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, String propName, boolean bindNull) throws SQLException {
return bindInternal(logLevelSql, value, prop, propName, bindNull);
}
/**
* Bind the value to the preparedStatement without logging.
*/
public Object bindNoLog(Object value, BeanProperty prop, String propName, boolean bindNull) throws SQLException {
return bindInternal(false, value, prop, propName, bindNull);
}
private Object bindInternal(boolean log, Object value, BeanProperty prop, String propName, boolean bindNull) throws SQLException {
if (!bindNull){
if (emptyStringToNull && (value instanceof String) && ((String)value).length() == 0){
// support Oracle conversion of empty string to null
//value = prop.getDbNullValue(value);
value = null;
}
}
if (!bindNull && value == null) {
// where will have IS NULL clause so don't actually bind
if (log) {
bindLog.append(propName).append("=");
bindLog.append("null, ");
}
} else {
if (log) {
bindLog.append(propName).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);
}
bindLog.append(", ");
}
// do the actual binding to PreparedStatement
prop.bind(dataBind, value);
// if (checkDelta) {
// if (!prop.isId() && prop.isDeltaRequired()){
// if (deltaBean == null){
// deltaBean = persistRequest.createDeltaBean();
// transaction.getEvent().addBeanDelta(deltaBean);
// }
// deltaBean.add(prop, value);
// }
// }
}
return value;
}
/**
* Add the comment to the bind information log.
*/
protected void bindLogAppend(String comment) {
if (logLevelSql) {
bindLog.append(comment);
}
}
/**
* For generated properties set on insert register as additional
* loaded properties if required.
*/
public final void registerAdditionalProperty(String propertyName) {
if (loadedProps != null && !loadedProps.contains(propertyName)){
if (additionalProps == null){
additionalProps = new HashSet<String>();
}
additionalProps.add(propertyName);
}
}
/**
* Set any additional (generated) properties to the set of loaded properties
* if required.
*/
protected void setAdditionalProperties() {
if (additionalProps != null){
// additional generated properties set on insert
// added to the set of loaded properties
additionalProps.addAll(loadedProps);
persistRequest.setLoadedProps(additionalProps);
}
}
/**
* 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, Object bean, Object value) {
if (updateGenValues == null) {
updateGenValues = new ArrayList<UpdateGenValue>();
}
updateGenValues.add(new UpdateGenValue(prop, bean, value));
registerAdditionalProperty(prop.getName());
}
/**
* 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;
}
if (logLevelSql){
t.logInternal(sql);
}
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 Object bean;
private final Object value;
private UpdateGenValue(BeanProperty property, Object 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,258 +1,239 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
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.sql.Statement;
import java.util.HashSet;
import java.util.List;
import java.util.logging.Level;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
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 {
/**
* 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();
}
@Override
public boolean isIncluded(BeanProperty prop) {
return prop.isDbInsertable() && (super.isIncluded(prop));
}
/**
* Generate and bind the insert statement.
*/
public void bind() throws SQLException {
BeanDescriptor<?> desc = persistRequest.getBeanDescriptor();
Object bean = persistRequest.getBean();
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();
boolean isBatch = t.isBatchThisRequest();
// get the appropriate sql
sql = meta.getSql(withId);
PreparedStatement pstmt;
if (isBatch) {
pstmt = getPstmt(t, sql, persistRequest, useGeneratedKeys);
} else {
logSql(sql);
pstmt = getPstmt(t, sql, useGeneratedKeys);
}
dataBind = new DataBind(pstmt);
bindLogAppend("Binding Insert [");
bindLogAppend(desc.getBaseTable());
bindLogAppend("] set[");
// bind the bean property values
meta.bind(this, bean, withId);
bindLogAppend("]");
logBinding();
}
/**
* 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, Statement.RETURN_GENERATED_KEYS);
} 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);
setAdditionalProperties();
executeDerivedRelationships();
}
protected void executeDerivedRelationships() {
List<DerivedRelationshipData> derivedRelationships = persistRequest.getDerivedRelationships();
if (derivedRelationships != null) {
for (int i = 0; i < derivedRelationships.size(); i++) {
DerivedRelationshipData derivedRelationshipData = derivedRelationships.get(i);
EbeanServer ebeanServer = persistRequest.getEbeanServer();
HashSet<String> updateProps = new HashSet<String>();
updateProps.add(derivedRelationshipData.getLogicalName());
ebeanServer.update(derivedRelationshipData.getBean(), updateProps, transaction, false, true);
}
}
}
/**
* 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.log(Level.WARNING, 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.log(Level.WARNING, msg, ex);
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException ex) {
String msg = "Error closing stmt for fetchGeneratedKeyUsingSelect?";
logger.log(Level.WARNING, 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.sql.Statement;
import java.util.HashSet;
import java.util.List;
import java.util.logging.Level;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
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 {
/**
* 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();
}
@Override
public boolean isIncluded(BeanProperty prop) {
return prop.isDbInsertable() && (super.isIncluded(prop));
}
/**
* Generate and bind the insert statement.
*/
public void bind() throws SQLException {
BeanDescriptor<?> desc = persistRequest.getBeanDescriptor();
Object bean = persistRequest.getBean();
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();
boolean isBatch = t.isBatchThisRequest();
// get the appropriate sql
sql = meta.getSql(withId);
PreparedStatement pstmt;
if (isBatch) {
pstmt = getPstmt(t, sql, persistRequest, useGeneratedKeys);
} else {
logSql(sql);
pstmt = getPstmt(t, sql, useGeneratedKeys);
}
dataBind = new DataBind(pstmt);
bindLogAppend("Binding Insert [");
bindLogAppend(desc.getBaseTable());
bindLogAppend("] set[");
// bind the bean property values
meta.bind(this, bean, withId);
bindLogAppend("]");
logBinding();
}
/**
* 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, Statement.RETURN_GENERATED_KEYS);
} 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);
setAdditionalProperties();
executeDerivedRelationships();
}
protected void executeDerivedRelationships() {
List<DerivedRelationshipData> derivedRelationships = persistRequest.getDerivedRelationships();
if (derivedRelationships != null) {
for (int i = 0; i < derivedRelationships.size(); i++) {
DerivedRelationshipData derivedRelationshipData = derivedRelationships.get(i);
EbeanServer ebeanServer = persistRequest.getEbeanServer();
HashSet<String> updateProps = new HashSet<String>();
updateProps.add(derivedRelationshipData.getLogicalName());
ebeanServer.update(derivedRelationshipData.getBean(), updateProps, transaction, false, true);
}
}
}
/**
* 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.log(Level.WARNING, 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.log(Level.WARNING, msg, ex);
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException ex) {
String msg = "Error closing stmt for fetchGeneratedKeyUsingSelect?";
logger.log(Level.WARNING, msg, ex);
}
}
}
public void registerDerivedRelationship(DerivedRelationshipData derivedRelationship) {
persistRequest.getTransaction().registerDerivedRelationship(derivedRelationship);
}
}
@@ -1,208 +1,189 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.Set;
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, null);
// 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;
this.identityDbColumns = new String[]{id.getIdentityColumn()};
this.sqlNullId = genSql(true, null);
this.supportsGetGeneratedKeys = dbPlatform.getDbIdentity().isSupportsGetGeneratedKeys();
this.selectLastInsertedId = desc.getSelectLastInsertedId();
}
}
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, Object bean, boolean withId) throws SQLException {
if (withId) {
id.dmlBind(request, false, bean);
}
if (shadowFKey != null){
shadowFKey.dmlBind(request, false, bean);
}
if (discriminator != null){
discriminator.dmlBind(request, false, bean);
}
all.dmlBind(request, false, 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, Set<String> loadedProps) {
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringToNull, loadedProps, null);
request.setInsertSetMode();
request.append("insert into ").append(tableName);
request.append(" (");
if (!nullId) {
id.dmlInsert(request, false);
}
if (shadowFKey != null){
shadowFKey.dmlInsert(request, false);
}
if (discriminator != null){
discriminator.dmlInsert(request, false);
}
all.dmlInsert(request, false);
request.append(") values (");
request.append(request.getInsertBindBuffer());
request.append(")");
return request.toString();
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.Set;
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, null);
// 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;
this.identityDbColumns = new String[]{id.getIdentityColumn()};
this.sqlNullId = genSql(true, null);
this.supportsGetGeneratedKeys = dbPlatform.getDbIdentity().isSupportsGetGeneratedKeys();
this.selectLastInsertedId = desc.getSelectLastInsertedId();
}
}
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, Object bean, boolean withId) throws SQLException {
if (withId) {
id.dmlBind(request, false, bean);
}
if (shadowFKey != null){
shadowFKey.dmlBind(request, false, bean);
}
if (discriminator != null){
discriminator.dmlBind(request, false, bean);
}
all.dmlBind(request, false, 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, Set<String> loadedProps) {
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringToNull, loadedProps, null);
request.setInsertSetMode();
request.append("insert into ").append(tableName);
request.append(" (");
if (!nullId) {
id.dmlInsert(request, false);
}
if (shadowFKey != null){
shadowFKey.dmlInsert(request, false);
}
if (discriminator != null){
discriminator.dmlInsert(request, false);
}
all.dmlInsert(request, false);
request.append(") values (");
request.append(request.getInsertBindBuffer());
request.append(")");
return request.toString();
}
}
@@ -1,146 +1,127 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
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);
List<Bindable> allList = new ArrayList<Bindable>();
baseFact.create(allList, desc, DmlMode.WHERE, false);
embeddedFact.create(allList, desc, DmlMode.WHERE, false);
assocOneFact.create(allList, desc, DmlMode.WHERE);
Bindable setBindable = new BindableList(setList);
Bindable allBindable = new BindableList(allList);
return new UpdateMeta(emptyStringAsNull, desc, setBindable, id, ver, allBindable);
}
/**
* Create the DeleteMeta for the given bean type.
*/
public DeleteMeta createDelete(BeanDescriptor<?> desc) {
BindableId id = idFact.createId(desc);
Bindable ver = versionFact.create(desc);
List<Bindable> allList = new ArrayList<Bindable>();
baseFact.create(allList, desc, DmlMode.WHERE, false);
embeddedFact.create(allList, desc, DmlMode.WHERE, false);
assocOneFact.create(allList, desc, DmlMode.WHERE);
Bindable allBindable = new BindableList(allList);
return new DeleteMeta(emptyStringAsNull, desc, id, ver, allBindable);
}
/**
* 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);
List<Bindable> allList = new ArrayList<Bindable>();
baseFact.create(allList, desc, DmlMode.WHERE, false);
embeddedFact.create(allList, desc, DmlMode.WHERE, false);
assocOneFact.create(allList, desc, DmlMode.WHERE);
Bindable setBindable = new BindableList(setList);
Bindable allBindable = new BindableList(allList);
return new UpdateMeta(emptyStringAsNull, desc, setBindable, id, ver, allBindable);
}
/**
* Create the DeleteMeta for the given bean type.
*/
public DeleteMeta createDelete(BeanDescriptor<?> desc) {
BindableId id = idFact.createId(desc);
Bindable ver = versionFact.create(desc);
List<Bindable> allList = new ArrayList<Bindable>();
baseFact.create(allList, desc, DmlMode.WHERE, false);
embeddedFact.create(allList, desc, DmlMode.WHERE, false);
assocOneFact.create(allList, desc, DmlMode.WHERE);
Bindable allBindable = new BindableList(allList);
return new DeleteMeta(emptyStringAsNull, desc, id, ver, allBindable);
}
/**
* 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,53 +1,34 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
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,122 +1,103 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Set;
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.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* Update bean handler.
*/
public class UpdateHandler extends DmlHandler {
private final UpdateMeta meta;
private Set<String> updatedProperties;
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;
}
updatedProperties = updatePlan.getProperties();
sql = updatePlan.getSql();
SpiTransaction t = persistRequest.getTransaction();
boolean isBatch = t.isBatchThisRequest();
PreparedStatement pstmt;
if (isBatch) {
pstmt = getPstmt(t, sql, persistRequest, false);
} else {
logSql(sql);
pstmt = getPstmt(t, sql, false);
}
dataBind = new DataBind(pstmt);
bindLogAppend("Binding Update [");
bindLogAppend(meta.getTableName());
bindLogAppend("] ");
meta.bind(persistRequest, this, updatePlan);
setUpdateGenValues();
bindLogAppend("]");
logBinding();
}
@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);
setAdditionalProperties();
}
}
@Override
public boolean isIncluded(BeanProperty prop) {
return prop.isDbUpdatable() && (updatedProperties == null || updatedProperties.contains(prop.getName()));
}
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 java.util.Set;
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.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* Update bean handler.
*/
public class UpdateHandler extends DmlHandler {
private final UpdateMeta meta;
private Set<String> updatedProperties;
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;
}
updatedProperties = updatePlan.getProperties();
sql = updatePlan.getSql();
SpiTransaction t = persistRequest.getTransaction();
boolean isBatch = t.isBatchThisRequest();
PreparedStatement pstmt;
if (isBatch) {
pstmt = getPstmt(t, sql, persistRequest, false);
} else {
logSql(sql);
pstmt = getPstmt(t, sql, false);
}
dataBind = new DataBind(pstmt);
bindLogAppend("Binding Update [");
bindLogAppend(meta.getTableName());
bindLogAppend("] ");
meta.bind(persistRequest, this, updatePlan);
setUpdateGenValues();
bindLogAppend("]");
logBinding();
}
@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);
setAdditionalProperties();
}
}
@Override
public boolean isIncluded(BeanProperty prop) {
return prop.isDbUpdatable() && (updatedProperties == null || updatedProperties.contains(prop.getName()));
}
public void registerDerivedRelationship(DerivedRelationshipData derivedRelationship) {
persistRequest.getTransaction().registerDerivedRelationship(derivedRelationship);
}
}
@@ -1,259 +1,240 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.core.ConcurrencyMode;
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;
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 Bindable set;
private final BindableId id;
private final Bindable version;
private final Bindable all;
private final String tableName;
private final UpdatePlan modeNoneUpdatePlan;
private final UpdatePlan modeVersionUpdatePlan;
private final boolean emptyStringAsNull;
public UpdateMeta(boolean emptyStringAsNull, BeanDescriptor<?> desc, Bindable set, BindableId id, Bindable version, Bindable all) {
this.emptyStringAsNull = emptyStringAsNull;
this.tableName = desc.getBaseTable();
this.set = set;
this.id = id;
this.version = version;
this.all = all;
this.sqlNone = genSql(ConcurrencyMode.NONE, null, null);
this.sqlVersion = genSql(ConcurrencyMode.VERSION, null, null);
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 {
Object bean = persist.getBean();
bind.bindLogAppend(" set[");
// bind.setCheckDelta(true);
updatePlan.bindSet(bind, bean);
// bind.setCheckDelta(false);
bind.bindLogAppend("] where[");
id.dmlBind(bind, false, bean);
switch (persist.getConcurrencyMode()) {
case VERSION:
version.dmlBind(bind, false, bean);
break;
case ALL:
Object oldBean = persist.getOldValues();
all.dmlBindWhere(bind, true, oldBean);
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;
case ALL:
Object oldValues = request.getOldValues();
if (oldValues == null) {
throw new PersistenceException("OldValues are null?");
}
String sql = genDynamicWhere(request.getUpdatedProperties(), request.getLoadedProperties(), oldValues);
return new UpdatePlan(ConcurrencyMode.ALL, sql, set);
default:
throw new RuntimeException("Invalid mode " + mode);
}
}
private SpiUpdatePlan getDynamicUpdatePlan(ConcurrencyMode mode, PersistRequestBean<?> persistRequest) {
Set<String> updatedProps = persistRequest.getUpdatedProperties();
if (ConcurrencyMode.ALL.equals(mode)) {
// due to is null in where clause we won't bother trying to
// cache plans for ConcurrencyMode.ALL
String sql = genSql(mode, persistRequest, null);
if (sql == null) {
// changed properties must have been updatable=false
return UpdatePlan.EMPTY_SET_CLAUSE;
} else {
return new UpdatePlan(null, mode, sql, set, updatedProps);
}
}
// we can use a cached UpdatePlan for the changed properties
int hash = mode.hashCode();
hash = hash * 31 + (updatedProps == null ? 0 : updatedProps.hashCode());
Integer key = Integer.valueOf(hash);
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<Bindable>();
set.addChanged(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, null);
// 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();
if (bindableList != null) {
bindableList.dmlAppend(request, false);
} else {
set.dmlAppend(request, true);
}
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, false);
if (ConcurrencyMode.VERSION.equals(conMode)) {
if (version == null) {
return null;
}
version.dmlAppend(request, false);
} else if (ConcurrencyMode.ALL.equals(conMode)) {
all.dmlWhere(request, true, request.getOldValues());
}
return request.toString();
}
/**
* Generate the sql dynamically for where using IS NULL for binding null
* values.
*/
private String genDynamicWhere(Set<String> loadedProps, Set<String> whereProps, Object oldBean) {
// always has a preceding id property(s) so the first
// option is always ' and ' and not blank.
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringAsNull, loadedProps, whereProps, oldBean);
request.append(sqlNone);
request.setWhereMode();
all.dmlWhere(request, true, oldBean);
return request.toString();
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.core.ConcurrencyMode;
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;
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 Bindable set;
private final BindableId id;
private final Bindable version;
private final Bindable all;
private final String tableName;
private final UpdatePlan modeNoneUpdatePlan;
private final UpdatePlan modeVersionUpdatePlan;
private final boolean emptyStringAsNull;
public UpdateMeta(boolean emptyStringAsNull, BeanDescriptor<?> desc, Bindable set, BindableId id, Bindable version, Bindable all) {
this.emptyStringAsNull = emptyStringAsNull;
this.tableName = desc.getBaseTable();
this.set = set;
this.id = id;
this.version = version;
this.all = all;
this.sqlNone = genSql(ConcurrencyMode.NONE, null, null);
this.sqlVersion = genSql(ConcurrencyMode.VERSION, null, null);
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 {
Object bean = persist.getBean();
bind.bindLogAppend(" set[");
// bind.setCheckDelta(true);
updatePlan.bindSet(bind, bean);
// bind.setCheckDelta(false);
bind.bindLogAppend("] where[");
id.dmlBind(bind, false, bean);
switch (persist.getConcurrencyMode()) {
case VERSION:
version.dmlBind(bind, false, bean);
break;
case ALL:
Object oldBean = persist.getOldValues();
all.dmlBindWhere(bind, true, oldBean);
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;
case ALL:
Object oldValues = request.getOldValues();
if (oldValues == null) {
throw new PersistenceException("OldValues are null?");
}
String sql = genDynamicWhere(request.getUpdatedProperties(), request.getLoadedProperties(), oldValues);
return new UpdatePlan(ConcurrencyMode.ALL, sql, set);
default:
throw new RuntimeException("Invalid mode " + mode);
}
}
private SpiUpdatePlan getDynamicUpdatePlan(ConcurrencyMode mode, PersistRequestBean<?> persistRequest) {
Set<String> updatedProps = persistRequest.getUpdatedProperties();
if (ConcurrencyMode.ALL.equals(mode)) {
// due to is null in where clause we won't bother trying to
// cache plans for ConcurrencyMode.ALL
String sql = genSql(mode, persistRequest, null);
if (sql == null) {
// changed properties must have been updatable=false
return UpdatePlan.EMPTY_SET_CLAUSE;
} else {
return new UpdatePlan(null, mode, sql, set, updatedProps);
}
}
// we can use a cached UpdatePlan for the changed properties
int hash = mode.hashCode();
hash = hash * 31 + (updatedProps == null ? 0 : updatedProps.hashCode());
Integer key = Integer.valueOf(hash);
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<Bindable>();
set.addChanged(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, null);
// 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();
if (bindableList != null) {
bindableList.dmlAppend(request, false);
} else {
set.dmlAppend(request, true);
}
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, false);
if (ConcurrencyMode.VERSION.equals(conMode)) {
if (version == null) {
return null;
}
version.dmlAppend(request, false);
} else if (ConcurrencyMode.ALL.equals(conMode)) {
all.dmlWhere(request, true, request.getOldValues());
}
return request.toString();
}
/**
* Generate the sql dynamically for where using IS NULL for binding null
* values.
*/
private String genDynamicWhere(Set<String> loadedProps, Set<String> whereProps, Object oldBean) {
// always has a preceding id property(s) so the first
// option is always ' and ' and not blank.
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringAsNull, loadedProps, whereProps, oldBean);
request.append(sqlNone);
request.setWhereMode();
all.dmlWhere(request, true, oldBean);
return request.toString();
}
}
@@ -1,172 +1,153 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.Set;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.core.ConcurrencyMode;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
/**
* Cachable plan for executing bean updates for a given set of changed
* properties.
*
* @author rbygrave
*/
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 Set<String> properties;
private final boolean checkIncludes;
private final long timeCreated;
private final boolean emptySetClause;
private Long timeLastUsed;
/**
* Create a non cachable UpdatePlan.
*/
public UpdatePlan(ConcurrencyMode mode, String sql, Bindable set) {
this(null, mode, sql, set, null);
}
/**
* Create a cachable UpdatePlan with a given key.
*/
public UpdatePlan(Integer key, ConcurrencyMode mode, String sql,
Bindable set, Set<String> properties) {
this.emptySetClause = false;
this.key = key;
this.mode = mode;
this.sql = sql;
this.set = set;
this.properties = properties;
this.checkIncludes = properties != null;
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.properties = null;
this.checkIncludes = false;
this.timeCreated = 0;
}
public boolean isEmptySetClause() {
return emptySetClause;
}
/**
* Run the prepared statement binding for the 'update set' properties.
*/
public void bindSet(DmlHandler bind, Object bean) throws SQLException {
set.dmlBind(bind, checkIncludes, 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;
}
/**
* Return the set of changed properties.
* <p>
* This can return null when all properties in the set are being bound in
* the update statement.
* </p>
*/
public Set<String> getProperties() {
return properties;
}
}
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.Set;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.core.ConcurrencyMode;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
/**
* Cachable plan for executing bean updates for a given set of changed
* properties.
*
* @author rbygrave
*/
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 Set<String> properties;
private final boolean checkIncludes;
private final long timeCreated;
private final boolean emptySetClause;
private Long timeLastUsed;
/**
* Create a non cachable UpdatePlan.
*/
public UpdatePlan(ConcurrencyMode mode, String sql, Bindable set) {
this(null, mode, sql, set, null);
}
/**
* Create a cachable UpdatePlan with a given key.
*/
public UpdatePlan(Integer key, ConcurrencyMode mode, String sql,
Bindable set, Set<String> properties) {
this.emptySetClause = false;
this.key = key;
this.mode = mode;
this.sql = sql;
this.set = set;
this.properties = properties;
this.checkIncludes = properties != null;
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.properties = null;
this.checkIncludes = false;
this.timeCreated = 0;
}
public boolean isEmptySetClause() {
return emptySetClause;
}
/**
* Run the prepared statement binding for the 'update set' properties.
*/
public void bindSet(DmlHandler bind, Object bean) throws SQLException {
set.dmlBind(bind, checkIncludes, 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;
}
/**
* Return the set of changed properties.
* <p>
* This can return null when all properties in the set are being bound in
* the update statement.
* </p>
*/
public Set<String> getProperties() {
return properties;
}
}