Mybatis-Plus使用總結


1、忽略數據庫字段注解

@TableField(exist = false)

2、Mybatis通過colliection屬性遞歸獲取菜單樹

public class Department extends BaseEntity {
    private Long id;
    private String name;
    private Integer parentId;
    private List<Department> children;
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tumake.user.mapper.DepartmentMapper">
    <cache-ref namespace="com.tumake.user.mapper.DepartmentMapper" />

    <resultMap id="deptTree" type="com.tumake.user.entity.Department">
        <id column="id" property="id" javaType="java.lang.Long" />
        <result column="name" property="name" javaType="java.lang.String" />
        <result column="parentId" property="parentId" javaType="java.lang.Integer" />
        <!--id作為參數遞歸調用getDeptTree,查詢子節點-->
        <collection property="children" column="id" select="selectDeptTreeByParentId" ofType="com.tumake.user.entity.Department"></collection>
    </resultMap>

    <!--根據父id獲取子節點-->
    <select id="selectDeptTreeByParentId" resultMap="deptTree">
        select id,`name`,parentId from Department where parentId=#{id}
    </select>
</mapper>
@CacheNamespace(implementation = MybatisPlusRedisCache.class, eviction = MybatisPlusRedisCache.class)
public interface DepartmentMapper extends BaseMapper<Department> {

    List<Department> selectDeptTreeByParentId(@Param("id") Integer parentId);
}

3、由於生成表采用的JPA,所以需要“關閉駝峰轉換”和“表名注解”
不然提示錯誤Cause: java.sql.SQLSyntaxErrorException: Table 'tumake.department' doesn't exist

mybatis-plus: #Mybatis-plus配置
  configuration: #原生MyBatis所支持的配置
    map-underscore-to-camel-case: false #不啟用駝峰命名規則

@TableName("Department")
@Entity
public class Department extends BaseEntity {

}

@Test
// 測試回滾數據,不做真實插入
@Transactional
void contextLoads(){
    Department department=new Department();
    department.setId(4L);
    department.setName("測試");
    department.setParentId(1);
    department.setStatus(true);
    departmentMapper.insert(department);
}

4、Mybatis-plus orderBy多字段排序,null值排最后

// 不能使用last拼接排序,有SQL注入風險
if (sortDirection.replace("ending", "").equals("desc")) {
    userQueryWrapper.orderByDesc(sortField);
    //userQueryWrapper.orderByAsc(sortField + " is NULL").orderByDesc(sortField);
} else {
    userQueryWrapper.orderByAsc(sortField + " is NULL," + sortField);
    //userQueryWrapper.orderBy(true, true, Arrays.asList(new String[]{sortField + " is NULL", sortField}));
}

 


免責聲明!

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



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