1、实体类
public class Teacher { @TableId private int id; private String name; @TableField(exist = false) private List<Student> students; }
2、编写xml
同样还是,我们先来个嵌套结果映射
嵌套结果:
// teacherMapper.xml <select id="getStudent" parameterType="int" resultMap="getStudentMap"> SELECT a.*,b.id as cid,b.name as cname,b.tid from teacher as a , student as b where b.tid = a.id and a.id =#{id}; </select> <resultMap id="getStudentMap" type="teacher"> <id column="id" property="id"></id> <result column="name" property="name"></result> <collection property="students" ofType="Student"> <id column="cid" property="id"></id> <result column="cname" property="name"></result> <result column="tid" property="tid" ></result> </collection> </resultMap>
嵌套查询:
// teacherMapper.xml <select id="getStudent2" parameterType="int" resultMap="getStudentMap2"> select * from teacher as a where a.id = #{id} </select> <resultMap id="getStudentMap2" type="teacher"> <id column="id" property="id"></id> <result column="name" property="name"></result> <collection property="students" column="id" ofType="Student" select="com.lll.mybatisplusdemo.mapper.StudentMapper.getStudentByTid"> </collection> </resultMap> // studentMapper.xml <select id="getStudentByTid" parameterType="int" resultType="student"> select * from student as a where a.tid = #{id} </select>
1.3 多对多
学生与课程是多对多的关系,与上面的一对多的操作方式是类似的
2、自定义sql如何做分页
mapper定义方法,方法传入page参数
public interface UserMapper{ IPage<User> selectPageVo(Page<User> page); }
userMapper.xml文件编写一个普通的返回结果是list的方法,mybatis会自动帮你做分页
<select id="selectPage" resultType="com.baomidou.cloud.entity.UserVo"> SELECT * FROM user </select>
3、自定义sql如何做排序
结论:使用order by,记住要使用'$',不能使用'#'
<select id="selectPage" resultType="com.baomidou.cloud.entity.UserVo"> SELECT * FROM user order by ${sortColumn} ${sortOrder} </select>
4、自定义sql中的#{}和${}的区别
1、传入的参数在SQL中显示不同
#传入的参数在SQL中显示为字符串(当成一个字符串),会对自动传入的数据加一个双引号。
例:使用以下SQL
select id,name,age from student where id =#{id}
当我们传递的参数id为 “1” 时,上述 sql 的解析为:
select id,name,age from student where id ="1"
$传入的参数在SqL中直接显示为传入的值
例:使用以下SQL
select id,name,age from student where id =${id}
当我们传递的参数id为 “1” 时,上述 sql 的解析为:
select id,name,age from student where id =1
2、#可以防止SQL注入的风险(语句的拼接);但$无法防止Sql注入。
3、$方式一般用于传入数据库对象,例如传入表名。
4、大多数情况下还是经常使用#,一般能用#的就别用$
;但有些情况下必须使用$
,例:MyBatis排序时使用order by 动态参数时需要注意,用$而不是#。
到此这篇关于Mybatis自定义SQL的关系映射、分页、排序的文章就介绍到这了,更多相关Mybatis自定义SQL的关系映射内容请搜索
更多SQL内容来自木庄网络博客