# 定义 SQL 命令

对于需要重复使用的SQL,可以进行定义,通过命名统一管理和调用SQL

src/main/resources目录下,有多种方式可以定义SQL,加载顺序如下:

  1. classpath*:META-INF/sqls.yml
  2. classpath*:META-INF/sqls/**/*.yml
  3. classpath:sqls.yml
  4. classpath:sqls/**/*.yml

SQL命名受文件相对sqls目录的路径及YAML格式内多层级key的影响,如第3、4点示例及最终SQL命名分别如下:

  • sqls.yml
test:
  example:
    sql1: select count(id) from user where name = ?

生成的命名为:test.example.sql1

  • sqls/test/example.yml
sql2: select count(id) from user where name = :name

生成的命名为: test/example/sql2

当不同配置文件有重复命名的SQL根据加载顺序,优先级从低到高

定义SQL命令后,可以用Dao直接执行:

Integer count = dao.createNamedQuery("test.example.sql1", Integer.class, "nameArg");

若需要SQL语句作额外的处理(如拼接等),可以注入SQLSourceSQLCommand获取,SQLCommand自身也可以执行数据访问:

sqls/test.yml

array:
  - select 1 from dual
  - select 2 from dual

indexedArray[0]: update user set name = :name where id = :id
indexedArray[1]: update user set loginName = :loginName where id = :id
import fly.orm.dao.sql.SQLCommand;
import fly.orm.dao.sql.SQLSource;
import org.springframework.beans.factory.annotation.Value;

...

@Autowired
protected SQLSource source;

// 通过 @Value 获取 SQLCommand
@Value("test.example.sql2")
protected SQLCommand sql2;

@Value("test.array")
protected SQLCommand[] sqls;

@Test
public void testSQLs() {
    // 通过 SQLSource 获取单条或数组类型 SQLCommand
    SQLCommand sql1Command = source.getSQLCommand("test.example.sql1");
    SQLCommand[] indexedSQLs = source.getSQLCommand("test.indexedArray");
    
    // 获取 SQL 语句
    String sql1 = sql1Command.getSQL();
    sql1 = source.getSQLText("test.example.sql1");
    
    // SQLCommand 执行查询等操作
    int count = sql1.queryForInt("nameArg");
    
    Map<String, Object> params = New.hashMap("name", "...", "loginName", "...", "id", "1");
    int[] result = new int[indexedSQLs.length];
   	for (int i = 0; i < indexedSQLs.length; i++) {
        result[i] = indexedSQL.update(params);
    }
}
顶部