使用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語句。