ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## @SubQuery 注解@SubQuery 要求方法mapper方法返回LambdaQuery,不同于普通的LambdaQuery,此类实际上是其子类LambdaSubQuery,支持把子查询作为”表名“,以源码中的SubQueryCommonTest为例子说明 > 此想法和代码来源于 https://gitee.com/xiandafu/beetlsql/issues/I1WRHZ ```java @SqlResource("lambda") public interface AnyMapper extends BaseMapper<User>{ /* 构造一个公共的子查询Lambda,由lambda#allUserInDepartment构成 */ @SubQuery public LambdaQuery<User> allUserInDepartment(Integer deptId); } ``` 如上allUserInDepartment方法返回一个LambdaQuery<User>,lambda#allUserInDepartment提供了子查询语句,其内容如下 ```sql allUserInDepartment === select * from sys_user where department_id=#{deptId} ``` 因此,BeetlSQL实际Lambda查询的时候,构成的sql其实如下 ```java select * from (select * from sys_user where department_id=xxx) where ..... ``` 这样的好处是可以把复杂的查询转成简单的Lambda查询 ```java AnyMapper anyMapper = sqlManager.getMapper(AnyMapper.class); LambdaQuery<User> lambdaQuery = anyMapper.allUserInDepartment(1); List<User> newList = lambdaQuery.andEq(User::getAge,42).select(); Assert.assertEquals(0,newList.size()); ``` 如上查询,对应的sql实际上是 ```text ┏━━━━━ Debug [sql.SELECT * FROM ( select * from sys_user where d...] ━━━ ┣ SQL: SELECT * FROM ( select * from sys_user where department_id=? ) _t WHERE age = ? ┣ 参数: [1, 42] ┣ 位置: org.beetl.sql.core.mapper.SubQueryCommonTest.commonLambda(SubQueryCommonTest.java:32) ┣ 时间: 1ms ┣ 结果: [0] ┗━━━━━ Debug [sql.SELECT * FROM ( select * from sys_user where d...] ━━━ ```