[Java] 使用@SelectProvider注解实现多表关联查询(全注解,不使用不配置xml)

使用mybatisplus可以很容易实现不写SQL语句的CURD。也可以通过配置XML或注解实现多表关联查询,但这就得写相应的SQL语句了。我更喜欢全程注解的方式,必竟写着java忽然又跑去配置xml有点跳跃,既使是有相应的插件方便跳转,但还是不如写在一个文件中直接,后期也方便检视代码。

这里主要是使用 @SelectProvider 实现我们想要的功能。

@SelectProvider是声明在Mapper中方法上的。

参数 type 用来指定SQL生成器类, method 用来指定生成SQL对应的函数名称。

 

示例代码:

import xxx.entity.AccountEntity
import org.apache.ibatis.annotations.Mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param import org.apache.ibatis.annotations.SelectProvider import org.springframework.stereotype.Component @Component @Mapper interface AccountMapper : BaseMapper<AccountEntity> { /** * 获取账号列表, 注意,这里我们用的是 ArrayList,不能用 List, 因为是个虚类无法实例化 */ @SelectProvider(type = AccountSQLProvider::class, method = "getAccountList") fun <E : ArrayList<AccountEntity>> getAccountList(@Param("id") idArray: String): E /** * sql拼接处理 */ class AccountSQLProvider { fun getAccountList(id: String):String { return """ SELECT a.user_id, a.shop_id, b.name FROM account_user a LEFT Join shop b ON a.shop_id_id = b.id WHERE a.user_id in $id """.trimIndent() } } }

 

Mapper建议用Kotlin来写,可以更方便的写sql语句。

 

posted @ 2020-08-27 16:11  我爱我家喵喵  阅读(2650)  评论(0编辑  收藏  举报