Search in sources :

Example 1 with Scalar

use of io.requery.query.Scalar in project requery by requery.

the class EntityWriter method insert.

void insert(final E entity, EntityProxy<E> proxy, Cascade mode, GeneratedKeys<E> keys) {
    // if the type is immutable return the key(s) to the caller instead of modifying the object
    GeneratedResultReader keyReader = null;
    if (hasGeneratedKey) {
        final Settable<E> settable = keys == null ? proxy : keys;
        keyReader = new GeneratedResultReader() {

            @Override
            public void read(int index, ResultSet results) throws SQLException {
                if (results.next()) {
                    readGeneratedKeys(settable, results);
                }
            }

            @Override
            public String[] generatedColumns() {
                return generatedColumnNames;
            }
        };
    }
    EntityUpdateOperation insert = new EntityUpdateOperation(context, keyReader) {

        @Override
        public int bindParameters(PreparedStatement statement) throws SQLException {
            return EntityWriter.this.bindParameters(statement, entity, null);
        }
    };
    QueryElement<Scalar<Integer>> query = new QueryElement<>(QueryType.INSERT, model, insert);
    query.from(entityClass);
    for (Attribute<E, ?> attribute : associativeAttributes) {
        // persist the foreign key object if needed
        cascadeKeyReference(Cascade.INSERT, proxy, attribute);
    }
    incrementVersion(proxy);
    for (Attribute attribute : bindableAttributes) {
        query.value((Expression) attribute, null);
    }
    context.getStateListener().preInsert(entity, proxy);
    checkRowsAffected(query.get().value(), entity, null);
    proxy.link(context.read(entityClass));
    updateAssociations(mode, entity, proxy, null);
    context.getStateListener().postInsert(entity, proxy);
    // cache entity
    if (cacheable) {
        cache.put(entityClass, proxy.key(), entity);
    }
}
Also used : UPDATE(io.requery.query.element.QueryType.UPDATE) SQLException(java.sql.SQLException) QueryAttribute(io.requery.meta.QueryAttribute) Attribute(io.requery.meta.Attribute) PreparedStatement(java.sql.PreparedStatement) QueryElement(io.requery.query.element.QueryElement) Scalar(io.requery.query.Scalar) ResultSet(java.sql.ResultSet)

Aggregations

Attribute (io.requery.meta.Attribute)1 QueryAttribute (io.requery.meta.QueryAttribute)1 Scalar (io.requery.query.Scalar)1 QueryElement (io.requery.query.element.QueryElement)1 UPDATE (io.requery.query.element.QueryType.UPDATE)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1