一对多:
一对多关系是关系数据库中两个表之间的一种关系,该关系中第一个表中的单个行可以与第二个表中的一个或多个行相关,但第二个表中的一个行只可以与第一个表中的一个行相关。
Class班级表
实体类
/**
* @program: batis02
* @description:
* @author: 不会代码的坤仔
* @create: 2021-12-02 21:23
**/
@Data
public class Classes {
private int id;
private String name;
//对应学生表 因为是一对多的关系对应多个所以这里用几个List
private List<Student> students;
}
Student学生表
实体类
@Data
public class Student implements Serializable {
private String sId;
private String sName;
private String sBirth;
private String sSex;
private int cid;
映射文件
<sql id="sql1">
c.c_id,c_name,s_id,s_name,s_birth,s_sex,s.s_id
</sql>
<resultMap id="map" type="com.aaa.qy145.ninth.rqk.entity.Class">
<id column="c_id" jdbcType="INTEGER" property="cId" />
<result column="c_name" jdbcType="VARCHAR" property="cName" />
collection: 集合的意思 多的意思
property:集合对象名
ofType: 集合的泛型
<collection property="students" ofType="com.aaa.qy145.ninth.rqk.entity.Student" autoMapping="true">
<!--这里的id必须和Dao中的方法名一致。-->
<id property="sId" column="s_id"/>
<result property="sName" column="s_name"/>
<result property="sBirth" column="s_birth"/>
<result property="sSex" column="s_sex"/>
</collection>
</resultMap>
<select id="selectid" resultMap="map">
select <include refid="sql1"/>
from class c join Student s on c.c_id=s.c_id where c.c_id=#{id}
</select>
动态sql语句
if where联用
where会为sql语句自动添加where 还会自动去除第一个and
<select id="selectnameauthor" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from book_info
<where>
//test与实体类中的名字对应
<if test="bookName!=null and bookName!=''">
//#{}中的多个参数要与实体类中的属性名对照,如果只有一个参名字无所谓
and book_name=#{bookName}
</if>
<if test="bookAuthor!=null and bookAuthor!=''">
and book_author=#{bookAuthor}
</if>
</where>
</select>
choose(when,otherwise)/where
只要有一个条件满足就不会再向下执行了,如果没有条件满足就执行otherwise中的
<select id="selectnameauthor2" resultMap="BaseResultMap">
select <include refid="Base_Column_List"/> from book_info
<where>
<choose>
<when test="bookName!=null and bookName!=''">
and book_name=#{bookName}
</when>
<when test="bookAuthor!=null and bookAuthor!=''">
and book_author=#{bookAuthor}
</when>
<otherwise>
</otherwise>
</choose>
</where>
</select>
set 用于修改
set 可以帮你添加set关键字 并且去除最后的逗号。
<!--修改部分列的值。
set 可以帮你添加set关键字 并且去除最后的逗号。
-->
<update id="update">
update book_info
<set>
<if test="name!=null and name!=''">
book_name=#{name},
</if>
<if test="author!=null and author!=''">
book_author=#{author},
</if>
<if test="pub!=null and pub!=''">
book_pub=#{pub},
</if>
<if test="price!=null">
book_price=#{price},
</if>
</set>
where book_id=#{id}
</update>
foreach批量删除
<!--
delete from book_info where id in(1001,1002,1003)
in (1001,1002,1003)
foreach:
collection:要遍历的集合和数组名
item: 每次遍历时赋值的元素变量名
open: 以什么开始
close:以什么结束
separator: 分隔符
-->
<delete id="batchDelete">
delete from book_info where book_id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>