1. 程式人生 > 實用技巧 >[Java] 使用@SelectProvider註解實現多表關聯查詢(全註解,不使用不配置xml)

[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語句。