Mybatisplus 自定義sql 使用條件構造器


Mybatisplus 自定義sql 使用條件構造器

兩種方式

注解方式

動態查找:
@Select("select ${ew.SqlSelect} from ${tableName} ${ew.customSqlSegment}") List<File> listFileByCondition(@Param("tableName") String tableName, @Param("ew") Wrapper wrapper); ew.SqlSelect:所需要查找的字段 tableName:使用的是那張表 ew.customSqlSegment:條件 用法:allFileMapper.listFileByCondition(tableName,Wrappers.query().select("*").in("relation_uuid", uuids)); 結果: select * from tablName where relation_uuid in () 動態修改: @Update("update ${tableName} set ${ew.sqlSet} ${ew.customSqlSegment}") int updateByCondition(@Param("tableName") String tableName, @Param("ew") Wrapper wrapper); ew.sqlSet:修改的字段 tableName:使用的是那張表 ew.customSqlSegment:條件 用法: mapper.updateByCondition(tableName, Wrappers.update().set("state", "初始狀態").in("id", ids)); 結果: update tableName set state = '初始狀態' where id in () 

xml方式

查找:
<select id="listFileByCondition" resultType="com.example.entity.File"> SELECT ${ew.SqlSelect} FROM ${tableName} ${ew.customSqlSegment} </select> 修改: <update id="listFileByCondition" > update ${tableName} ${ew.SqlSelect} ${ew.customSqlSegment} </update> 

查找帶分頁

xml用法:
Page<File> selectPage(Page page, @Param("tableName") String tableName, @Param("ew") Wrapper wrapper); <select id="selectPage" resultType="com.example.entity.File"> select * from ${tableName} ${ew.customSqlSegment} </select> 注解分頁:



/** * * @param rowBounds 分頁對象 直接傳入page即可 * @param wrapper 條件構造器 * @return */ List<User> selectUserWrapper(RowBounds rowBounds, @Param("ew") Wrapper<User> wrapper); 

UserMapper.xml加入對應的xml節點:

    <!-- 條件構造器形式 --> <select id="selectUserWrapper" resultType="user"> SELECT <include refid="Base_Column_List" /> FROM USER <where> ${ew.sqlSegment} </where> </select> 

測試類:

@Test public void testCustomSql() { User user = new User(); user.setCode("703"); user.setName("okong-condition"); user.insert(); EntityWrapper<User> qryWrapper = new EntityWrapper<>(); qryWrapper.eq(User.CODE, user.getCode()); Page<User> pageUser = new Page<>(); pageUser.setCurrent(1); pageUser.setSize(10); List<User> userlist = userDao.selectUserWrapper(pageUser, qryWrapper); System.out.println(userlist.get(0)); log.info("自定義sql結束"); }



自定義SQL語句

在一些需要多表關聯時,條件構造器和通用CURD都無法滿足時,還可以自行手寫sql語句進行擴展。注意:這都是mybatis的用法。

以下兩種方式都是改造UserDao接口。

注解形式

@Select("SELECT * FROM USER WHERE CODE = #{userCode}") List<User> selectUserCustomParamsByAnno(@Param("userCode")String userCode); 

xml形式

List<User> selectUserCustomParamsByXml(@Param("userCode")String userCode); 

同時,UserMapper.xml新增一個節點:

    <!-- 由於設置了別名:typeAliasesPackage=cn.lqdev.learning.mybatisplus.samples.biz.entity,所以resultType可以不寫全路徑了。 --> <select id="selectUserCustomParamsByXml" resultType="user"> SELECT <include refid="Base_Column_List"/> FROM USER WHERE CODE = #{userCode} </select>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM