Async single record insertion

@return {@link SingleInsertionResult}
如果插入的记录是自动生成主键的，返回结果中会包含自动生成的主键id，否则返回的id属性为null，
同时返回插入条数。
489603
private Single<SingleInsertionResult> insert(String preparedSql, Object[] sqlParams) {
        return Single.fromCallable(() -> {
            PreparedStatement statement = connection0.prepareStatement(preparedSql, PreparedStatement.RETURN_GENERATED_KEYS);
            for (int i = 0; i < sqlParams.length; i++) {
                statement.setObject(i + 1, sqlParams[i]);
            }
            statement.execute();
            ResultSet rs = statement.getGeneratedKeys();
            Integer count = statement.getUpdateCount();
            Long id;
            if (rs.next()) {
                id = rs.getLong(1);
            } else {
                //no id is generated
                id = null;
            }
            rs.close();
            statement.close();
            return new SingleInsertionResult().setCount(count).setId(id).setPreparedSql(preparedSql);
        });
    }
421317
public static <T> String getInsertSQL(T t, List<Object> values, boolean isWithNullValue) {
        StringBuilder sql = new StringBuilder("INSERT INTO ");

        Table table = DOInfoReader.getTable(t.getClass());
        List<Field> fields = DOInfoReader.getColumns(t.getClass());

        sql.append(getTableName(table)).append(" (");
        List<Object> _values = new ArrayList<Object>(); // 之所以增加一个临时变量，是避免values初始不是空的易错情况
        String fieldSql = joinAndGetValue(fields, ",", _values, t, isWithNullValue);
        sql.append(fieldSql);
        sql.append(") VALUES ");
        String dotSql = "(" + join("?", _values.size(), ",") + ")";
        sql.append(dotSql);
        values.addAll(_values);

        return sql.toString();
	}
314478
public int[] insert(Connection conn, Collection<Entity> records) throws SQLException {
		return insert(conn, records.toArray(new Entity[records.size()]));
	}
1006502
protected ConcurrentSubList.Link insert(Token token,
                                            ConcurrentSubList.Link insertPoint,
                                            Transaction transaction)
                    throws ObjectManagerException
    {
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.entry(this, cclass,
                        "insert",
                        new Object[] { token, insertPoint, transaction });

        ConcurrentSubList.Link newLink = null;

        synchronized (transaction.internalTransaction) {
            // Establish the sequenceNumber of this Object in the overall list,
            // before the insert point.
            long sequenceNumber = insertPoint.sequenceNumber;
            sequenceNumber--;
            // Figure out which subList the Object should be added to.
            ConcurrentSubList list = getSublist(sequenceNumber);
            // Add the link near the tail of the list according to its assigned
            // sequence number.
            tailSequenceNumberLock.lock();
            try {
                newLink = list.addEntry(token,
                                        transaction,
                                        sequenceNumber,
                                        this);
            } finally {
                if (tailSequenceNumberLock.isHeldByCurrentThread())
                    tailSequenceNumberLock.unlock();
            } // try (tailSequenceNumberLock).
        } // synchronized (transaction.internalTransaction).

        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.exit(this, cclass,
                       "insert",
                       new Object[] { newLink });
        return newLink;
    }
1066604
public int create(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {
		if (mappedInsert == null) {
			mappedInsert = MappedCreate.build(dao, tableInfo);
		}
		int result = mappedInsert.insert(databaseType, databaseConnection, data, objectCache);
		if (dao != null && !localIsInBatchMode.get()) {
			dao.notifyChanges();
		}
		return result;
	}
357209
public Candidate instantiateForInsert() {
		Candidate entity = new Candidate();
		entity.setCategory(new Category(512973));
		entity.setComments("New lead candidate");
		entity.setEmployeeType("W2");
		entity.setIsDeleted(Boolean.FALSE);
		entity.setIsEditable(Boolean.TRUE);
		entity.setPreferredContact("Email");
		entity.setStatus("New Lead");
		entity.setOwner(new CorporateUser(1));
		entity.setName("");
		entity.setFirstName("");
		entity.setLastName("");
		entity.setUsername(new DateTime().toString());
		entity.setPassword("secret");
		return entity;
	}
704515
@Override
    public final Object singleResult(DBCollection dbCollection) {
        MapReduceOutput output = dbCollection.mapReduce(createMapFunction(), createReduceFunction(), null, query);
        Iterable<DBObject> results = output.results();

        try {
            return transformToValue(results);
        } finally {
            output.drop();
        }
    }
660696
@Override
	public synchronized RecordScan insert(long sessionId, String scanName) throws DatabaseException {
    	SqlPreparedStatementWrapper psInsert = null;
        try {
        	psInsert = DbSQL.getSingleton().getPreparedStatement("scan.ps.insert");
			psInsert.getPs().setLong(1, sessionId);
			psInsert.getPs().setString(2, scanName);
			psInsert.getPs().executeUpdate();
			
			int id;
			try (ResultSet rs = psInsert.getLastInsertedId()) {
				rs.next();
				id = rs.getInt(1);
			}
			return read(id);
		} catch (SQLException e) {
			throw new DatabaseException(e);
		} finally {
			DbSQL.getSingleton().releasePreparedStatement(psInsert);
		}
    }
1351971
public int[] insert(Connection conn, Entity... records) throws SQLException {
		checkConn(conn);
		if(ArrayUtil.isEmpty(records)){
			return new int[]{0};
		}
		
		//单条单独处理
		if(1 == records.length) {
			return new int[] { insert(conn, records[0])};
		}
		
		PreparedStatement ps = null;
		try {
			ps = dialect.psForInsertBatch(conn, records);
			return ps.executeBatch();
		} finally {
			DbUtil.close(ps);
		}
	}
498394
@SuppressWarnings("unchecked")
	@Override
	public int insert(final Object entity) {
		@SuppressWarnings("rawtypes")
		EntityHandler handler = this.getEntityHandler();
		if (!handler.getEntityType().isInstance(entity)) {
			throw new IllegalArgumentException("Entity type not supported");
		}

		try {
			Class<?> type = entity.getClass();
			TableMetadata metadata = handler.getMetadata(this.transactionManager, type);
			SqlContext context = handler.createInsertContext(this, metadata, type);
			context.setSqlKind(SqlKind.INSERT);

			// IDアノテーションが付与されたカラム情報を取得する
			MappingColumn[] idColumns = MappingUtils.getIdMappingColumns(type);

			setGeneratedKeyColumns(context, idColumns, metadata);

			handler.setInsertParams(context, entity);
			int count = handler.doInsert(this, context, entity);

			if (idColumns != null && idColumns.length > 0) {
				BigDecimal[] ids = context.getGeneratedKeyValues();
				int idx = 0;
				for (MappingColumn col : idColumns) {
					BigDecimal id = ids[idx++];
					setEntityIdValue(entity, id, col);
				}
			}

			return count;
		} catch (SQLException e) {
			throw new EntitySqlRuntimeException(SqlKind.INSERT, e);
		}
	}
531723
@Override
	public <T extends DAO> T insert(DAO dao, boolean excludePrimaryKeys)  throws DatabaseException{
		ModelDef model = db.getModelMetaDataDefinition().getDefinition(dao.getModelName());
		if(excludePrimaryKeys){
			dao.add_IgnoreColumn( model.getPrimaryAttributes());
		}
		return insertRecord(dao, model, true);
	}
421637
@Override
    public DaoResult createOrUpdate(T bo) {
        if (bo == null) {
            return null;
        }
        try (Connection conn = getConnection(upsertInTransaction)) {
            return createOrUpdate(conn, bo);
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }
861131
protected BatchInserter getBatchInserter()
    {
        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(
                getPersistenceUnit());
        Properties props = puMetadata.getProperties();

        // Datastore file path
        String datastoreFilePath = (String) props.get(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);
        if (StringUtils.isEmpty(datastoreFilePath))
        {
            throw new PersistenceException(
                    "For Neo4J, it's mandatory to specify kundera.datastore.file.path property in persistence.xml");
        }

        // Shut down Graph DB, at a time only one service may have lock on DB
        // file
        if (factory.getConnection() != null)
        {
            factory.getConnection().shutdown();
        }

        BatchInserter inserter = null;

        // Create Batch inserter with configuration if specified
        Neo4JSchemaMetadata nsmd = Neo4JPropertyReader.nsmd;
        ClientProperties cp = nsmd != null ? nsmd.getClientProperties() : null;
        if (cp != null)
        {
            DataStore dataStore = nsmd != null ? nsmd.getDataStore() : null;
            Properties properties = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection()
                    .getProperties() : null;

            if (properties != null)
            {
                Map<String, String> config = new HashMap<String, String>((Map) properties);
                inserter = BatchInserters.inserter(datastoreFilePath, config);
            }
        }

        // Create Batch inserter without configuration if not provided
        if (inserter == null)
        {
            inserter = BatchInserters.inserter(datastoreFilePath);
        }
        return inserter;
    }
927085
public int[] insert(Collection<Entity> records) throws SQLException {
		Connection conn = null;
		try {
			conn = this.getConnection();
			return runner.insert(conn, records);
		} catch (SQLException e) {
			throw e;
		} finally {
			this.closeConnection(conn);
		}
	}
880785
@InterfaceStability.Committed
    public AsyncMutateInBuilder insertDocument(boolean insertDocument) {
        if (this.upsertDocument && insertDocument) {
            throw new IllegalArgumentException("Cannot set both upsertDocument and insertDocument to true");
        }
        this.insertDocument = insertDocument;
        return this;
    }
1137986
public T insert(T entity) {

        if (!hasPrimaryKey(entity)) {
            throw new RuntimeException(String.format("Tried to insert entity of type %s with null or zero primary key",
                    entity.getClass().getSimpleName()));
        }

        InsertCreator insert = new InsertCreator(table);

        insert.setValue(idColumn.getColumnName(), getPrimaryKey(entity));

        if (versionColumn != null) {
            insert.setValue(versionColumn.getColumnName(), 0);
        }

        for (Column column : columns) {
            if (!column.isReadOnly()) {
                insert.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));
            }
        }

        new JdbcTemplate(ormConfig.getDataSource()).update(insert);

        if (versionColumn != null) {
            ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), 0);
        }

        return entity;
    }
635343
public static String insertColumns(Class<?> entityClass, boolean skipId, boolean notNull, boolean notEmpty) {
        StringBuilder sql = new StringBuilder();
        sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">");
        //获取全部列
        Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnSet) {
            if (!column.isInsertable()) {
                continue;
            }
            if (skipId && column.isId()) {
                continue;
            }
            if (notNull) {
                sql.append(SqlHelper.getIfNotNull(column, column.getColumn() + ",", notEmpty));
            } else {
                sql.append(column.getColumn() + ",");
            }
        }
        sql.append("</trim>");
        return sql.toString();
    }