Search in sources :

Example 6 with Id

use of siena.Id in project siena by mandubian.

the class H2PersistenceManager method insertBatchWithAutoIncrementKey.

/*
	 * Overrides the batch insert since H2 getGeneratedKeys doesn't return all generated identities but only the last one.
	 * This is a known limitation: http://markmail.org/message/hsgzgktbj4srz657
	 * It is planned in H2 v1.4 roadmap: http://www.h2database.com/html/roadmap.html
	 * Meanwhile, no batch insert is possible
	 *  
	 * (non-Javadoc)
	 * @see siena.jdbc.JdbcPersistenceManager#insertBatchWithAutoIncrementKey(siena.jdbc.JdbcPersistenceManager.JdbcClassInfo, java.util.Map)
	 */
@Override
protected int insertBatchWithAutoIncrementKey(JdbcClassInfo classInfo, Map<JdbcClassInfo, List<Object>> objMap) throws SQLException, IllegalAccessException {
    PreparedStatement ps = null;
    ps = getConnection().prepareStatement(classInfo.insertSQL, Statement.RETURN_GENERATED_KEYS);
    int res = 0;
    for (Object obj : objMap.get(classInfo)) {
        for (Field field : classInfo.keys) {
            Id id = field.getAnnotation(Id.class);
            if (id.value() == Generator.UUID) {
                field.set(obj, UUID.randomUUID().toString());
            }
        }
        // TODO: implement primary key generation: SEQUENCE
        addParameters(obj, classInfo.insertFields, ps, 1);
        ps.executeUpdate();
        if (!classInfo.generatedKeys.isEmpty()) {
            ResultSet gk = ps.getGeneratedKeys();
            int i;
            while (gk.next()) {
                i = 1;
                for (Field field : classInfo.generatedKeys) {
                    field.setAccessible(true);
                    JdbcMappingUtils.setFromObject(obj, field, gk.getObject(i++));
                }
            }
        }
        res++;
    }
    return res;
}
Also used : Field(java.lang.reflect.Field) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Id(siena.Id)

Example 7 with Id

use of siena.Id in project siena by mandubian.

the class JdbcPersistenceManager method insertBatchWithAutoIncrementKey.

/**
 * required to be overriden for Postgres
 *
 * @param classInfo
 * @param objMap
 * @throws SQLException
 * @throws IllegalAccessException
 */
protected int insertBatchWithAutoIncrementKey(JdbcClassInfo classInfo, Map<JdbcClassInfo, List<Object>> objMap) throws SQLException, IllegalAccessException {
    PreparedStatement ps = null;
    ps = getConnection().prepareStatement(classInfo.insertSQL, Statement.RETURN_GENERATED_KEYS);
    for (Object obj : objMap.get(classInfo)) {
        for (Field field : classInfo.keys) {
            Id id = field.getAnnotation(Id.class);
            if (id.value() == Generator.UUID) {
                field.set(obj, UUID.randomUUID().toString());
            }
        }
        // TODO: implement primary key generation: SEQUENCE
        addParameters(obj, classInfo.insertFields, ps, 1);
        ps.addBatch();
    }
    // TODO what to do with results of executeBatch ??????
    int[] res = ps.executeBatch();
    if (!classInfo.generatedKeys.isEmpty()) {
        ResultSet gk = ps.getGeneratedKeys();
        int i;
        int idx = 0;
        while (gk.next()) {
            i = 1;
            for (Field field : classInfo.generatedKeys) {
                field.setAccessible(true);
                JdbcMappingUtils.setFromObject(objMap.get(classInfo).get(idx++), field, gk.getObject(i++));
            }
        }
    }
    return res.length;
}
Also used : Field(java.lang.reflect.Field) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Id(siena.Id)

Example 8 with Id

use of siena.Id in project siena by mandubian.

the class JdbcPersistenceManager method insert.

public void insert(Object obj) {
    JdbcClassInfo classInfo = JdbcClassInfo.getClassInfo(obj.getClass());
    PreparedStatement ps = null;
    try {
        for (Field field : classInfo.keys) {
            Id id = field.getAnnotation(Id.class);
            if (id.value() == Generator.UUID) {
                field.set(obj, UUID.randomUUID().toString());
            }
        }
        if (!classInfo.generatedKeys.isEmpty()) {
            insertWithAutoIncrementKey(classInfo, obj);
        } else {
            ps = getConnection().prepareStatement(classInfo.insertSQL);
            addParameters(obj, classInfo.insertFields, ps, 1);
            ps.executeUpdate();
        }
    } catch (SienaException e) {
        throw e;
    } catch (Exception e) {
        throw new SienaException(e);
    } finally {
        JdbcDBUtils.closeStatementAndConnection(this, ps);
    }
}
Also used : Field(java.lang.reflect.Field) PreparedStatement(java.sql.PreparedStatement) Id(siena.Id) SienaException(siena.SienaException) SQLException(java.sql.SQLException) SienaException(siena.SienaException) IOException(java.io.IOException) SienaRestrictedApiException(siena.SienaRestrictedApiException)

Example 9 with Id

use of siena.Id in project siena by mandubian.

the class DdlGenerator method addTable.

public Table addTable(Class<?> clazz) {
    if (Modifier.isAbstract(clazz.getModifiers())) {
        return null;
    }
    Table table = new Table();
    ClassInfo info = ClassInfo.getClassInfo(clazz);
    table.setName(info.tableName);
    table.setType("MyISAM");
    database.addTable(table);
    Map<String, UniqueIndex> uniques = new HashMap<String, UniqueIndex>();
    Map<String, NonUniqueIndex> indexes = new HashMap<String, NonUniqueIndex>();
    /* columns */
    for (Field field : info.allFields) {
        String[] columns = ClassInfo.getColumnNames(field);
        boolean notNull = field.getAnnotation(NotNull.class) != null;
        Class<?> type = field.getType();
        if (!ClassInfo.isModel(type) || (ClassInfo.isModel(type) && ClassInfo.isEmbedded(field))) {
            Column column = createColumn(clazz, field, columns[0]);
            if (notNull || type.isPrimitive()) {
                column.setRequired(true);
                if (type.isPrimitive() && !ClassInfo.isId(field)) {
                    // TODO: add also Boolean, Long, Double,... ?
                    if (type == Boolean.TYPE) {
                        column.setDefaultValue("false");
                    } else {
                        column.setDefaultValue("0");
                    }
                }
            }
            Id id = field.getAnnotation(Id.class);
            if (id != null) {
                column.setPrimaryKey(true);
                column.setRequired(true);
                // auto_increments managed ONLY for long
                if (id.value() == Generator.AUTO_INCREMENT && (Long.TYPE == type || Long.class.isAssignableFrom(type)))
                    column.setAutoIncrement(true);
            // adds index on primary key
            /*UniqueIndex i = uniques.get(columns[0]);
					if(i == null) {
						i = new UniqueIndex();
						i.setName(columns[0]);
						uniques.put(columns[0], i);
						table.addIndex(i);
					}
					fillIndex(i, field);*/
            }
            table.addColumn(column);
        } else {
            List<Field> keys = ClassInfo.getClassInfo(type).keys;
            for (int i = 0; i < columns.length; i++) {
                Field f = keys.get(i);
                Column column = createColumn(clazz, f, columns[i]);
                if (notNull)
                    column.setRequired(true);
                table.addColumn(column);
            }
        }
    }
    /* indexes */
    for (Field field : info.updateFields) {
        Index index = field.getAnnotation(Index.class);
        if (index != null) {
            String[] names = index.value();
            for (String name : names) {
                NonUniqueIndex i = indexes.get(name);
                if (i == null) {
                    i = new NonUniqueIndex();
                    i.setName(name);
                    indexes.put(name, i);
                    table.addIndex(i);
                }
                fillIndex(i, field);
            }
        }
        Unique unique = field.getAnnotation(Unique.class);
        if (unique != null) {
            String[] names = unique.value();
            for (String name : names) {
                UniqueIndex i = uniques.get(name);
                if (i == null) {
                    i = new UniqueIndex();
                    i.setName(name);
                    uniques.put(name, i);
                    table.addIndex(i);
                }
                fillIndex(i, field);
            }
        }
    }
    tables.put(table.getName(), table);
    return table;
}
Also used : Table(org.apache.ddlutils.model.Table) NonUniqueIndex(org.apache.ddlutils.model.NonUniqueIndex) HashMap(java.util.HashMap) NonUniqueIndex(org.apache.ddlutils.model.NonUniqueIndex) Index(siena.Index) UniqueIndex(org.apache.ddlutils.model.UniqueIndex) NotNull(siena.NotNull) Field(java.lang.reflect.Field) IndexColumn(org.apache.ddlutils.model.IndexColumn) Column(org.apache.ddlutils.model.Column) Unique(siena.Unique) Id(siena.Id) NonUniqueIndex(org.apache.ddlutils.model.NonUniqueIndex) UniqueIndex(org.apache.ddlutils.model.UniqueIndex) ClassInfo(siena.ClassInfo)

Example 10 with Id

use of siena.Id in project siena by mandubian.

the class JdbcPersistenceManager method save.

@Override
public int save(Iterable<?> objects) {
    Map<JdbcClassInfo, List<Object>> objMap = new HashMap<JdbcClassInfo, List<Object>>();
    PreparedStatement ps = null;
    for (Object obj : objects) {
        JdbcClassInfo classInfo = JdbcClassInfo.getClassInfo(obj.getClass());
        if (!objMap.containsKey(classInfo)) {
            List<Object> l = new ArrayList<Object>();
            l.add(obj);
            objMap.put(classInfo, l);
        } else {
            objMap.get(classInfo).add(obj);
        }
    }
    int total = 0;
    try {
        for (JdbcClassInfo classInfo : objMap.keySet()) {
            if (!classInfo.generatedKeys.isEmpty()) {
                ps = getConnection().prepareStatement(classInfo.insertOrUpdateSQL, Statement.RETURN_GENERATED_KEYS);
            } else {
                ps = getConnection().prepareStatement(classInfo.insertOrUpdateSQL);
            }
            for (Object obj : objMap.get(classInfo)) {
                Field idField = classInfo.info.getIdField();
                Object idVal = Util.readField(obj, idField);
                // only generates a UUID if the idVal is null
                if (idVal == null) {
                    for (Field field : classInfo.keys) {
                        Id id = field.getAnnotation(Id.class);
                        if (id.value() == Generator.UUID) {
                            field.set(obj, UUID.randomUUID().toString());
                        }
                    }
                }
                // TODO: implement primary key generation: SEQUENCE
                int i = 1;
                i = addParameters(obj, classInfo.allFields, ps, i);
                addParameters(obj, classInfo.updateFields, ps, i);
                ps.addBatch();
            }
            int[] res = ps.executeBatch();
            if (!classInfo.generatedKeys.isEmpty()) {
                ResultSet gk = ps.getGeneratedKeys();
                int i;
                int idx = 0;
                int sz = objMap.get(classInfo).size();
                // so we take only the first SZ values which are the key values.
                while (gk.next() && idx < sz) {
                    i = 1;
                    for (Field field : classInfo.generatedKeys) {
                        field.setAccessible(true);
                        JdbcMappingUtils.setFromObject(objMap.get(classInfo).get(idx++), field, gk.getObject(i++));
                    }
                }
            }
            total += res.length;
        }
        return total;
    } catch (SienaException e) {
        throw e;
    } catch (Exception e) {
        throw new SienaException(e);
    } finally {
        JdbcDBUtils.closeStatementAndConnection(this, ps);
    }
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) SQLException(java.sql.SQLException) SienaException(siena.SienaException) IOException(java.io.IOException) SienaRestrictedApiException(siena.SienaRestrictedApiException) Field(java.lang.reflect.Field) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) Id(siena.Id) SienaException(siena.SienaException)

Aggregations

Id (siena.Id)17 Field (java.lang.reflect.Field)14 SienaException (siena.SienaException)14 SienaRestrictedApiException (siena.SienaRestrictedApiException)13 IOException (java.io.IOException)7 PreparedStatement (java.sql.PreparedStatement)7 ResultSet (java.sql.ResultSet)5 SQLException (java.sql.SQLException)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)3 List (java.util.List)3 ClassInfo (siena.ClassInfo)3 Entity (com.google.appengine.api.datastore.Entity)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 Key (com.google.appengine.api.datastore.Key)1 FilterOperator (com.google.appengine.api.datastore.Query.FilterOperator)1 Collection (java.util.Collection)1 UUID (java.util.UUID)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1