cn.vonce.sql.helper.SqlHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of vonce-sqlbean-core Show documentation
Show all versions of vonce-sqlbean-core Show documentation
This is the core project of Sqlbean.
The newest version!
package cn.vonce.sql.helper;
import cn.vonce.sql.annotation.*;
import cn.vonce.sql.define.SqlEnum;
import cn.vonce.sql.define.SqlFun;
import cn.vonce.sql.uitls.ReflectUtil;
import cn.vonce.sql.uitls.StringUtil;
import cn.vonce.sql.bean.*;
import cn.vonce.sql.constant.SqlConstant;
import cn.vonce.sql.enumerate.*;
import cn.vonce.sql.exception.SqlBeanException;
import cn.vonce.sql.uitls.SqlBeanUtil;
import java.lang.reflect.Field;
import java.util.*;
/**
* SQL 语句助手
*
* @author jovi
* @version 1.0
* @email [email protected]
* @date 2017年6月2日下午5:41:59
*/
public class SqlHelper {
/**
* 生成select sql语句
*
* @param select
* @return
*/
public static String buildSelectSql(Select select) {
SqlBeanUtil.check(select);
StringBuffer sqlSb = new StringBuffer();
Integer[] pageParam = null;
String orderSql = orderBySql(select);
//SQLServer2008 分页处理
if (select.getSqlBeanDB().getDbType() == DbType.SQLServer) {
if (SqlBeanUtil.isUsePage(select)) {
pageParam = pageParam(select);
sqlSb.append(SqlConstant.SELECT);
sqlSb.append(SqlConstant.ALL);
sqlSb.append(SqlConstant.FROM);
sqlSb.append(SqlConstant.BEGIN_BRACKET);
}
}
//标准Sql
sqlSb.append(select.isDistinct() ? SqlConstant.SELECT_DISTINCT : SqlConstant.SELECT);
//SqlServer 分页处理
if (select.getSqlBeanDB().getDbType() == DbType.SQLServer) {
if (SqlBeanUtil.isUsePage(select)) {
sqlSb.append(SqlConstant.TOP);
sqlSb.append(pageParam[0]);
sqlSb.append(SqlConstant.ROW_NUMBER + SqlConstant.OVER + SqlConstant.BEGIN_BRACKET + orderSql + SqlConstant.END_BRACKET + SqlConstant.ROWNUM + SqlConstant.COMMA);
}
}
//标准Sql
if (select.isCount() && !select.isDistinct()) {
sqlSb.append(SqlConstant.COUNT + SqlConstant.BEGIN_BRACKET + SqlConstant.ALL + SqlConstant.END_BRACKET);
} else {
sqlSb.append(column(select));
}
sqlSb.append(SqlConstant.FROM);
sqlSb.append(SqlBeanUtil.fromFullName(select.getTable().getSchema(), select.getTable().getName(), select.getTable().getAlias(), select));
sqlSb.append(joinSql(select));
sqlSb.append(whereSql(select, null));
String groupBySql = groupBySql(select);
sqlSb.append(groupBySql);
sqlSb.append(havingSql(select));
if (!select.isCount()) {
sqlSb.append(orderSql);
}
//SQLServer2008 分页处理
if (select.getSqlBeanDB().getDbType() == DbType.SQLServer) {
// 主要逻辑 结束
if (SqlBeanUtil.isUsePage(select)) {
sqlSb.append(SqlConstant.END_BRACKET);
sqlSb.append(SqlConstant.T);
sqlSb.append(SqlConstant.WHERE);
sqlSb.append(SqlConstant.T + SqlConstant.POINT + SqlConstant.ROWNUM);
sqlSb.append(SqlConstant.GREATER_THAN);
sqlSb.append(pageParam[1]);
}
}
//标准Sql 如果是克隆的select则为分页时的count
if ((select.isCount() && select.isDistinct()) || (select.isCount() && StringUtil.isNotEmpty(groupBySql))) {
sqlSb.insert(0, SqlConstant.SELECT + SqlConstant.COUNT + SqlConstant.BEGIN_BRACKET + SqlConstant.ALL + SqlConstant.END_BRACKET + SqlConstant.FROM + SqlConstant.BEGIN_BRACKET);
sqlSb.append(SqlConstant.END_BRACKET + SqlConstant.AS + SqlConstant.T);
}
//MySQL,MariaDB,H2 分页处理
if (!select.isCount() && (select.getSqlBeanDB().getDbType() == DbType.MySQL || select.getSqlBeanDB().getDbType() == DbType.MariaDB || select.getSqlBeanDB().getDbType() == DbType.H2)) {
mysqlPageDispose(select, sqlSb);
}
//Postgresql,SQLite,Hsql 分页处理
else if (!select.isCount() && (select.getSqlBeanDB().getDbType() == DbType.Postgresql || select.getSqlBeanDB().getDbType() == DbType.SQLite || select.getSqlBeanDB().getDbType() == DbType.Hsql)) {
PostgresqlPageDispose(select, sqlSb);
}
//Oracle 分页处理
else if (!select.isCount() && select.getSqlBeanDB().getDbType() == DbType.Oracle) {
oraclePageDispose(select, sqlSb);
}
//DB2 分页处理
else if (!select.isCount() && select.getSqlBeanDB().getDbType() == DbType.DB2) {
db2PageDispose(select, sqlSb);
}
//Derby 分页处理
else if (!select.isCount() && select.getSqlBeanDB().getDbType() == DbType.Derby) {
derbyPageDispose(select, sqlSb);
}
return sqlSb.toString();
}
/**
* 生成update sql语句
*
* @param update
* @return
* @throws SqlBeanException
*/
public static String buildUpdateSql(Update update) {
SqlBeanUtil.check(update);
StringBuffer sqlSb = new StringBuffer();
sqlSb.append(SqlConstant.UPDATE);
if (update.getSqlBeanDB().getDbType() == DbType.H2 || update.getSqlBeanDB().getDbType() == DbType.Oracle) {
sqlSb.append(SqlBeanUtil.fromFullName(update.getTable().getSchema(), update.getTable().getName(), update.getTable().getAlias(), update));
} else {
sqlSb.append(SqlBeanUtil.getTableName(update.getTable(), update));
}
sqlSb.append(SqlConstant.SET);
sqlSb.append(setSql(update));
sqlSb.append(whereSql(update, update.getBean()));
return sqlSb.toString();
}
/**
* 生成insert sql语句
*
* @param insert
* @return
*/
@SuppressWarnings("unchecked")
public static String buildInsertSql(Insert insert) {
SqlBeanUtil.check(insert);
String sql = null;
try {
sql = fieldAndValuesSql(insert);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return sql;
}
/**
* 生成delete sql语句
*
* @param delete
* @return
*/
public static String buildDeleteSql(Delete delete) {
SqlBeanUtil.check(delete);
StringBuffer sqlSb = new StringBuffer();
sqlSb.append(SqlConstant.DELETE_FROM);
if (delete.getSqlBeanDB().getDbType() == DbType.H2 || delete.getSqlBeanDB().getDbType() == DbType.Oracle) {
sqlSb.append(SqlBeanUtil.fromFullName(delete.getTable().getSchema(), delete.getTable().getName(), delete.getTable().getAlias(), delete));
} else {
sqlSb.append(SqlBeanUtil.getTableName(delete.getTable(), delete));
}
sqlSb.append(whereSql(delete, null));
return sqlSb.toString();
}
/**
* 生成create sql语句
*
* @param create
* @return
*/
public static String buildCreateSql(Create create) {
SqlBeanUtil.check(create);
StringBuffer sqlSb = new StringBuffer();
sqlSb.append(SqlConstant.CREATE_TABLE);
sqlSb.append(SqlBeanUtil.getTableName(create.getTable(), create));
sqlSb.append(SqlConstant.BEGIN_BRACKET);
List fieldList = SqlBeanUtil.getBeanAllField(create.getBeanClass());
SqlTable sqlTable = SqlBeanUtil.getSqlTable(create.getBeanClass());
DbType dbType = create.getSqlBeanDB().getDbType();
for (int i = 0; i < fieldList.size(); i++) {
if (SqlBeanUtil.isIgnore(fieldList.get(i))) {
continue;
}
SqlColumn sqlColumn = fieldList.get(i).getAnnotation(SqlColumn.class);
sqlSb.append(SqlBeanUtil.addColumn(create, SqlBeanUtil.buildColumnInfo(create.getSqlBeanDB(), fieldList.get(i), sqlTable, sqlColumn), null));
sqlSb.append(SqlConstant.COMMA);
}
Field idField = SqlBeanUtil.getIdField(create.getBeanClass());
//主键
if (idField != null) {
String idFieldName = SqlBeanUtil.getTableFieldName(create, idField, sqlTable);
sqlSb.append(SqlConstant.PRIMARY_KEY);
sqlSb.append(SqlConstant.BEGIN_BRACKET);
sqlSb.append(idFieldName);
sqlSb.append(SqlConstant.END_BRACKET);
} else {
sqlSb.deleteCharAt(sqlSb.length() - SqlConstant.COMMA.length());
}
sqlSb.append(SqlConstant.END_BRACKET);
//如果是Mysql或MariaDB可直接保存备注
if (sqlTable != null && StringUtil.isNotBlank(sqlTable.remarks()) && (dbType == DbType.MySQL || dbType == DbType.MariaDB)) {
sqlSb.append(SqlConstant.SPACES);
sqlSb.append(SqlConstant.COMMENT);
sqlSb.append(SqlConstant.EQUAL_TO);
sqlSb.append(SqlConstant.SINGLE_QUOTATION_MARK);
sqlSb.append(sqlTable.remarks());
sqlSb.append(SqlConstant.SINGLE_QUOTATION_MARK);
}
return sqlSb.toString();
}
/**
* 生成backup sql语句
*
* @param backup
* @return
*/
public static String buildBackup(Backup backup) {
SqlBeanUtil.check(backup);
String targetSchema = backup.getTargetSchema();
if (StringUtil.isEmpty(targetSchema)) {
targetSchema = backup.getTable().getSchema();
}
StringBuffer backupSql = new StringBuffer();
//非SQLServer、Postgresql数据库则使用:create table A as select * from B
if (DbType.SQLServer != backup.getSqlBeanDB().getDbType() && DbType.Postgresql != backup.getSqlBeanDB().getDbType()) {
backupSql.append(SqlConstant.CREATE_TABLE);
backupSql.append(SqlBeanUtil.getTableName(backup, targetSchema, backup.getTargetTableName()));
backupSql.append(SqlConstant.SPACES);
backupSql.append(SqlConstant.AS);
}
backupSql.append(SqlConstant.SELECT);
if (backup.getColumns() != null && backup.getColumns().length > 0) {
for (Column column : backup.getColumns()) {
backupSql.append(column.getName());
backupSql.append(SqlConstant.COMMA);
}
backupSql.delete(backupSql.length() - SqlConstant.COMMA.length(), backupSql.length());
} else {
backupSql.append(SqlConstant.ALL);
}
//如果是SQLServer、Postgresql数据库则需要拼接INTO:select * into A from B
if (DbType.SQLServer == backup.getSqlBeanDB().getDbType() || DbType.Postgresql == backup.getSqlBeanDB().getDbType()) {
backupSql.append(SqlConstant.INTO);
backupSql.append(SqlBeanUtil.getTableName(backup, targetSchema, backup.getTargetTableName()));
}
backupSql.append(SqlConstant.FROM);
backupSql.append(SqlBeanUtil.getTableName(backup.getTable(), backup));
//如果是Derby数据库,仅支持创建表结构,其他数据库则可通过条件备份数据和是否需要数据
if (DbType.Derby == backup.getSqlBeanDB().getDbType()) {
backupSql.append(" WITH NO DATA");
} else {
backupSql.append(whereSql(backup, null));
}
return backupSql.toString();
}
/**
* 生成copy sql语句
*
* @param copy
* @return
*/
public static String buildCopy(Copy copy) {
SqlBeanUtil.check(copy);
String targetSchema = copy.getTargetSchema();
if (StringUtil.isEmpty(targetSchema)) {
targetSchema = copy.getTable().getSchema();
}
StringBuffer copySql = new StringBuffer();
StringBuffer columnSql = new StringBuffer();
copySql.append(SqlConstant.INSERT_INTO);
copySql.append(SqlBeanUtil.getTableName(copy.getTable(), copy));
if (copy.getColumns() != null && copy.getColumns().length > 0) {
for (Column column : copy.getColumns()) {
columnSql.append(column.getName());
columnSql.append(SqlConstant.COMMA);
}
columnSql.delete(columnSql.length() - SqlConstant.COMMA.length(), columnSql.length());
copySql.append(SqlConstant.SPACES);
copySql.append(SqlConstant.BEGIN_BRACKET);
copySql.append(columnSql);
copySql.append(SqlConstant.END_BRACKET);
}
copySql.append(SqlConstant.SPACES);
copySql.append(SqlConstant.SELECT);
if (copy.getTargetColumns() != null && copy.getTargetColumns().length > 0) {
StringBuffer targetColumnSql = new StringBuffer();
for (Column column : copy.getTargetColumns()) {
targetColumnSql.append(column.getName());
targetColumnSql.append(SqlConstant.COMMA);
}
targetColumnSql.delete(targetColumnSql.length() - SqlConstant.COMMA.length(), targetColumnSql.length());
copySql.append(targetColumnSql);
} else if (copy.getTargetColumns() != null && copy.getTargetColumns().length > 0) {
copySql.append(columnSql);
} else {
copySql.append(SqlConstant.ALL);
}
copySql.append(SqlConstant.FROM);
copySql.append(SqlBeanUtil.getTableName(copy, targetSchema, copy.getTargetTableName()));
copySql.append(whereSql(copy, null));
return copySql.toString();
}
/**
* 生成drop sql语句
*
* @param drop
* @return
*/
public static String buildDrop(Drop drop) {
StringBuffer dropSql = new StringBuffer();
String tableName = SqlBeanUtil.getTableName(drop.getTable(), drop);
if (drop.getSqlBeanDB().getDbType() == DbType.MySQL || drop.getSqlBeanDB().getDbType() == DbType.MariaDB || drop.getSqlBeanDB().getDbType() == DbType.Postgresql || drop.getSqlBeanDB().getDbType() == DbType.H2) {
dropSql.append("DROP TABLE IF EXISTS ");
dropSql.append(tableName);
} else if (drop.getSqlBeanDB().getDbType() == DbType.MySQL) {
dropSql.append("IF OBJECT_ID(N'" + tableName + "', N'U') IS NOT NULL ");
dropSql.append("DROP TABLE " + tableName + " ");
} else {
dropSql.append("DROP TABLE ");
dropSql.append(tableName);
}
return dropSql.toString();
}
/**
* 返回column语句
*
* @param select
* @return
*/
private static String column(Select select) {
StringBuffer columnSql = new StringBuffer();
if (select.getColumnList() != null && select.getColumnList().size() != 0) {
for (int i = 0; i < select.getColumnList().size(); i++) {
Column column = select.getColumnList().get(i);
Column newColumn = SqlBeanUtil.copy(column);
if (column instanceof SqlFun) {
newColumn.setName(SqlBeanUtil.getSqlFunction(select, (SqlFun) column));
}
String escape = SqlBeanUtil.getEscape(select);
//存在列别名
boolean existAlias = StringUtil.isNotEmpty(newColumn.getAlias());
if (existAlias) {
columnSql.append(SqlConstant.BEGIN_BRACKET);
}
//存在表别名
if (StringUtil.isNotEmpty(newColumn.getTableAlias())) {
columnSql.append(SqlBeanUtil.getTableFieldFullName(select, newColumn));
} else {
columnSql.append(newColumn.getName(SqlBeanUtil.isToUpperCase(select)));
}
if (existAlias) {
columnSql.append(SqlConstant.END_BRACKET);
columnSql.append(SqlConstant.AS);
columnSql.append(escape);
columnSql.append(newColumn.getAlias());
columnSql.append(escape);
}
columnSql.append(SqlConstant.COMMA);
}
columnSql.deleteCharAt(columnSql.length() - SqlConstant.COMMA.length());
}
return columnSql.toString();
}
/**
* 返回innerJoin语句
*
* @param select
* @return
*/
private static String joinSql(Select select) {
StringBuffer joinSql = new StringBuffer();
if (select != null && select.getJoin().size() != 0) {
for (int i = 0; i < select.getJoin().size(); i++) {
Join join = select.getJoin().get(i);
switch (join.getJoinType()) {
case INNER_JOIN:
joinSql.append(SqlConstant.INNER_JOIN);
break;
case LEFT_JOIN:
joinSql.append(SqlConstant.LEFT_JOIN);
break;
case RIGHT_JOIN:
joinSql.append(SqlConstant.RIGHT_JOIN);
break;
case FULL_JOIN:
joinSql.append(SqlConstant.FULL_JOIN);
break;
}
String schema = join.getSchema();
String tableName = join.getTableName();
String tableAlias = join.getTableAlias();
joinSql.append(SqlBeanUtil.fromFullName(schema, tableName, tableAlias, select));
joinSql.append(SqlConstant.ON);
if (join.on() != null && join.on().getDataList().size() > 0) {
joinSql.append(simpleConditionHandle(select, join.on().getDataList()));
} else {
//过时暂时兼容
String tableKeyword = SqlBeanUtil.getTableFieldFullName(select, tableAlias, join.getTableKeyword());
String mainKeyword = SqlBeanUtil.getTableFieldFullName(select, select.getTable().getAlias(), join.getMainKeyword());
if (StringUtil.isNotEmpty(join.getOn())) {
joinSql.append(join.getOn());
} else {
joinSql.append(tableKeyword);
joinSql.append(SqlConstant.EQUAL_TO);
joinSql.append(mainKeyword);
}
if (i < select.getJoin().size() - 1) {
joinSql.append(SqlConstant.SPACES);
}
}
}
}
return joinSql.toString();
}
/**
* 返回field及values语句
*
* @param insert
* @return
* @throws IllegalArgumentException
*/
private static String fieldAndValuesSql(Insert insert) throws IllegalArgumentException {
String tableName = SqlBeanUtil.getTableName(insert.getTable(), insert);
StringBuffer fieldSql = new StringBuffer();
StringBuffer valueSql = new StringBuffer();
StringBuffer fieldAndValuesSql = new StringBuffer();
List valueSqlList = new ArrayList<>();
List objectList = insert.getBean();
SqlTable sqlTable = SqlBeanUtil.getSqlTable(insert.getBeanClass());
//获取bean的全部字段
List fieldList = SqlBeanUtil.getBeanAllField(insert.getBeanClass());
if (insert.getSqlBeanDB().getDbType() == DbType.Oracle) {
if (objectList != null && objectList.size() > 1) {
fieldAndValuesSql.append(SqlConstant.INSERT_ALL_INTO);
} else {
fieldAndValuesSql.append(SqlConstant.INSERT_INTO);
}
} else {
fieldAndValuesSql.append(SqlConstant.INSERT_INTO);
}
//如果是Bean模式
if (objectList != null && objectList.size() > 0) {
for (int i = 0; i < objectList.size(); i++) {
//每次必须清空
valueSql.delete(0, valueSql.length());
//只有在循环第一遍的时候才会处理
if (i == 0) {
fieldSql.append(SqlConstant.BEGIN_BRACKET);
}
valueSql.append(SqlConstant.BEGIN_BRACKET);
int existId = 0;
for (Field field : fieldList) {
if (SqlBeanUtil.isIgnore(field)) {
continue;
}
SqlId sqlId = field.getAnnotation(SqlId.class);
SqlDefaultValue sqlDefaultValue = field.getAnnotation(SqlDefaultValue.class);
if (sqlId != null) {
existId++;
}
if (existId > 1) {
throw new SqlBeanException("请正确的标识id字段,id字段只能标识一个,但我们在'" + field.getDeclaringClass().getName() + "'此实体类或其父类找到了不止一处");
}
//只有在循环第一遍的时候才会处理
if (i == 0) {
String tableFieldName = SqlBeanUtil.getTableFieldName(insert, field, sqlTable);
//如果此字段非id字段 或者 此字段为id字段但是不是自增的id则生成该字段的insert语句
if (sqlId == null || (sqlId != null && sqlId.type() != IdType.AUTO)) {
fieldSql.append(tableFieldName);
fieldSql.append(SqlConstant.COMMA);
}
}
if (sqlId != null && sqlId.type() == IdType.AUTO) {
continue;
}
Object value = ReflectUtil.instance().get(objectList.get(i).getClass(), objectList.get(i), field.getName());
//如果此字段为id且需要生成唯一id
if (sqlId != null && sqlId.type() != IdType.AUTO && sqlId.type() != IdType.NORMAL) {
if (StringUtil.isEmpty(value)) {
value = insert.getSqlBeanDB().getSqlBeanConfig().getUniqueIdProcessor().uniqueId(sqlId.type());
ReflectUtil.instance().set(objectList.get(i).getClass(), objectList.get(i), field.getName(), value);
}
valueSql.append(SqlBeanUtil.getSqlValue(insert, value));
} else if (field.isAnnotationPresent(SqlLogically.class) && value == null) {
//如果标识逻辑删除的字段为空则自动填充
Object defaultValue = SqlBeanUtil.assignInitialValue(SqlBeanUtil.getEntityClassFieldType(field));
valueSql.append(SqlBeanUtil.getSqlValue(insert, defaultValue));
ReflectUtil.instance().set(objectList.get(i).getClass(), objectList.get(i), field.getName(), field.getType() == Boolean.class || field.getType() == boolean.class ? false : 0);
} else if (value == null && sqlDefaultValue != null && (sqlDefaultValue.with() == FillWith.INSERT || sqlDefaultValue.with() == FillWith.TOGETHER)) {
Object defaultValue = SqlBeanUtil.assignInitialValue(SqlBeanUtil.getEntityClassFieldType(field));
valueSql.append(SqlBeanUtil.getSqlValue(insert, defaultValue));
if (SqlEnum.class.isAssignableFrom(field.getType())) {
ReflectUtil.instance().set(objectList.get(i).getClass(), objectList.get(i), field.getName(), SqlBeanUtil.matchEnum(field, defaultValue));
} else {
ReflectUtil.instance().set(objectList.get(i).getClass(), objectList.get(i), field.getName(), defaultValue);
}
} else {
valueSql.append(SqlBeanUtil.getSqlValue(insert, ReflectUtil.instance().get(objectList.get(i).getClass(), objectList.get(i), field.getName())));
}
valueSql.append(SqlConstant.COMMA);
}
valueSql.deleteCharAt(valueSql.length() - SqlConstant.COMMA.length());
valueSql.append(SqlConstant.END_BRACKET);
valueSqlList.add(valueSql.toString());
//只有在循环第一遍的时候才会处理
if (i == 0) {
fieldSql.deleteCharAt(fieldSql.length() - SqlConstant.COMMA.length());
fieldSql.append(SqlConstant.END_BRACKET);
}
}
} else {
List columnList = insert.getColumnList();
List> valuesList = insert.getValuesList();
if (columnList == null || columnList.size() == 0) {
throw new SqlBeanException("如果你不使用Bean对象的方式用作Insert,请指定Insert的字段");
}
if (valuesList == null || valuesList.size() == 0) {
throw new SqlBeanException("请指定Insert的字段对应的值");
}
fieldSql.append(SqlConstant.BEGIN_BRACKET);
for (int i = 0; i < columnList.size(); i++) {
fieldSql.append(SqlBeanUtil.getTableFieldName(insert, columnList.get(i).getName()));
if (i < columnList.size() - 1) {
fieldSql.append(SqlConstant.COMMA);
}
}
fieldSql.append(SqlConstant.END_BRACKET);
for (int i = 0; i < valuesList.size(); i++) {
//每次必须清空
valueSql.delete(0, valueSql.length());
List
© 2015 - 2024 Weber Informatics LLC | Privacy Policy