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}));
}