当前位置: 首页> 教育> 就业 > MyBatis3(动态SQL 常用的动态SQL 元素 映射器注解 基本注解 结果映射注解)

MyBatis3(动态SQL 常用的动态SQL 元素 映射器注解 基本注解 结果映射注解)

时间:2025/8/29 11:47:52来源:https://blog.csdn.net/qq_52897007/article/details/140143458 浏览次数:0次

目录

一、动态SQL

常用的动态SQL 元素 

二、if元素

三、choose 、when 、otherwise 元素

四、trim 、where 、set 元素

trim(不常用)

where

 set

五、foreach 元素

六、bind 元素 

#{} ${} 区别

示例完整代码

七、映射器注解

八、基本注解

@Insert 新增

主键回填 

主键自增 

@Delete 删除

@Update 更新

@Selete 查询 

传递多个参数的方式: 

九、结果映射注解

@Results 结果映射

一对一映射 

一对多映射

示例完整代码 


一、动态SQL

  • 定义:根据不同条件拼接SQL 语句,实现对数据库更准确的操作;
  • 实现:映射器配置文件或者注解。

常用的动态SQL 元素 

  • if 元素:判断语句,单条件分 支判断.
  • choose 元素 (when,otherwise): 多条件分支判断,等 同于java 的 switch.
  • trim (where,set): 辅助元素,用于处理一些 SQL 拼接的问题.
  • foreach 元素 :循环语句,在in 语 句等列举条件常用
  • bind 元素 :自定义上下文变量, 传递参数.

二、if元素

语法: 

语法
< if  test =”条件”> 满足条件的语句 </ if>

注意:拼接SQL 语句的时候注意AND 和逗号。

实现:

Student.java 下面所需要的bean同这个一样

public class Student {//属性 对应 数据库中的字段 ---名字一致 类型一致//长像相似就行private int sid;private String sname;private Date birthday;private String ssex;private int classid;//1:1外部属性private Banji bj;get/set 方法 构造方法省略。。。
}

StudentMapper.java

// 查询public List<Student> findStudent(Student s);

StudentMapper.xml

<!-- OGNL 对象图导航语言 属性 运算符 逻辑 字符串增强 == --><!-- test中的表达式成立 就把if标签里面的字串拼接 --><select id="findStudent" resultType="student" parameterType="student">select * from student where 1=1<if test="ssex != null">and ssex=#{ssex}</if><if test="classid != 0">and classid=#{classid}</if></select>

测试:

    SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();s.setClassid(1);
//		s.setSsex("男");
//		s.setSname("zkt");
//		s.setSid(1);List<Student> slist = stuMapper.findStudent(s);slist.forEach(System.out::println);DaoUtil.closeResource(sqlSession);

三、choose 、when 、otherwise 元素

为什么用choose 元素 

  • 01.场景1 当新闻编号不为空,则只用新闻编号作为查询条件;
  • 02.场景2 当新闻编号为空,而新闻标题不为空,则用新闻 标题作为条件进行模糊查询
  • 03.场景3 当新闻编号和新闻标题都为空,则要求新闻作者 不能为空

语法:

语法:
<choose>  
<when test=“条件”>满足条件的语句</ when><otherwise> 满足其他条件的语句<otherwise></choose>

choose 类似于switch 只要满足条件只走一个

注意:拼接SQL 语句的时候注意AND 和逗号。 

实现:

StudentMapper.java

public List<Student> findStudentChoose(Student s);

StudentMapper.xml

<select id="findStudentChoose" resultType="student" parameterType="student">select * from student <where><choose><when test="sname != null">and sname = #{sname}</when><when test="ssex != null">and ssex = #{ssex}</when><otherwise>and sid > 10 </otherwise></choose></where></select>

测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();s.setClassid(1);
//		s.setSsex("男");
//		s.setSname("zkt");
//		s.setSid(1);List<Student> slist = stuMapper.findStudentChoose(s);slist.forEach(System.out::println);DaoUtil.closeResource(sqlSession);

四、trim 、where 、set 元素

trim(不常用)

语法:

语法:
<trim   prefix = “”suffixOverrides = “” prefixOverrides=“”suffix=“”></trim>prefix 需要拼接的子句,可以是where,or 或者set;suffixOvrrides 忽略通过管道分隔的文本序列后缀。一般不与prefixOvrrides 同时使用prefixOvrrides 忽略通过管道分隔的文本序列前缀。一般不与suffixOvrrides 同时使用

实现:

StudentMapper.java

public List<Student> findStudentTrim(Student s);

StudentMapper.xml

<!-- trim 万能标签prefix 开始添加一个什么prefixOverrides 开始去掉一个什么suffix 结束添加一个什么suffixOverrides 结束去掉一个什么--><select id="findStudentTrim" parameterType="student" resultType="student">select * from student <trim prefix=" where " prefixOverrides="and" ><if test="ssex != null"> and ssex= #{ssex}</if><if test="classid != 0"> and classid = #{classid}</if></trim></select>

测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();s.setClassid(1);s.setSsex("男");
//		s.setSname("zkt");
//		s.setSid(1);List<Student> slist = stuMapper.findStudentTrim(s);slist.forEach(System.out::println);DaoUtil.closeResource(sqlSession);


实现:

StudentMapper.java

public int addStudent(Student s);

StudentMapper.xml

 <insert id="addStudent" parameterType="student">insert into  student <trim prefix="(" suffix=")" suffixOverrides=","><if test="sid != 0"> sid,</if><if test="sname != null"> sname,</if><if test="birthday != null"> birthday,</if><if test="ssex != null"> ssex,</if><if test="classid != 0"> classid,</if></trim>values<trim prefix="(" suffix=")" suffixOverrides=","><if test="sid != 0"> #{sid},</if><if test="sname != null"> #{sname},</if><if test="birthday != null"> #{birthday},</if><if test="ssex != null"> #{ssex},</if><if test="classid != 0"> #{classid},</if></trim></insert><update id="updateStudentTrim" parameterType="student">update student<trim prefix="set " suffixOverrides=","><if test="sname != null">sname = #{sname},</if><if test="birthday != null">birthday = #{birthday},</if><if test="ssex != null">ssex = #{ssex},</if><if test="classid != 0">classid = #{classid},</if></trim>where sid = #{sid}</update>

测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();s.setClassid(1);s.setSsex("男");s.setSname("zkt");s.setSid(1);//		int ret = stuMapper.updateStudentSet(s);int ret = stuMapper.addStudent(s);if (ret > 0) {sqlSession.commit();System.out.println("成了");} else {sqlSession.rollback();System.out.println("凉了");}DaoUtil.closeResource(sqlSession);

where

语法:

语法:
<where><if  test =”条件”> 满足条件的语句 </if></where>

说明:where 元素只会在至少有一个子元素的 条件返回SQL 子句的情况下才去插入 “WHERE”子句。而且,若语句的开头为 “AND”或“OR”,where 元素也会将它们去除。

实现:

StudentMapper.java

	public List<Student> findStudentWhere(Student s);

StudentMapper.xml

<!-- where标签 1.添加一个where关键词 2. 去掉where后的第一个and 3.当没where标签中没有任何成立的字串时 什么也不添加 --><select id="findStudentWhere" resultType="student" parameterType="student">select * from student<where><if test="ssex != null">and ssex=#{ssex}</if><if test="classid != 0">and classid=#{classid}</if></where></select>

测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();s.setClassid(1);s.setSsex("男");
//		s.setSname("zkt");
//		s.setSid(1);List<Student> slist = stuMapper.findStudentWhere(s);slist.forEach(System.out::println);DaoUtil.closeResource(sqlSession);

 set

语法:

语法:
<set><if  test =”条件”> 满足条件的语句 </if></set>

说明:set 标签元素主要是用在更新操作的时候, 它的主要功能和where 标签元素其实是差不 多的,主要是在包含的语句前输出一个set, 然后如果包含的语句是以逗号结束的话将会 把该逗号忽略,如果set 包含的内容为空的 话则会出错。有了set 元素就可以动态的更 新那些修改了的字段。 

实现:

StudentMapper.java

public int updateStudentSet(Student s);

StudentMapper.xml

	<update id="updateStudentSet" parameterType="student">update student<set><if test="sname != null">sname = #{sname},</if><if test="birthday != null">birthday = #{birthday},</if><if test="ssex != null">ssex = #{ssex},</if><if test="classid != 0">classid = #{classid}</if></set>where sid = #{sid}</update>

测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();
//		s.setSsex("男");s.setClassid(2);s.setSid(19);s.setSname("zkthah");int ret = stuMapper.updateStudentSet(s);if (ret > 0) {System.out.println("成功");sqlSession.commit();} else {System.out.println("失败");sqlSession.rollback();}DaoUtil.closeResource(sqlSession);

五、foreach 元素

语法:

语法:
<foreach   item = “”index=“” collection=“” open=“” separator=“” close=“”></foreach>item 循环中的当前元素;
index 当前循环元素的位置下标;
collection 方法传递的参数,一个数组或者集合;
close 以什么符号结束将这些集合元素包装起来;
open 以什么符号开始将这些集合元素包装起来;
separator 各个元素的间隔符号。

参数是数组

实现:

StudentMapper.java

public List<Student> findStudentArray(int[] arr);

StudentMapper.xml

 <select id="findStudentArray" resultType="student" >select * from student<where><foreach collection="array" item="x" open=" sid in(" close=")" index="i" separator=",">#{x}</foreach> </where></select>

测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);int[] arr = { 1, 2, 3, 4, 5, 6, 7 };List<Student> slist = stuMapper.findStudentArray(arr);slist.forEach(System.out::println);DaoUtil.closeResource(sqlSession);


参数是ArrayList

实现:

StudentMapper.java

	public List<Student> findStudentList(List<Integer> sidList);

StudentMapper.xml

<select id="findStudentList" resultType="student" >select * from student<where><foreach collection="list" item="x" open=" sid in(" close=")" index="i" separator=",">#{x}</foreach> </where></select>

测试:


SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);List<Integer> sidlist = new ArrayList<Integer>();sidlist.add(1);sidlist.add(2);sidlist.add(3);sidlist.add(4);sidlist.add(5);List<Student> slist = stuMapper.findStudentList(sidlist);slist.forEach(System.out::println);DaoUtil.closeResource(sqlSession);


批量增加

实现:

StudentMapper.java

// 批量增加public int addStudentList(List<Student> stuList);

StudentMapper.xml

<insert id="addStudentList" >insert into student (sname,birthday,ssex,classid)values<foreach collection="list" item="stu" separator=",">(#{stu.sname},#{stu.birthday},#{stu.ssex},#{stu.classid})</foreach></insert>

测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s1 = new Student();s1.setBirthday(new Date());s1.setClassid(1);s1.setSname("刘备");s1.setSsex("男");Student s2 = new Student();s2.setBirthday(new Date());s2.setClassid(2);s2.setSname("小乔");s2.setSsex("女");Student s3 = new Student();s3.setBirthday(new Date());s3.setClassid(2);s3.setSname("曹操");s3.setSsex("男");List<Student> stulist = new ArrayList<Student>();stulist.add(s1);stulist.add(s2);stulist.add(s3);int ret = stuMapper.addStudentList(stulist);if (ret == stulist.size()) {sqlSession.commit();System.out.println("成了");} else {sqlSession.rollback();System.out.println("凉了");}DaoUtil.closeResource(sqlSession);

六、bind 元素 

定义一个变量

语法:

语法:
<bind   name=“”value=“_parameter”></bind>name 自定义变量的变量名
value 自定义变量的变量值
_parameter 传递进来的参数

实现:

StudentMapper.java

	// 模糊查询public List<Student> findStudentLikeSname(String keyname);

StudentMapper.xml

<select id="findStudentLikeSname" parameterType="String" resultType="Student"><!-- select * from student where sname like '%#{v}%' --><!-- 方式一 业务层解决 --><!-- select * from student where sname like #{v} --><!-- 方式二 concat 推荐--><!-- select * from student where sname like concat('%',#{v},'%') --><!-- 方式三 ${} ${} 和 #{} 区别 *****--><!-- select * from student where sname like '%${v}%' --><!-- 方式四 sql语法 --><!-- select * from student where sname like "%"#{v}"%" --><!-- 方式五 bind  推荐--><bind name="kk" value="'%'+_parameter+'%'"/>select * from student where sname like #{kk}</select>

测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);	List<Student> slist = stuMapper.findStudentLikeSname("张");slist.forEach(System.out::println);DaoUtil.closeResource(sqlSession);

方式一:在 张 前后加%%即

  List<Student> slist = stuMapper.findStudentLikeSname("%张%");

#{} ${} 区别

  • #{}匹配的是一个占位符,相当于JDBC中的一个?会对一些敏感的字符进行过滤,编译过后会对传递的值加上双引号,因此可以防止SQL注入问题。
  • ${}匹配的是真实传递的值,传递过后,会与sql语句进行字符串拼接。${}会与其他sql进行字符串拼接,不能预防sql注入问题。

#{}是预编译处理,$ {}是字符串替换。

mybatis在处理#{}时,会将sql中的#{}替换为?号,调用PreparedStatement的set方法来赋值;

mybatis在处理 $ { } 时,就是把 ${ } 替换成变量的值。使用 #{} 可以有效的防止SQL注入,提高系统安全性。

示例完整代码

StudentMapper.java

public interface StudentMapper {// 查询public List<Student> findStudent(Student s);public List<Student> findStudentWhere(Student s);public List<Student> findStudentChoose(Student s);public int updateStudentSet(Student s);public List<Student> findStudentTrim(Student s);public int updateStudentTrim(Student s);public int addStudent(Student s);public List<Student> findStudentArray(int[] arr);public List<Student> findStudentList(List<Integer> sidList);// 批量增加public int addStudentList(List<Student> stuList);// 模糊查询public List<Student> findStudentLikeSname(String keyname);}

StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.zkt.mapper.StudentMapper"><!-- OGNL 对象图导航语言 属性 运算符 逻辑 字符串增强 == --><!-- test中的表达式成立 就把if标签里面的字串拼接 --><select id="findStudent" resultType="student" parameterType="student">select * from student where 1=1<if test="ssex != null">and ssex=#{ssex}</if><if test="classid != 0">and classid=#{classid}</if></select><!-- where标签 1.添加一个where关键词 2. 去掉where后的第一个and 3.当没where标签中没有任何成立的字串时 什么也不添加 --><select id="findStudentWhere" resultType="student" parameterType="student">select * from student<where><if test="ssex != null">and ssex=#{ssex}</if><if test="classid != 0">and classid=#{classid}</if></where></select><select id="findStudentChoose" resultType="student" parameterType="student">select * from student<where><choose><when test="sname != null">and sname=#{sname}</when><when test="ssex != null">and ssex=#{ssex}</when><otherwise>and sid > 10</otherwise></choose></where></select><update id="updateStudentSet" parameterType="student">update student<set><if test="sname != null">sname = #{sname},</if><if test="birthday != null">birthday = #{birthday},</if><if test="ssex != null">ssex = #{ssex},</if><if test="classid != 0">classid = #{classid}</if></set>where sid = #{sid}</update><!-- trim 万能标签prefix 开始添加一个什么prefixOverrides 开始去掉一个什么suffix 结束添加一个什么suffixOverrides 结束去掉一个什么--><select id="findStudentTrim" parameterType="student" resultType="student">select * from student <trim prefix=" where " prefixOverrides="and" ><if test="ssex != null"> and ssex= #{ssex}</if><if test="classid != 0"> and classid = #{classid}</if></trim></select><update id="updateStudentTrim" parameterType="student">update student<trim prefix="set " suffixOverrides=","><if test="sname != null">sname = #{sname},</if><if test="birthday != null">birthday = #{birthday},</if><if test="ssex != null">ssex = #{ssex},</if><if test="classid != 0">classid = #{classid},</if></trim>where sid = #{sid}</update><insert id="addStudent" parameterType="student">insert into  student <trim prefix="(" suffix=")" suffixOverrides=","><if test="sid != 0"> sid,</if><if test="sname != null"> sname,</if><if test="birthday != null"> birthday,</if><if test="ssex != null"> ssex,</if><if test="classid != 0"> classid,</if></trim>values<trim prefix="(" suffix=")" suffixOverrides=","><if test="sid != 0"> #{sid},</if><if test="sname != null"> #{sname},</if><if test="birthday != null"> #{birthday},</if><if test="ssex != null"> #{ssex},</if><if test="classid != 0"> #{classid},</if></trim></insert><select id="findStudentArray" resultType="student">select * from student<where> <foreach collection="array" item="x" open="sid in(" close=")" index="i" separator=",">#{x}</foreach></where></select><select id="findStudentList" resultType="student">select * from student<where> <foreach collection="list" item="x" open="sid in(" close=")" index="i" separator=",">#{x}</foreach></where></select><insert id="addStudentList" >insert into student (sname,birthday,ssex,classid)values<foreach collection="list" item="stu" separator=",">(#{stu.sname},#{stu.birthday},#{stu.ssex},#{stu.classid})</foreach></insert><select id="findStudentLikeSname" parameterType="String" resultType="Student"><!-- select * from student where sname like '%#{v}%' --><!-- 方式一 业务层解决 --><!-- select * from student where sname like #{v} --><!-- 方式二 concat 推荐--><!-- select * from student where sname like concat('%',#{v},'%') --><!-- 方式三 ${} ${} 和 #{} 区别 *****--><!-- select * from student where sname like '%${v}%' --><!-- 方式四 sql语法 --><!-- select * from student where sname like "%"#{v}"%" --><!-- 方式五 bind  推荐--><bind name="kk" value="'%'+_parameter+'%'"/>select * from student where sname like #{kk}</select></mapper>

测试:

public class Test01 {public static void main(String[] args) {SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();
//		s.setClassid(1);
//		s.setSsex("男");
//		s.setSname("zkt");
//		s.setSid(1);//		List<Student> slist = stuMapper.findStudent(s);
//		List<Student> slist = stuMapper.findStudentWhere(s);
//		List<Student> slist = stuMapper.findStudentChoose(s);
//		List<Student> slist = stuMapper.findStudentTrim(s);//		int[] arr = {1,2,3,4,5,6,7};
//		List<Student> slist = stuMapper.findStudentArray(arr);//		List<Integer> sidlist = new ArrayList<Integer>();
//		sidlist.add(1);
//		sidlist.add(2);
//		sidlist.add(3);
//		sidlist.add(4);
//		sidlist.add(5);
//		List<Student> slist = stuMapper.findStudentList(sidlist);List<Student> slist = stuMapper.findStudentLikeSname("张");slist.forEach(System.out::println);//		int ret = stuMapper.updateStudentSet(s);
//		int ret = stuMapper.addStudent(s);//		Student s1 = new Student();
//		s1.setBirthday(new Date());
//		s1.setClassid(1);
//		s1.setSname("刘备");
//		s1.setSsex("男");
//		
//		Student s2 = new Student();
//		s2.setBirthday(new Date());
//		s2.setClassid(2);
//		s2.setSname("小乔");
//		s2.setSsex("女");
//		
//		Student s3 = new Student();
//		s3.setBirthday(new Date());
//		s3.setClassid(2);
//		s3.setSname("曹操");
//		s3.setSsex("男");
//		
//		List<Student> stulist = new ArrayList<Student>();
//		stulist.add(s1);
//		stulist.add(s2);
//		stulist.add(s3);
//		
//		int ret = stuMapper.addStudentList(stulist);
//		
//		if(ret == stulist.size()) {
//			sqlSession.commit();
//			System.out.println("成了");
//		}else {
//			sqlSession.rollback();
//			System.out.println("凉了");
//		}DaoUtil.closeResource(sqlSession);}
}




七、映射器注解

映射器配置文件的缺陷

  • 繁琐:配置文件的书写本身繁琐,需要掌 握的内容比较多
  • 不直观:配置文件和接口直接只是名称相同, 对应起来比较麻烦.

常用的注解

  • 基本注解:实现简单的增删改查操作。
  • 结果映射注解:实现结果的映射关系, 也可以完成级联映射。
  • 动态SQL注解:实现动态 SQL 的内容

八、基本注解

基本注解的分类

  • 增加操作 @Insert 类似 < insert > 完成新增
  • 删除操作 @Delete 类似 < delete > 完成删除
  • 修改操作 @Update 类似 < update > 完成修改
  • 查询操作 @Select 类似 < select > 完成查询

@Insert 新增

功能:完成新增操作,类似配置文件的<insert>元素;

说明:新增时所用的参数取值是接口方法的入参,可以是对象,也可以是 Map 集合。

语法:

语法:
@Insert (“ sql 语句”)

主键回填 

功能:完成数据库自增主键的回填;

语法:

语法:
@Options(useGeneratedKeys = true, keyProperty = "主键属性")

StudentMapper.java

//新增 -- 主键回填@Insert("insert into student(sname,birthday,ssex,classid)"+ "values(#{sname},#{birthday},#{ssex},#{classid})")@Options(useGeneratedKeys = true,keyProperty = "sid")public int addStudent(Student s);

 测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();s.setClassid(1);s.setSsex("男");s.setSname("zkt89");s.setBirthday(new Date());
//		s.setSid(1);System.out.println("添加前"+s);int ret = stuMapper.addStudent(s);System.out.println("添加后"+s);if(ret >0) {sqlSession.commit();System.out.println("成了");}else {sqlSession.rollback();System.out.println("凉了");}DaoUtil.closeResource(sqlSession);

 

主键自增 

功能:完成自定义主键的自增;

语法:

语法:
@SelectKey ( statement = "自增规则", keyProperty 
= "主键属性", resultType = 结果类型, before = true )

@Delete 删除

功能:完成删除操作,类似配置文件的<delete>元素;

说明:删除时所用的参数取值是接口方法的入参,可以是对象,也可以是 Map 集合。

语法:

语法:
@Delete (“ sql 语句”)

示例:

StudentMapper.java

@Delete("delete from student where sid = #{v}")public int deleteStudent(int sid);

 测试:

	SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);int ret = stuMapper.deleteStudent(23);if (ret > 0) {sqlSession.commit();System.out.println("成了");} else {sqlSession.rollback();System.out.println("凉了");}DaoUtil.closeResource(sqlSession);

@Update 更新

功能:完成更新操作,类似配置文件的<update>元素;

说明:更新时所用的参数取值是接口方法的入参,可以是对象,也可以是Map 集合。

语法:

语法:
@Update (“ sql 语句”)

示例:

StudentMapper.java

@Update("update student set sname=#{sname},birthday=#{birthday},"+ "ssex=#{ssex},classid=#{classid} where sid=#{sid}")	public int updateStudent(Student s);

 测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();s.setClassid(1);s.setSsex("男");s.setSname("zkt89");s.setBirthday(new Date());s.setSid(4);int ret = stuMapper.updateStudent(s);if (ret > 0) {sqlSession.commit();System.out.println("成了");} else {sqlSession.rollback();System.out.println("凉了");}DaoUtil.closeResource(sqlSession);

@Selete 查询 

功能:完成查询操作,类似配置文件的 <select>元素;

说明:查询时所用的参数取值是接口方法的入参,可以是 对象,也可以是 Map 集合。

语法:

语法:
@Selete (“ sql 语句”)

示例:

StudentMapper.java

@Select("select * from student")public List<Student> findStudent();@Select("select * from student where sid = #{v}")public Student findStudentBySid(int Sid);

 测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);List<Student> slist = stuMapper.findStudent();slist.forEach(System.out::println);System.out.println("============");Student s = stuMapper.findStudentBySid(5);System.out.println(s);DaoUtil.closeResource(sqlSession);

注解和sqlMapper.xml 可以同时使用

注解底层还是sqlMapper 方法还是不能重载

传递多个参数的方式: 

  • 方法1:Map 方式 跟sqlmap一样
  • 方法2:JavaBean 方式 跟sqlmap一样
  • 方法3:@Param 方式

示例:

StudentMapper.java

//多参 4 javabean map arg0... param1...//@Param@Select("select * from student where ssex = #{sex} and classid=#{banjibianhao} limit #{cp},#{sp}")public List<Student> findStudentBySexAndClassidPage(@Param("sex")String sex,@Param("banjibianhao")int classid,@Param("cp")int curpage,@Param("sp")int sizepage);

 测试:

SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);List<Student> slist = stuMapper.findStudentBySexAndClassidPage("男", 1, (1-1)*3, 3);slist.forEach(System.out::println);DaoUtil.closeResource(sqlSession);

九、结果映射注解

@Results 结果映射

功能: 完成数据库字段和 JavaBean 属性的映射关系;

说明:每个 @Results 可以包含多个 @Result,其中通过 id 属性来判断是否为主键。

语法:

语法:
@Results({ @Result(id = 是否为主键, 
column = "字段", property = "属性" ) })

@Results 复用

示例:

SMasterMapper .java

@Results({ @Result(column = "sm_name", property = "smname") })@Select("select * from schoolmaster")public List<SMaster> findAllSm();@Select("select * from schoolmaster where smid = #{v}")public SMaster findSmBySmid(int smid);

测试:

SqlSession sqlSession = DaoUtil.getSqlSession();SMasterMapper smMapper = sqlSession.getMapper(SMasterMapper.class);List<SMaster> smlist = smMapper.findAllSm();smlist.forEach(System.out::println);SMaster sm = smMapper.findSmBySmid(1);System.out.println(sm);

注解映射各用各的

一对一映射 

功能:一对一的关系映射; 

说明:FetchType.lazy 是延时加载,FetchType.EAGER 是即时加载。

语法:

语法:
@One( Select = 一对一查询方法, 
fetchType = FetchType.EAGER ) 

示例:

StudentMapper.java

@Results({@Result(column = "classid",property = "bj", one=@One(select = "com.ape.mapper.BanjiMapper.findBanjiByClassid"))})@Select("select * from student ")public List<Student> findStudentAndClass();

BanjiMapper.java

@Select("select * from class where classid=#{classid}")public Banji findBanjiByClassid(int classid);

 测试:

SqlSession sqlSession =DaoUtil.getSqlSession();StudentMapper stuMapper =sqlSession.getMapper(StudentMapper.class);List<Student> sList = stuMapper.findStudentAndClass();sList.forEach(System.out::println);DaoUtil.closeResource(sqlSession);

注解没有表联查 只有单表和自己写的映射关系

一对一映射的实现案例

一对多映射

功能:一对多的关系映射;

说明:FetchType.lazy 是延时加载,FetchType.EAGER 是即时加载。

语法:

语法:
@Many( Select = 一对多查询方法, 
fetchType = FetchType.EAGER ) 

示例:

BanjiMapper.java

@Results({@Result(column = "classid",property = "classid"),@Result(column = "classid",property = "sList",many =@Many(select = "com.zkt.mapper.StudentMapper.findStudentByClassid"))})@Select("select * from class")public List<Banji> findAllBanji();

StudentMapper.java

@Select("select * from student where classid=#{v}")public List<Student> findStudentByClassid(int classid);

 测试:

SqlSession sqlSession = DaoUtil.getSqlSession();BanjiMapper bjmapper = sqlSession.getMapper(BanjiMapper.class);List<Banji> bjList = bjmapper.findAllBanji();bjList.forEach(System.out::println);DaoUtil.closeResource(sqlSession);

一对多映射的实现案例

示例完整代码 

实体类同mybatis2

BanjiMapper.java

public interface BanjiMapper {@Select("select * from class where classid=#{classid}")public Banji findBanjiByClassid(int classid);@Results({ @Result(column = "classid", property = "classid"),@Result(column = "classid", property = "sList", many = @Many(select = "com.zkt.mapper.StudentMapper.findStudentByClassid")) })@Select("select * from class")public List<Banji> findAllBanji();}

StudentMapper.java

public interface StudentMapper {@Select("select * from student")public List<Student> findStudent();@Select("select * from student where sid = #{v}")public Student findStudentBySid(int Sid);// 多参 4 javabean map arg0... param1...// @Param@Select("select * from student where ssex = #{sex} and classid=#{banjibianhao} limit #{cp},#{sp}")public List<Student> findStudentBySexAndClassidPage(@Param("sex") String sex, @Param("banjibianhao") int classid,@Param("cp") int curpage, @Param("sp") int sizepage);// 新增 -- 主键回填@Insert("insert into student(sname,birthday,ssex,classid)" + "values(#{sname},#{birthday},#{ssex},#{classid})")@Options(useGeneratedKeys = true, keyProperty = "sid")public int addStudent(Student s);@Update("update student set sname=#{sname},birthday=#{birthday},"+ "ssex=#{ssex},classid=#{classid} where sid=#{sid}")public int updateStudent(Student s);@Delete("delete from student where sid = #{v}")public int deleteStudent(int sid);@Results({@Result(column = "classid", property = "bj", one = @One(select = "com.zkt.mapper.BanjiMapper.findBanjiByClassid")) })@Select("select * from student")public List<Student> findStudentAndClass();@Select("select * from student where classid=#{v}")public List<Student> findStudentByClassid(int classid);}

测试1

public class Test01 {public static void main(String[] args) {SqlSession sqlSession = DaoUtil.getSqlSession();StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);Student s = new Student();s.setClassid(1);s.setSsex("男");s.setSname("zkt89");s.setBirthday(new Date());s.setSid(4);//		List<Student> slist = stuMapper.findStudent();
//
//		slist.forEach(System.out::println);//		System.out.println("=============");
//		Student s = stuMapper.findStudentBySid(5);
//		System.out.println(s);List<Student> slist = stuMapper.findStudentBySexAndClassidPage("男", 1, (1-1)*3, 3);slist.forEach(System.out::println);//		System.out.println("添加前"+s);
//		int ret = stuMapper.addStudent(s);
//		System.out.println("添加后"+s);//		int ret = stuMapper.updateStudent(s);
//		int ret = stuMapper.deleteStudent(23);
//		if (ret > 0) {
//			sqlSession.commit();
//			System.out.println("成了");
//		} else {
//			sqlSession.rollback();
//			System.out.println("凉了");
//		}DaoUtil.closeResource(sqlSession);}
}

测试3

public class Test03 {public static void main(String[] args) {SqlSession sqlSession = DaoUtil.getSqlSession();
//		StudentMapper stuMapper =sqlSession.getMapper(StudentMapper.class);
//		List<Student> sList = stuMapper.findStudentAndClass();
//		sList.forEach(System.out::println);BanjiMapper bjmapper = sqlSession.getMapper(BanjiMapper.class);List<Banji> bjList = bjmapper.findAllBanji();bjList.forEach(System.out::println);DaoUtil.closeResource(sqlSession);}
}

关键字:MyBatis3(动态SQL 常用的动态SQL 元素 映射器注解 基本注解 结果映射注解)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: