Java Code Examples for org.apache.ibatis.jdbc.SQL

The following are top voted examples for showing how to use org.apache.ibatis.jdbc.SQL. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: mybatis-spring-support   File: CrudProvider.java   Source Code and License 7 votes vote down vote up
/**
 * 查询所有记录(分页)
 *
 * @param parameter
 * @return
 */
public String findByPage(final Map<String, Object> parameter) {
  return new SQL() {
    {
      Class<?> clazz = (Class<?>) parameter.get(CLASS_KEY);
      SELECT("*");
      FROM(EntityUtil.getTableName(clazz));
      if (parameter.containsKey(WHERE_KEY)) {
        WHERE((String) parameter.get(WHERE_KEY));
      }
      if (parameter.containsKey(ORDER_KEY)) {
        ORDER_BY((String) parameter.get(ORDER_KEY));
      }
      if (parameter.containsKey(GROUP_KEY)) {
        GROUP_BY((String) parameter.get(GROUP_KEY));
      }
    }
  }.toString();
}
 
Example 2
Project: hibatis   File: SqlBuilder.java   Source Code and License 6 votes vote down vote up
public String update(String[] fields, String conditions) {
	SQL sql = new SQL().UPDATE(metadata.getTableName() + " AS _this");
	for (ColumnProperty property : metadata.getUpdateProperties()) {
		String propertyName = property.getName();
		// 不包含字段
		if (fields.length > 0 && !ArrayUtils.contains(fields, propertyName)) {
			continue;
		}
		Path path = root.getPath(property);
		sql.SET(path.getColumn() + "=#{" + path.getPropertyName() + "}");
	}
	if (conditions != null && conditions.length() > 0) {
		sql.WHERE(conditions);
	}
	return sql.toString();
}
 
Example 3
Project: k-framework   File: BaseSqlBuilder.java   Source Code and License 6 votes vote down vote up
public String insert(T record) {
    SQL sql = new SQL().INSERT_INTO(this.getTableName());
    getAllDeclaredFields(entityClass).stream()
            .filter(field -> !field.isAnnotationPresent(Ignore.class))
            .forEach(field -> {
                String fieldName = field.getName();
                Object value = valueOfField(record, fieldName);
                if (null != value) {
                    if (field.isAnnotationPresent(Column.class)) {
                        Column annotation = field.getAnnotation(Column.class);
                        sql.VALUES(annotation.column().trim(), fieldExpression(fieldName, annotation));
                    } else {
                        sql.VALUES(columnName(fieldName), fieldExpression(fieldName, null));
                    }
                }
            });
    if (logger.isDebugEnabled()) {
        logger.debug(sql.toString());
    }
    return sql.toString();
}
 
Example 4
Project: Okra-Ax   File: AccountSqlProvider.java   Source Code and License 6 votes vote down vote up
public String insertSql(final MemAccount memAccount) {
    return new SQL(){{
        INSERT_INTO(TABLE_NAME);
        VALUES("uid", "#{uid}");
        VALUES("name", "#{name}");
        VALUES("figure", "#{figure}");
        VALUES("account", "#{account}");
        VALUES("psw", "#{psw}");
        VALUES("email", "#{email}");
        VALUES("phone", "#{phone}");
        VALUES("channel", "#{channel}");
        VALUES("platform", "#{platform}");
        VALUES("timeCreate", "#{timeCreate}");
        VALUES("timeLastLogin", "#{timeLastLogin}");
        VALUES("ipCreate", "#{ipCreate}");
        VALUES("ipLastLogin", "#{ipLastLogin}");
        VALUES("vipLevel", "#{vipLevel}");
        VALUES("vipExp", "#{vipExp}");
        VALUES("rmb", "#{rmb}");
    }}.toString();
}
 
Example 5
Project: Okra-Ax   File: AccountSqlProvider.java   Source Code and License 6 votes vote down vote up
public String updateSql() {
    return new SQL(){{
        UPDATE(TABLE_NAME);
        SET("uid=#{uid}");
        SET("name=#{name}");
        SET("figure=#{figure}");
        SET("account=#{account}");
        SET("psw=#{psw}");
        SET("email=#{email}");
        SET("phone=#{phone}");
        SET("channel=#{channel}");
        SET("platform=#{platform}");
        SET("timeLastLogin=#{timeLastLogin}");
        SET("ipLastLogin=#{ipLastLogin}");
        SET("vipLevel=#{vipLevel}");
        SET("vipExp=#{vipExp}");
        SET("rmb=#{rmb}");
        WHERE("uid=#{uid}");
    }}.toString();
}
 
Example 6
Project: SpringbootMybatis   File: UserSqlProvider.java   Source Code and License 6 votes vote down vote up
/**
 * This method was generated by MyBatis Generator.
 * This method corresponds to the database table user
 *
 * @mbg.generated
 */
public String insertSelective(User record) {
    SQL sql = new SQL();
    sql.INSERT_INTO("user");
    
    if (record.getId() != null) {
        sql.VALUES("id", "#{id,jdbcType=INTEGER}");
    }
    
    if (record.getUsername() != null) {
        sql.VALUES("username", "#{username,jdbcType=VARCHAR}");
    }
    
    if (record.getPsw() != null) {
        sql.VALUES("psw", "#{psw,jdbcType=VARCHAR}");
    }
    
    return sql.toString();
}
 
Example 7
Project: SpringbootMybatis   File: UserSqlProvider.java   Source Code and License 6 votes vote down vote up
/**
 * This method was generated by MyBatis Generator.
 * This method corresponds to the database table user
 *
 * @mbg.generated
 */
public String selectByExample(UserCriteria example) {
    SQL sql = new SQL();
    if (example != null && example.isDistinct()) {
        sql.SELECT_DISTINCT("id");
    } else {
        sql.SELECT("id");
    }
    sql.SELECT("username");
    sql.SELECT("psw");
    sql.FROM("user");
    applyWhere(sql, example, false);
    
    if (example != null && example.getOrderByClause() != null) {
        sql.ORDER_BY(example.getOrderByClause());
    }
    
    return sql.toString();
}
 
Example 8
Project: SpringbootMybatis   File: UserSqlProvider.java   Source Code and License 6 votes vote down vote up
/**
 * This method was generated by MyBatis Generator.
 * This method corresponds to the database table user
 *
 * @mbg.generated
 */
public String updateByExampleSelective(Map<String, Object> parameter) {
    User record = (User) parameter.get("record");
    UserCriteria example = (UserCriteria) parameter.get("example");
    
    SQL sql = new SQL();
    sql.UPDATE("user");
    
    if (record.getId() != null) {
        sql.SET("id = #{record.id,jdbcType=INTEGER}");
    }
    
    if (record.getUsername() != null) {
        sql.SET("username = #{record.username,jdbcType=VARCHAR}");
    }
    
    if (record.getPsw() != null) {
        sql.SET("psw = #{record.psw,jdbcType=VARCHAR}");
    }
    
    applyWhere(sql, example, true);
    return sql.toString();
}
 
Example 9
Project: SpringbootMybatis   File: UserSqlProvider.java   Source Code and License 6 votes vote down vote up
/**
 * This method was generated by MyBatis Generator.
 * This method corresponds to the database table user
 *
 * @mbg.generated
 */
public String updateByPrimaryKeySelective(User record) {
    SQL sql = new SQL();
    sql.UPDATE("user");
    
    if (record.getUsername() != null) {
        sql.SET("username = #{username,jdbcType=VARCHAR}");
    }
    
    if (record.getPsw() != null) {
        sql.SET("psw = #{psw,jdbcType=VARCHAR}");
    }
    
    sql.WHERE("id = #{id,jdbcType=INTEGER}");
    
    return sql.toString();
}
 
Example 10
Project: mybatis-easy-mapper   File: SQLProvider.java   Source Code and License 6 votes vote down vote up
public String select(Map<String, Object> params) {
    Object condition = params.get("condition");
    EntityTable entityTable = getEntityTable(condition.getClass());
    Pageable pageable = null;
    if (params.containsKey("pageable")) {
        pageable = (Pageable) params.get("pageable");
    }
    SQL sql = new SQL();
    sql.SELECT(entityTable.getSelectColumns());
    sql.FROM(entityTable.getName());
    entityTable.getInnerJoins().forEach(sql::INNER_JOIN);
    applyWhere(sql, entityTable, condition);
    if (pageable == null) {
        entityTable.getOrderBys().forEach(sql::ORDER_BY);
        return sql.toString();
    } else {
        return applyPageable(sql, pageable);
    }
}
 
Example 11
Project: mybatis-spring-support   File: CrudProvider.java   Source Code and License 6 votes vote down vote up
/**
 * 更新操作
 *
 * @param obj
 * @return String
 */
public String update(Object obj) {
  Class<?> clazz = obj.getClass();
  PersistMeta meta = EntityUtil.getMeta(clazz);
  StringBuilder setting = new StringBuilder(32);
  int i = 0;
  for (Map.Entry<String, Field> kv : meta.getColumns().entrySet()) {
    if (isNull(kv.getValue(), obj)) {
      continue;
    }

    if (i++ != 0) {
      setting.append(',');
    }

    setting.append('`').append(kv.getKey()).append('`').append("=#{").append(kv.getValue().getName()).append('}');
  }

  return new SQL().UPDATE(getTableName(meta, obj)).SET(setting.toString()).WHERE("id=#{id}").toString();
}
 
Example 12
Project: mybatis-spring-support   File: CrudProvider.java   Source Code and License 6 votes vote down vote up
/**
 * 新增操作
 *
 * @param obj
 * @return String
 */
public String insert(Object obj) {
  PersistMeta meta = EntityUtil.getMeta(obj.getClass());
  StringBuilder names = new StringBuilder(), values = new StringBuilder();
  int i = 0;
  for (Map.Entry<String, Field> kv : meta.getColumns().entrySet()) {
    if (isNull(kv.getValue(), obj)) {
      continue;
    }

    if (i++ != 0) {
      names.append(',');
      values.append(',');
    }

    names.append('`').append(kv.getKey()).append('`');
    values.append("#{").append(kv.getValue().getName()).append('}');
  }

  return new SQL().INSERT_INTO(getTableName(meta, obj)).VALUES(names.toString(), values.toString()).toString();
}
 
Example 13
Project: mybatis-helper   File: SqlProvider.java   Source Code and License 6 votes vote down vote up
public String query(DefaultPageAndSortEntity defaultPageAndSortEntity) {
    try {
        final Map<String, Object> entityData = getParam(defaultPageAndSortEntity);
        return new SQL() {
            {
                SELECT("*");
                FROM(TABLE_NAME);
                for(String column : entityData.keySet()) {
                    WHERE(column + "=#{" + entityData.get(column) + "}");
                }
            }
        }.toString();
    } catch(Exception e) {
        throw new MybatisHelperException("query sql error", e);
    }
}
 
Example 14
Project: mybatis-helper   File: SqlProvider.java   Source Code and License 6 votes vote down vote up
public String count(DefaultPageAndSortEntity defaultPageAndSortEntity) {
    try {
        final Map<String, Object> entityData = getParam(defaultPageAndSortEntity);
        return new SQL() {
            {
                SELECT("count(*)");
                FROM(TABLE_NAME);
                for(String column : entityData.keySet()) {
                    WHERE(column + "=#{" + entityData.get(column) + "}");
                }
            }
        }.toString();
    } catch(Exception e) {
        throw new MybatisHelperException("count sql error", e);
    }
}
 
Example 15
Project: mybatis-helper   File: SqlProvider.java   Source Code and License 6 votes vote down vote up
public String update(Entity model) {
    try {
        final Map<String, Object> entityData = getParam(model);
        entityData.remove("id");
        return new SQL() {
            {
                UPDATE(TABLE_NAME);
                for(String column : entityData.keySet()) {
                    SET(column + "=#{" + entityData.get(column) + "}");
                }
                WHERE("id = #{id}");
            }
        }.toString();
    } catch(Exception e) {
        throw new MybatisHelperException("construct update sql error", e);
    }
}
 
Example 16
Project: mmt   File: LocalMsgBeanSQLProvider.java   Source Code and License 6 votes vote down vote up
/**
 * 提供deleteMsgSQLByCustomer的SQL
 * @param paramMap
 * @return
 */
public String deleteMsgSQLByCustomer(final Map<String, Object> paramMap) {
	final int cust_id = (int) paramMap.get("cust_id");
	final int level = (int) paramMap.get("level");
	if (level != 1 && level != 2 && level != 3)
		throw new MmtException("消息库找不到: level=" + level);
	if(level == 3)
		throw new MmtException("通用消息库不支持按照cust_id删除。");
	return new SQL() {
		{
			DELETE_FROM("msg_repo_l" + level);
			WHERE("cust_id=" + cust_id);
			
		}
	}.toString();
}
 
Example 17
Project: mybatis-3   File: OurSqlBuilder.java   Source Code and License 6 votes vote down vote up
public String buildSelectByIdAndNameMultipleParamAndProviderContextWithAtParam(@Param("id") final Integer id, ProviderContext context, @Param("name") final String name) {
  final boolean containsLogicalDelete = context.getMapperMethod().getAnnotation(BaseMapper.ContainsLogicalDelete.class) != null;
  final String tableName = context.getMapperType().getAnnotation(BaseMapper.Meta.class).tableName();
  return new SQL(){{
    SELECT("*");
    FROM(tableName);
    if (id != null) {
      WHERE("id = #{id}");
    }
    if (name != null) {
      WHERE("name like #{name} || '%'");
    }
    if (!containsLogicalDelete){
      WHERE("logical_delete = false");
    }
  }}.toString();
}
 
Example 18
Project: mybatis-3   File: OurSqlBuilder.java   Source Code and License 6 votes vote down vote up
public String buildSelectByIdAndNameMultipleParamAndProviderContext(final Integer id, final String name, ProviderContext context) {
  final boolean containsLogicalDelete = context.getMapperMethod().getAnnotation(BaseMapper.ContainsLogicalDelete.class) != null;
  final String tableName = context.getMapperType().getAnnotation(BaseMapper.Meta.class).tableName();
  return new SQL(){{
    SELECT("*");
    FROM(tableName);
    if (id != null) {
      WHERE("id = #{param1}");
    }
    if (name != null) {
      WHERE("name like #{param2} || '%'");
    }
    if (!containsLogicalDelete){
      WHERE("logical_delete = false");
    }
  }}.toString();
}
 
Example 19
Project: mybatis-plus-mini   File: SqlBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test1() {
    String sql = new SQL()
            .SELECT("id, name").FROM("PERSON A")
            .WHERE("name like ?")
            .WHERE("id = ?").toString();

    System.err.println(sql);
}
 
Example 20
Project: tasfe-framework   File: CrudDaoProvider.java   Source Code and License 5 votes vote down vote up
@Deprecated
public String insertSelectiveSql(final Map<String, Object> param) {
    return new SQL() {
        {
            INSERT_INTO((String) param.get("tableName"));

            @SuppressWarnings("unchecked")
            Map<String, String> mapping = (Map<String, String>) param.get("columnValueMapping");
            for (String key : mapping.keySet()) {
                VALUES(key, "#{columnValueMapping." + key + "}");
            }

        }
    }.toString();
}
 
Example 21
Project: tasfe-framework   File: CrudDaoProvider.java   Source Code and License 5 votes vote down vote up
@Deprecated
public String updateByPrimaryKeySql(final Map<String, Object> param) {
    return new SQL() {
        {
            UPDATE((String) param.get("tableName"));

            @SuppressWarnings("unchecked")
            Map<String, String> mapping = (Map<String, String>) param.get("columnValueMapping");
            for (String key : mapping.keySet()) {
                SET(key + "=" + "#{columnValueMapping." + key + "}");
            }

            WHERE((String) param.get("primaryKey") + "=" + param.get("primaryValue"));

        }
    }.toString();
}
 
Example 22
Project: easymall   File: SimpleMybatisSqlProvider.java   Source Code and License 5 votes vote down vote up
public String insert(SimpleTable simpleTable) throws EasyMallTestException {
    SQL sql = new SQL() {{
        INSERT_INTO(simpleTable.getTableName());
        for (String column : simpleTable.getColumns()) {
            INTO_VALUES("#{row." + column + "}");
            INTO_COLUMNS(column);
        }
    }};
    logger.debug(sql.toString());
    return sql.toString();
}
 
Example 23
Project: easymall   File: SimpleMybatisSqlProvider.java   Source Code and License 5 votes vote down vote up
public String select(SimpleTable simpleTable) throws EasyMallTestException {
    SQL sql = new SQL() {{
        SELECT(simpleTable.getColumns().toArray(new String[]{}));
        FROM(simpleTable.getTableName());
        Map<String, Object> params = simpleTable.getParam();
        Set<String> keys = params.keySet();

        for (String key : keys) {
            Object param = params.get(key);
            if (param instanceof Object[]) {
                StringBuilder inSql = new StringBuilder(key);
                inSql.append(" in (");
                Object[] paramArr = (Object[]) param;
                for (int i = 0; i < paramArr.length; i++) {
                    inSql.append("#{param.").append(key).append("[" + i + "]} ,");
                }
                inSql.deleteCharAt(inSql.length() - 1);
                inSql.append(" ) ");
                WHERE(inSql.toString());
            } else if (param instanceof String && ((String) param).contains("%")) {
                WHERE(key + " like '" + param + "'");
            } else {
                WHERE(key + "=#{param." + key + "}");
            }
        }

    }};
    logger.debug(sql.toString());
    return sql.toString();
}
 
Example 24
Project: mybatis-dao   File: RelationInsertExcutor.java   Source Code and License 5 votes vote down vote up
private int insert(Object fromId,Object toId,ManyToMany mm,DaoMapper daoMapper){
	SQL sql = new SQL();
	sql = sql.INSERT_INTO(mm.getRelationTableName());
	sql = sql.VALUES(mm.getFromId(), "#{" + mm.getFromId() + "}");
	sql = sql.VALUES(mm.getToId(), "#{" + mm.getToId() + "}");
	HashMap<String, Object> paramter = new HashMap<>();
	paramter.put(Constant.SQL_SYMBOL, sql.toString());
	paramter.put(mm.getFromId(), fromId);
	paramter.put(mm.getToId(), toId);
	return daoMapper.insert(paramter);
}
 
Example 25
Project: mybatis-dao   File: DeleteExcutor.java   Source Code and License 5 votes vote down vote up
public int delete(DeleteContext context){
	int count = -1;
	Object target = context.getTarget();
	Class<?> targetType = Toolkit.isCglibProxy(target) ? target.getClass().getSuperclass() : target.getClass();
	SQL sql = new SQL();
	sql.DELETE_FROM(getTableName(context));
	HashMap<String, Object> paramter = new HashMap<>();
	paramter.put(Constant.SQL_SYMBOL, context.getCondation() == null?sql.toString():sql.toString()+context.getCondation().toSql(targetType, paramter));
	count = context.getDaoMapper().delete(paramter);
	return count;
}
 
Example 26
Project: mybatis-dao   File: CondationUpdateExcutor.java   Source Code and License 5 votes vote down vote up
public int update(UpdateContext context){
	int count = -1;
	SQL sql = new SQL();
	sql.UPDATE(getTableName(context));
	HashMap<String, Object> paramter = new HashMap<>();
	Table table = TableMap.getInstance().getTableMap(clazz);
	for (int i = 0;i<fields.length;i++) {
		String fieldName = table.getDataBaseField(fields[i]);
		sql = sql.SET(fieldName+ " = #{" + fields[i] + i + "}");
		paramter.put(fields[i] + i, values[i]);
	}
	paramter.put(Constant.SQL_SYMBOL, sql.toString()+context.getCondation().toSql(clazz, paramter));
	
	count = context.getDaoMapper().update(paramter);
	
	return count;
}
 
Example 27
Project: mybatis-dao   File: UpdateExcutor.java   Source Code and License 5 votes vote down vote up
public int update(UpdateContext context){
	int count = -1;
	
	Object target = context.getTarget();
	Class<?> targetType = Toolkit.isCglibProxy(target) ? target.getClass().getSuperclass() : target.getClass();
	Table table = TableMap.getInstance().getTableMap(targetType);
	SQL sql = new SQL();
	
	sql.UPDATE(getTableName(context));
	HashMap<String, Object> paramter = new HashMap<>();
	for (String fieldStr : table.getDataBaseFieldMap().values()) {
		Field field = table.getField(fieldStr);
		if (field == table.getId().getField())
			continue;
		Object value = ReflectionUtils.getValue(target, field);
		if (value == null)
			continue;
		sql = sql.SET(fieldStr+ " = #{" + field.getName() + "}");
		paramter.put(field.getName(), value);
	}
	paramter.put(Constant.SQL_SYMBOL, sql.toString()+context.getCondation().toSql(targetType, paramter));
	
	count = context.getDaoMapper().update(paramter);
	
	return count;
}
 
Example 28
Project: hibatis   File: SqlBuilder.java   Source Code and License 5 votes vote down vote up
public String select(String conditions, String orderBy, LockMode lockMode) {
	SQL sql = select(conditions, orderBy);
	if (lockMode == LockMode.UPGRADE || lockMode == LockMode.UPGRADE_NOWAIT) {
		return sql + " FOR UPDATE";
	} else if (lockMode == LockMode.UPGRADE_NOWAIT) {
		return sql + " FOR UPDATE NOWAIT";
	} else {
		return sql.toString();
	}
}
 
Example 29
Project: hibatis   File: SqlBuilder.java   Source Code and License 5 votes vote down vote up
public String paging(String conditions, String orderBy, LockMode lockMode) {
	SQL sql = select(conditions, orderBy);
	StringBuilder sqlSb = new StringBuilder();
	sqlSb.append(sql);
	sqlSb.append(" LIMIT #{firstResult},#{maxResults}");
	if (lockMode == LockMode.UPGRADE) {
		sqlSb.append(" FOR UPDATE");
	}else if (lockMode == LockMode.UPGRADE_NOWAIT) {
		sqlSb.append(" FOR UPDATE NOWAIT");
	}
	return sqlSb.toString();
}
 
Example 30
Project: hibatis   File: SqlBuilder.java   Source Code and License 5 votes vote down vote up
public String select(String columns, String conditions, String groupBy, String orderBy) {
	String tableName = metadata.getTableName();
	SQL sql = new SQL().FROM(tableName + " _this");
	sql.SELECT(columns);
	// 加入查询条件
	if (!StringUtils.isEmpty(conditions)) {
		where(sql, conditions);
	}
	// 加入分组依据
	if (!StringUtils.isEmpty(groupBy)) {
		sql.GROUP_BY(groupBy);
	}
	// 加入排序条件
	if (!StringUtils.isEmpty(orderBy)) {
		sql.ORDER_BY(orderBy);
	}
	return sql.toString();
}
 
Example 31
Project: hibatis   File: SqlBuilder.java   Source Code and License 5 votes vote down vote up
public String count(String conditions) {
	String tableName = metadata.getTableName();
	SQL sql = new SQL().FROM(tableName + " _this");
	sql.SELECT("count(1)");
	// 加入查询条件
	where(sql, conditions);
	// 返回SQL语句
	return sql.toString();
}
 
Example 32
Project: hibatis   File: SqlBuilder.java   Source Code and License 5 votes vote down vote up
public String selectId(String conditions, String orderBy) {
	String tableName = metadata.getTableName();
	SQL sql = new SQL().FROM(tableName + " _this");
	List<IdProperty> properties = metadata.getIdProperties();
	for (IdProperty property : properties) {
		Path path = root.getPath(property);
		String column = path.getColumn() + " AS " + path.getMapping();
		sql.SELECT(column);
	}
	// 加入查询条件
	where(sql, conditions);
	// 加入排序条件
	if (!StringUtils.isEmpty(orderBy)) {
		sql.ORDER_BY(orderBy);
	}
	return sql.toString();
}
 
Example 33
Project: hibatis   File: SqlBuilder.java   Source Code and License 5 votes vote down vote up
private void where(SQL sql, String conditions) {
	// 外连接其他表
	for (AssociationProperty association : metadata.getAssociations()) {
		// 非Join方式不处理
		if (association.getFetchMode() != FetchMode.JOIN) {
			continue;
		}
		Class<?> referenceType = association.getReferenceType();
		EntityMetadata refMetadata = EntityMetadata.get(referenceType);
		// 获取主表和从表的关联属性
		StringBuilder joinBuilder = new StringBuilder();
		joinBuilder.append(refMetadata.getTableName());
		joinBuilder.append(" AS ");
		joinBuilder.append("_").append(association.getName());
		joinBuilder.append(" ON ");
		List<ColumnProperty> assocProperties = association.getProperties();
		List<ColumnProperty> refReferences = association.getReferences();
		for (int i = 0; i < assocProperties.size(); i++) {
			if (i > 0) {
				joinBuilder.append(" AND ");
			}
			ColumnProperty property = assocProperties.get(i);
			ColumnProperty reference = refReferences.get(i);
			joinBuilder.append(root.getPath(property).getColumn());
			joinBuilder.append("=");
			joinBuilder.append(root.getPath(association, reference).getColumn());
		}
		sql.LEFT_OUTER_JOIN(joinBuilder.toString());
	}
	if (!StringUtils.isEmpty(conditions)) {
		sql.WHERE(conditions);
	}
}
 
Example 34
Project: hibatis   File: SqlBuilder.java   Source Code and License 5 votes vote down vote up
public String insert() {
	String tableName = metadata.getTableName();
	List<ColumnProperty> properties = metadata.getInsertProperties();
	SQL sql = new SQL().INSERT_INTO(tableName);
	for (ColumnProperty property : properties) {
		// 是否为主键列
		if (property instanceof IdProperty) {
			IdProperty idProperty = (IdProperty) property;
			if (idProperty.keyGenerator != null) {
				continue;
			}
		}
		String name = property.getName();
		String columnName = property.getColumnName();
		sql.VALUES(columnName, "#{" + name + "}");
	}
	return sql.toString();
}
 
Example 35
Project: tulingchat   File: PageSqlProvider.java   Source Code and License 5 votes vote down vote up
protected String findByPage(PageRequest request, String tableName) {
	SQL sql = new SQL();
	sql.SELECT("*").FROM(tableName);
	if (request.getSorts() != null && request.getSorts().length != 0) {
		for (int i = 0; i < request.getSorts().length; i++) {
			PageRequest.Sort sort = request.getSorts()[i];
			sql.ORDER_BY(sort.getField() + " " + sort.getType());
		}
	}
	String preSql = sql.toString();
	StringBuilder sb = new StringBuilder(preSql);
	sb.append(" limit #{page.start},#{page.size}");
	return sb.toString();
}
 
Example 36
Project: tulingchat   File: CommentSqlProvider.java   Source Code and License 5 votes vote down vote up
public String findAll() {
	return new SQL() {
		{
			SELECT("*");
			FROM("comment");
		}
	}.toString();
}
 
Example 37
Project: easy-test   File: SimpleMybatisSqlProvider.java   Source Code and License 5 votes vote down vote up
public String insert(SimpleTable simpleTable) throws EasyTestException {
    SQL sql = new SQL() {{
        INSERT_INTO(simpleTable.getTableName());
        for (String column : simpleTable.getColumns()) {
            INTO_VALUES("#{row." + column + "}");
            INTO_COLUMNS(column);
        }
    }};
    logger.debug(sql.toString());
    return sql.toString();
}
 
Example 38
Project: easy-test   File: SimpleMybatisSqlProvider.java   Source Code and License 5 votes vote down vote up
public String select(SimpleTable simpleTable) throws EasyTestException {
    SQL sql = new SQL() {{
        SELECT(simpleTable.getColumns().toArray(new String[]{}));
        FROM(simpleTable.getTableName());
        Map<String, Object> params = simpleTable.getParam();
        Set<String> keys = params.keySet();

        for (String key : keys) {
            Object param = params.get(key);
            if (param instanceof Object[]) {
                StringBuilder inSql = new StringBuilder(key);
                inSql.append(" in (");
                Object[] paramArr = (Object[]) param;
                for (int i = 0; i < paramArr.length; i++) {
                    inSql.append("#{param.").append(key).append("[").append(i).append("]} ,");
                }
                inSql.deleteCharAt(inSql.length() - 1);
                inSql.append(" ) ");
                WHERE(inSql.toString());
            } else if (param instanceof String && ((String) param).contains("%")) {
                WHERE(key + " like '" + param + "'");
            } else {
                WHERE(key + "=#{param." + key + "}");
            }
        }

    }};
    logger.debug(sql.toString());
    return sql.toString();
}
 
Example 39
Project: jeeWe   File: BaseProvider.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public String saveSql(Object obj) throws Exception {
    String tableName = getTableName(obj);
    Map oMap = getBeanMap(obj);
    SQL iSql = new SQL();
    iSql.INSERT_INTO(tableName);
    for (Object key : oMap.keySet()) {
        iSql.VALUES(key.toString(), "#{" + key.toString() + "}");
    }
    return iSql.toString();
}
 
Example 40
Project: jeeWe   File: BaseProvider.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public String updateSql(Object obj) throws Exception {
    String tableName = getTableName(obj);
    Map oMap = getBeanMap(obj);
    SQL uSql = new SQL();
    uSql.UPDATE(tableName);
    for (Object key : oMap.keySet()) {
        // 属性为null,统一不做修改
        if (null != oMap.get(key) && !key.toString().equals("id")) {
            uSql.SET(key.toString() + " = #{" + key.toString() + "}");
        }
    }
    uSql.WHERE("id = #{id}");
    return uSql.toString();
}
 
Example 41
Project: jeeWe   File: BaseProvider.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private String deleteByExampleSql(Object obj, boolean flag) throws Exception {
    String tableName = getTableName(obj);
    Map oMap = getBeanMap(obj);
    SQL dSql = new SQL();
    dSql.DELETE_FROM(tableName);
    dSql.WHERE("1 = 1");
    for (Object key : oMap.keySet()) {
        if (null != oMap.get(key)) {
            if (flag) {
                dSql.AND();
            } else {
                dSql.OR();
            }
            dSql.WHERE(key.toString() + " = #{" + key.toString() + "}");
        }
    }
    return dSql.toString();
}
 
Example 42
Project: jeeWe   File: BaseProvider.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private String findByExampleSql(Object obj, boolean flag) throws Exception {
    String tableName = getTableName(obj);
    Map oMap = getBeanMap(obj);
    SQL fSql = new SQL();
    fSql.SELECT("*");
    fSql.FROM(tableName);
    fSql.WHERE("1 = 1");
    for (Object key : oMap.keySet()) {
        if (null != oMap.get(key)) {
            if (flag) {
                fSql.AND();
            } else {
                fSql.OR();
            }
            fSql.WHERE(key.toString() + " = #{" + key.toString() + "}");
        }
    }
    return fSql.toString();
}
 
Example 43
Project: jeeWe   File: BaseProvider.java   Source Code and License 5 votes vote down vote up
public String findAllSql(Object obj) throws Exception {
    String tableName = getTableName(obj);
    SQL fSql = new SQL();
    fSql.SELECT("*");
    fSql.FROM(tableName);
    return fSql.toString();
}
 
Example 44
Project: k-framework   File: SqlBuilderUtils.java   Source Code and License 5 votes vote down vote up
static void queryWHERE(SQL sql, Object query, String orderBy) {
    getAllDeclaredFields(query.getClass()).stream()
            .filter(field -> !field.isAnnotationPresent(Ignore.class))
            .forEach(field -> {
                String fieldName = field.getName();
                String columnName;
                String fieldExpression;
                if (field.isAnnotationPresent(Column.class)) {
                    Column annotation = field.getAnnotation(Column.class);
                    columnName = annotation.column().trim();
                    fieldExpression = fieldExpression("query." + fieldName, annotation);
                } else {
                    columnName = columnName(fieldName);
                    fieldExpression = fieldExpression("query." + fieldName, null);
                }
                Object value = valueOfField(query, fieldName);
                if (null != value) {
                    if (value instanceof String) {
                        if (!((String) value).isEmpty() && !value.equals("%%")) {
                            sql.WHERE(columnName + " like " + fieldExpression);
                        }
                    } else if (value instanceof Number
                            || value instanceof LocalDate
                            || value instanceof LocalDateTime) {
                        if (fieldName.startsWith("min")) {
                            sql.WHERE(columnName + ">=" + fieldExpression);
                        } else if (field.getName().startsWith("max")) {
                            sql.WHERE(columnName + "<=" + fieldExpression);
                        } else {
                            sql.WHERE(columnName + "=" + fieldExpression);
                        }
                    } else {
                        sql.WHERE(columnName + "=" + fieldExpression);
                    }
                }
            });
    if (null != orderBy && !orderBy.isEmpty()) {
        sql.ORDER_BY(orderBy);
    }
}
 
Example 45
Project: k-framework   File: SqlBuilderUtils.java   Source Code and License 5 votes vote down vote up
static SQL selectByQueryInternal(String tableName, Class clazz) {
    SQL sql = new SQL().FROM(tableName);
    getAllDeclaredFields(clazz).stream()
            .filter(field -> !field.isAnnotationPresent(Ignore.class))
            .forEach(field -> {
                if (field.isAnnotationPresent(Column.class)) {
                    sql.SELECT(field.getAnnotation(Column.class).column().trim());
                } else {
                    sql.SELECT(columnName(field.getName()));
                }
            });
    return sql;
}
 
Example 46
Project: k-framework   File: AbstractCommonSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String insert(Object record) {
    SQL sql = new SQL().INSERT_INTO(this.getTableName());
    getAllDeclaredFields(record.getClass()).stream()
            .filter(field -> !field.isAnnotationPresent(Ignore.class))
            .forEach(field -> {
                String fieldName = field.getName();
                Object value = valueOfField(record, fieldName);
                if (null != value) {
                    if (field.isAnnotationPresent(Column.class)) {
                        Column annotation = field.getAnnotation(Column.class);
                        sql.VALUES(annotation.column().trim(), fieldExpression(fieldName, annotation));
                    } else {
                        sql.VALUES(columnName(fieldName), fieldExpression(fieldName, null));
                    }
                }
            });
    if (logger.isDebugEnabled()) {
        logger.debug(sql.toString());
    }
    return sql.toString();
}
 
Example 47
Project: k-framework   File: AbstractCommonSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String updateByPrimaryKeySelective(Object record) {
    final String[] primaryKeyName = {null};
    final Column[] primaryKeyAnnotation = {null};
    SQL sql = new SQL().UPDATE(this.getTableName());
    getAllDeclaredFields(record.getClass()).stream()
            .filter(field -> !field.isAnnotationPresent(Ignore.class))
            .forEach(field -> {
                String fieldName = field.getName();
                if (field.isAnnotationPresent(PK.class)) {
                    primaryKeyName[0] = field.getName();
                    if (field.isAnnotationPresent(Column.class)) {
                        primaryKeyAnnotation[0] = field.getAnnotation(Column.class);
                    }
                }
                Object value = valueOfField(record, fieldName);
                if (null != value) {
                    if (field.isAnnotationPresent(Column.class)) {
                        Column annotation = field.getAnnotation(Column.class);
                        sql.SET(annotation.column().trim() + "=" + fieldExpression(fieldName, annotation));
                    } else {
                        sql.SET(columnName(fieldName) + "=" + fieldExpression(fieldName, null));
                    }
                }
            });
    if (null == primaryKeyName[0]) {
        return null;
    }
    if (null != primaryKeyAnnotation[0]) {
        sql.WHERE(primaryKeyAnnotation[0].column().trim()
                + "=" + fieldExpression(primaryKeyName[0], primaryKeyAnnotation[0]));
    } else {
        sql.WHERE(columnName(primaryKeyName[0])
                + "=" + fieldExpression(primaryKeyName[0], null));
    }
    return sql.toString();
}
 
Example 48
Project: k-framework   File: AbstractCommonSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String selectByQuery(Class clazz, @Param("query") Object query, String orderBy) {
    SQL sql = selectByQueryInternal(this.getTableName(), clazz);
    queryWHERE(sql, query, orderBy);
    if (logger.isDebugEnabled()) {
        logger.debug(sql.toString());
    }
    return sql.toString();
}
 
Example 49
Project: k-framework   File: AbstractCommonSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String selectPageByQuery(Class clazz, @Param("query") Object query, Page page) {
    String orderBy = null;
    if (null != page) {
        orderBy = page.getOrderBy();
    }
    SQL sql = selectByQueryInternal(this.getTableName(), clazz);
    queryWHERE(sql, query, orderBy);
    String sqlStr = sql.toString();
    if (null != page) {
        long limit = page.getPageSize();
        long offset = limit * (page.getPageNo() - 1);
        sqlStr += " limit " + offset + "," + limit;
    }
    if (logger.isDebugEnabled()) {
        logger.debug(sqlStr);
    }
    return sqlStr;
}
 
Example 50
Project: k-framework   File: AbstractCommonSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String countByQuery(Map<String, Object> params) {
    SQL sql = countByQueryInternal(this.getTableName());
    queryWHERE(sql, params.get("query"), null);
    if (logger.isDebugEnabled()) {
        logger.debug(sql.toString());
    }
    return sql.toString();
}
 
Example 51
Project: k-framework   File: BaseSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String updateByPrimaryKeySelective(T record) {
    final String[] primaryKeyName = {null};
    final Column[] primaryKeyAnnotation = {null};
    SQL sql = new SQL().UPDATE(this.getTableName());
    getAllDeclaredFields(entityClass).stream()
            .filter(field -> !field.isAnnotationPresent(Ignore.class))
            .forEach(field -> {
                String fieldName = field.getName();
                if (field.isAnnotationPresent(PK.class)) {
                    primaryKeyName[0] = field.getName();
                    if (field.isAnnotationPresent(Column.class)) {
                        primaryKeyAnnotation[0] = field.getAnnotation(Column.class);
                    }
                }
                Object value = valueOfField(record, fieldName);
                if (null != value) {
                    if (field.isAnnotationPresent(Column.class)) {
                        Column annotation = field.getAnnotation(Column.class);
                        sql.SET(annotation.column().trim() + "=" + fieldExpression(fieldName, annotation));
                    } else {
                        sql.SET(columnName(fieldName) + "=" + fieldExpression(fieldName, null));
                    }
                }
            });
    if (null == primaryKeyName[0]) {
        return null;
    }
    if (null != primaryKeyAnnotation[0]) {
        sql.WHERE(primaryKeyAnnotation[0].column().trim()
                + "=" + fieldExpression(primaryKeyName[0], primaryKeyAnnotation[0]));
    } else {
        sql.WHERE(columnName(primaryKeyName[0])
                + "=" + fieldExpression(primaryKeyName[0], null));
    }
    return sql.toString();
}
 
Example 52
Project: k-framework   File: BaseSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String selectByQuery(@Param("query") Object query, String orderBy) {
    SQL sql = selectByQueryInternal(this.getTableName(), entityClass);
    queryWHERE(sql, query, orderBy);
    if (logger.isDebugEnabled()) {
        logger.debug(sql.toString());
    }
    return sql.toString();
}
 
Example 53
Project: k-framework   File: BaseSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String selectPageByQuery(@Param("query") Object query, Page page) {
    String orderBy = null;
    if (null != page) {
        orderBy = page.getOrderBy();
    }
    SQL sql = selectByQueryInternal(this.getTableName(), entityClass);
    queryWHERE(sql, query, orderBy);
    String sqlStr = sql.toString();
    if (null != page) {
        long limit = page.getPageSize();
        long offset = limit * (page.getPageNo() - 1);
        sqlStr += " limit " + offset + "," + limit;
    }
    if (logger.isDebugEnabled()) {
        logger.debug(sqlStr);
    }
    return sqlStr;
}
 
Example 54
Project: k-framework   File: BaseSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String countByQuery(Map<String, Object> params) {
    SQL sql = countByQueryInternal(this.getTableName());
    queryWHERE(sql, params.get("query"), null);
    if (logger.isDebugEnabled()) {
        logger.debug(sql.toString());
    }
    return sql.toString();
}
 
Example 55
Project: k-framework   File: PaymentTransactionSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String updateToNeedCloseByOrderId(@Param("orderId") String orderId, @Param("tradeId") Integer tradeId) {
    return new SQL()
            .UPDATE(getTableName())
            .SET("need_close=1")
            .WHERE("order_id=#{orderId}")
            .WHERE("id!=#{tradeId}").toString();
}
 
Example 56
Project: k-framework   File: PaymentTransactionSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String updateToNotPay(@Param("orderId") String orderId, @Param("payMethod") String payMethod, @Param("time") Long time, @Param("status") String status) {
    return new SQL()
            .UPDATE(getTableName())
            .SET("status=#{status}")
            .SET("transaction_time=#{time}")
            .WHERE("order_id=#{orderId}")
            .WHERE("payment_method=#{payMethod}")
            .WHERE("status!='SUCCESS'")
            .WHERE("status!='CLOSED'").toString();
}
 
Example 57
Project: k-framework   File: PaymentTransactionSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String selectByOrderIdAndPayMethod(@Param("orderId") String orderId, @Param("payMethod") String payMethod) {
    return new SQL()
            .SELECT("*")
            .FROM(getTableName())
            .WHERE("order_id=#{orderId}")
            .WHERE("payment_method=#{payMethod}")
            .ORDER_BY("id DESC").toString();
}
 
Example 58
Project: k-framework   File: PaymentTransactionSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String selectNeedCloseTrades() {
    return new SQL()
            .SELECT("*")
            .FROM(getTableName())
            .WHERE("need_close=1")
            .WHERE("status!='CLOSED'")
            .WHERE("status!='SUCCESS'").toString();
}
 
Example 59
Project: k-framework   File: PaymentTransactionSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String selectExpiredTrades(@Param("orderIdList") List<String> orderIdList) {
    String orderIdStr = orderIdList.stream().collect(Collectors.joining(","));
    orderIdStr = "(" + orderIdStr + ")";
    return new SQL()
            .SELECT("*")
            .FROM(getTableName())
            .WHERE("order_id IN " + orderIdStr).toString();
}
 
Example 60
Project: k-framework   File: PaymentTransactionSqlBuilder.java   Source Code and License 5 votes vote down vote up
public String selectNeedQueryTrades(@Param("maxTime") Long maxTime, @Param("minTime") Long minTime, @Param("status") String status) {
    return new SQL()
            .SELECT("*")
            .FROM(getTableName())
            .WHERE("transaction_time <= #{maxTime}")
            .WHERE("expire_time >= #{minTime}")
            .WHERE("status = #{status}")
            .ORDER_BY("transaction_time ASC LIMIT 200").toString();
}