Search in sources :

Example 11 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class SqlBoxContextUtils method delete.

/**
 * Delete entityBean in database according primary key value
 */
public static void delete(SqlBoxContext ctx, Object entityBean) {
    SqlBox box = SqlBoxUtils.findAndBindSqlBox(ctx, entityBean);
    checkBeanAndBoxExist(entityBean, box);
    TableModel tableModel = box.getTableModel();
    List<Object> pkeyParameters = new ArrayList<Object>();
    StringBuilder sb = new StringBuilder();
    sb.append("delete from ").append(tableModel.getTableName()).append(" where ");
    Map<String, Method> readMethods = ClassCacheUtils.getClassReadMethods(entityBean.getClass());
    for (String fieldName : readMethods.keySet()) {
        ColumnModel col = findMatchColumnForJavaField(fieldName, box);
        if (!col.getTransientable() && col.getPkey()) {
            Object value = ClassCacheUtils.readValueFromBeanField(entityBean, fieldName);
            sb.append(col.getColumnName()).append("=?, ");
            pkeyParameters.add(value);
        }
    }
    // delete the last "," character
    sb.setLength(sb.length() - 2);
    if (pkeyParameters.isEmpty())
        throw new SqlBoxException("No primary key set for entityBean");
    int rowAffected = box.context.nExecute(sb.toString(), pkeyParameters.toArray(new Object[pkeyParameters.size()]));
    if (ctx.isBatchEnabled())
        return;
    if (rowAffected <= 0)
        throw new SqlBoxException("No row be deleted for entityBean");
    if (rowAffected > 1)
        throw new SqlBoxException("Multiple rows affected when delete entityBean");
}
Also used : ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Example 12 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class SqlBoxContextUtils method update.

/**
 * Update entityBean according primary key
 */
public static int update(SqlBoxContext ctx, Object entityBean) {
    SqlBox box = SqlBoxUtils.findAndBindSqlBox(ctx, entityBean);
    checkBeanAndBoxExist(entityBean, box);
    TableModel tableModel = box.getTableModel();
    StringBuilder sb = new StringBuilder();
    sb.append("update ").append(tableModel.getTableName()).append(" set ");
    List<Object> normalParams = new ArrayList<Object>();
    List<Object> pkeyParams = new ArrayList<Object>();
    List<ColumnModel> pkeyColumns = new ArrayList<ColumnModel>();
    Map<String, Method> readMethods = ClassCacheUtils.getClassReadMethods(entityBean.getClass());
    for (String fieldName : readMethods.keySet()) {
        ColumnModel col = findMatchColumnForJavaField(fieldName, box);
        if (!col.getTransientable() && col.getUpdatable()) {
            Object value = ClassCacheUtils.readValueFromBeanField(entityBean, fieldName);
            if (!col.getPkey()) {
                normalParams.add(value);
                sb.append(col.getColumnName()).append("=?, ");
            } else {
                pkeyParams.add(value);
                pkeyColumns.add(col);
            }
        }
    }
    if (!normalParams.isEmpty())
        // delete the last ", " characters
        sb.setLength(sb.length() - 2);
    if (pkeyColumns.isEmpty())
        throw new SqlBoxException("No primary column setting found for entityBean");
    sb.append(" where ");
    for (ColumnModel col : pkeyColumns) sb.append(col.getColumnName()).append("=? and ");
    // delete the last " and " characters
    sb.setLength(sb.length() - 5);
    for (Object pkeyParam : pkeyParams) // join PKey values
    normalParams.add(pkeyParam);
    return box.context.nUpdate(sb.toString(), normalParams.toArray(new Object[normalParams.size()]));
}
Also used : ArrayList(java.util.ArrayList) ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) Method(java.lang.reflect.Method) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Example 13 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class SqlBoxContextUtils method findMatchColumnForJavaField.

private static ColumnModel findMatchColumnForJavaField(String entityField, TableModel tableModel) {
    if (tableModel == null)
        return null;
    List<ColumnModel> columns = tableModel.getColumns();
    ColumnModel result = null;
    String underLineFieldName = SqlBoxStrUtils.camelToLowerCaseUnderline(entityField);
    for (ColumnModel col : columns) {
        if (entityField.equalsIgnoreCase(col.getEntityField()) || underLineFieldName.equalsIgnoreCase(col.getColumnName())) {
            if (result != null)
                throw new SqlBoxException("Field '" + entityField + "' found duplicated columns definition");
            result = col;
        }
    }
    return result;
}
Also used : ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel)

Example 14 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class SqlBoxContextUtils method load.

@SuppressWarnings("unchecked")
public static <T> T load(SqlBoxContext ctx, Class<?> entityClass, Object pkeyValue) {
    SqlBoxException.assureNotNull(entityClass, "entityClass can not be null");
    SqlBoxException.assureNotNull(entityClass, "pkey can not be null");
    Map<String, Object> pkValueMap = null;
    if (pkeyValue instanceof Map)
        // NOSONAR
        pkValueMap = (Map<String, Object>) pkeyValue;
    else {
        pkValueMap = new HashMap<String, Object>();
        pkValueMap.put("ooxxooxx", pkeyValue);
    }
    Object entity = null;
    try {
        entity = entityClass.newInstance();
    } catch (Exception e) {
        throw new SqlBoxException(e);
    }
    SqlBox box = SqlBoxUtils.findAndBindSqlBox(ctx, entity);
    TableModel model = box.getTableModel();
    StringBuilder sb = new StringBuilder("select ");
    List<Object> pkParams = new ArrayList<Object>();
    List<ColumnModel> pkeyColumns = new ArrayList<ColumnModel>();
    List<ColumnModel> allColumns = new ArrayList<ColumnModel>();
    List<String> allFieldNames = new ArrayList<String>();
    Map<String, Method> writeMethods = ClassCacheUtils.getClassWriteMethods(entityClass);
    for (String fieldName : writeMethods.keySet()) {
        ColumnModel col = findMatchColumnForJavaField(fieldName, box);
        if (!col.getTransientable()) {
            allColumns.add(col);
            allFieldNames.add(fieldName);
            sb.append(col.getColumnName()).append(", ");
            if (col.getPkey()) {
                pkeyColumns.add(col);
                if (pkValueMap.size() == 1)
                    pkParams.add(pkValueMap.entrySet().iterator().next().getValue());
                else
                    pkParams.add(pkValueMap.get(fieldName));
            }
        }
    }
    if (pkeyColumns.isEmpty())
        throw new SqlBoxException("No primary key set for entityBean");
    // delete the last ", "
    sb.setLength(sb.length() - 2);
    if (pkParams.size() != pkValueMap.size())
        throw new SqlBoxException("Wrong number of primary key parameters: expected " + pkParams.size() + ", was given " + pkValueMap.size());
    sb.append(" from ").append(model.getTableName()).append(" where ");
    for (ColumnModel col : pkeyColumns) sb.append(col.getColumnName()).append("=? and ");
    // delete the last " and "
    sb.setLength(sb.length() - 5);
    try {
        Object[] values = ctx.nQuery(new ArrayHandler(), sb.toString(), pkParams.toArray(new Object[pkParams.size()]));
        for (int i = 0; i < values.length; i++) {
            Method writeMethod = writeMethods.get(allFieldNames.get(i));
            writeMethod.invoke(entity, values[i]);
        }
    } catch (Exception e) {
        throw new SqlBoxException(e);
    }
    return (T) entity;
}
Also used : ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) SQLException(java.sql.SQLException) ArrayHandler(org.apache.commons.dbutils.handlers.ArrayHandler) ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) HashMap(java.util.HashMap) Map(java.util.Map) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Example 15 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class SqlBoxContextUtils method insert.

/**
 * Insert entityBean into database, and change ID fields to values generated by
 * IdGenerator (identity or sequence or UUID...)
 */
public static void insert(SqlBoxContext ctx, Object entityBean) {
    SqlBox box = SqlBoxUtils.findAndBindSqlBox(ctx, entityBean);
    checkBeanAndBoxExist(entityBean, box);
    TableModel tableModel = box.getTableModel();
    StringBuilder sb = new StringBuilder();
    sb.append("insert into ").append(tableModel.getTableName()).append(" (");
    List<Object> params = new ArrayList<Object>();
    String identityFieldName = null;
    Type identityType = null;
    Map<String, Method> readMethods = ClassCacheUtils.getClassReadMethods(entityBean.getClass());
    for (String fieldName : readMethods.keySet()) {
        ColumnModel col = findMatchColumnForJavaField(fieldName, box);
        if (!col.getTransientable() && col.getInsertable()) {
            if (col.getIdGenerationType() != null || !StrUtils.isEmpty(col.getIdGeneratorName())) {
                IdGenerator idGen = col.getIdGenerator();
                if (GenerationType.IDENTITY.equals(idGen.getGenerationType())) {
                    if (identityFieldName != null)
                        throw new SqlBoxException("More than 1 identity field found for model '" + tableModel.getTableName() + "'");
                    identityFieldName = fieldName;
                } else {
                    sb.append(col.getColumnName()).append(", ");
                    Object id = idGen.getNextID(ctx, ctx.getDialect(), col.getColumnType());
                    params.add(id);
                    ClassCacheUtils.writeValueToBeanField(entityBean, fieldName, id);
                }
            } else {
                Object value = ClassCacheUtils.readValueFromBeanField(entityBean, fieldName);
                sb.append(col.getColumnName()).append(", ");
                params.add(value);
            }
        }
    }
    if (!params.isEmpty())
        // delete the last ", " character
        sb.setLength(sb.length() - 2);
    sb.append(") values(").append(SqlBoxStrUtils.getQuestionsStr(params.size())).append(")");
    int result = ctx.nExecute(sb.toString(), params.toArray(new Object[params.size()]));
    if (ctx.isBatchEnabled())
        return;
    if (result != 1)
        throw new SqlBoxException(result + " row record be inserted.");
    if (identityFieldName != null) {
        // write identity id to Bean field
        Object identityId = IdentityIdGenerator.INSTANCE.getNextID(ctx, ctx.getDialect(), identityType);
        ClassCacheUtils.writeValueToBeanField(entityBean, identityFieldName, identityId);
    }
}
Also used : ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) IdentityIdGenerator(com.github.drinkjava2.jdialects.id.IdentityIdGenerator) IdGenerator(com.github.drinkjava2.jdialects.id.IdGenerator) Type(com.github.drinkjava2.jdialects.Type) GenerationType(com.github.drinkjava2.jdialects.annotation.jpa.GenerationType) ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Aggregations

Method (java.lang.reflect.Method)9 TableModel (com.github.drinkjava2.jdialects.model.TableModel)8 ColumnModel (com.github.drinkjava2.jdialects.model.ColumnModel)6 SqlBoxException (com.github.drinkjava2.jsqlbox.SqlBoxException)6 PreparedSQL (com.github.drinkjava2.jdbpro.inline.PreparedSQL)5 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)3 IOException (java.io.IOException)2 Type (com.github.drinkjava2.jdialects.Type)1 GenerationType (com.github.drinkjava2.jdialects.annotation.jpa.GenerationType)1 IdGenerator (com.github.drinkjava2.jdialects.id.IdGenerator)1 IdentityIdGenerator (com.github.drinkjava2.jdialects.id.IdentityIdGenerator)1 FKeyModel (com.github.drinkjava2.jdialects.model.FKeyModel)1 Sql (com.github.drinkjava2.jsqlbox.annotation.Sql)1 EntityListHandler (com.github.drinkjava2.jsqlbox.handler.EntityListHandler)1 File (java.io.File)1 FileReader (java.io.FileReader)1 Annotation (java.lang.annotation.Annotation)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 SQLException (java.sql.SQLException)1