All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hecloud.runtime.database.builder.InBuilder Maven / Gradle / Ivy

There is a newer version: 1.0.8
Show newest version
package com.hecloud.runtime.database.builder;

import com.alibaba.fastjson.JSON;
import com.hecloud.runtime.common.utils.Common;
import com.hecloud.runtime.database.utils.Command;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Objects;

/**
 * In 查询SQL拼接
 *
 * @author LoveinBJ
 */
public class InBuilder {

    /**
     * In 查询语句拼接
     *
     * @param source  源SQL
     * @param objects 值列表
     * @return SQL语句
     */
    public static String build(String source, Collection objects) {
        if (null == objects || objects.isEmpty()) {
            return source;
        }
        return source + build(objects);
    }

    public static String build(Collection objects) {
        StringBuilder builder = new StringBuilder(Command.LEFTB);
        DateFormat dateFormat = new SimpleDateFormat(Common.DATETIME_FORMAT);
        objects.stream().filter(Objects::nonNull).forEach(object -> {
            String value;
            if (object instanceof Long
                    || object instanceof Integer
                    || object instanceof Float
                    || object instanceof Double) {
                value = object.toString();
            } else if (object instanceof Date) {
                value = dateFormat.format((Date) object);
            } else if (object instanceof String) {
                value = (String) object;
            } else {
                value = JSON.toJSONString(object);
            }
            builder.append(Command.QUOTE).append(value).append(Command.QUOTE).append(Command.COMMA);
        });
        builder.deleteCharAt(builder.length() - 1);
        builder.append(Command.RIGHTB);
        return builder.toString();
    }
}