MyBatis 笔记总结

Mybatis 持久层框架 简化JDBC开发

持久层 负责将数据保存到数据库那一层的代码

JavaEE架构 表现层 业务层 持久层

idea配置数据库链接

environments 配置多源数据库 通过default属性切换不同的数据库

配置类型别名映射到pojo类

数据库表的字段名称 和实体类的属性名称 不一样时 不能自动封装数据

解决方式 一 起别名 让别名和实体类属性名一致就行 缺点 每次查询都要起别名

<select id="selectAll" resultType="brand" >
	select id, brand_name as brandName, cpompany_name as companyName, status from tb_brand
</select>

解决方式二 定义sql片段 缺点不灵活

<sql id="brand_column">
	id, brand_name as brandName, cpompany_name as companyName, status
</sql>

<select id="selectAll" resultType="brand">
	select <include refid="brand_column" />
      from tb_brand;
</select>

解决方式三 resultMap 只需在resultMap定义不一样的字段 id 唯一标识 type 映射的类型 支持别名

<resultMap id="brandResultMap" type="brand">
	<result column="brand_name" property="brandName"></result>
    <result column="company_name" property="companyName"></result>
</resultMap>

<select id="selectAll" resultMap="brandResultMap">
	select * from tb_brand
</select>

resultMap id 完成主键字段的映射 result 完成一般字段的映射

column 表的列名 property 实体属性名

<!-- 在 MyBatis 的 XML 映射文件中 -->

<resultMap id="userResultMap" type="com.example.User">
    <!-- 主键映射 -->
    <id property="id" column="user_id"/>
    
    <!-- 部分查询字段映射 -->
    <result property="username" column="user_name"/>
    <result property="email" column="email_address"/>
</resultMap>

<!-- 使用 resultMap 的 SQL 查询示例 -->
<select id="selectUsers" resultMap="userResultMap">
    SELECT user_id, user_name, email_address 
    FROM users
    WHERE status = 'active'
</select>
``

在这个例子中:
- `<resultMap>` 标签定义了一个名为 `userResultMap` 的映射,适用于 `com.example.User` 类型的对象。
- `<id>` 标签用来映射表的主键,这里假设数据库表的主键列名为 `user_id`,而对应的 Java 对象属性为 `id`。
- `<result>` 标签用于映射其他非主键字段,如用户名(`user_name`)和电子邮件地址(`email_address`),它们分别映射到 User 对象的 `username` 和 `email` 属性上。
- 最后,一个 SQL 查询语句使用了这个 `resultMap` 来选择特定的列,并将查询结果映射到 `User` 对象的实例上。

请根据你的实际需求调整数据库列名、Java 属性名和实体类路径等信息。

查看详情

Brand selectById(int id)
<select id="selectById" parameterType="int" resultMap="brandResultMap">
	select * from tb_brand where id = #{id}
</select>

参数占位符 #{} 会将其替换为? 防止sql注入

${ } 拼成sql 会存在sql注入问题

参数传递时采用 #{} 动态表名时采用${}

参数类型可以省略

特殊字符处理 < &lt ; 也可采用 CDATA处理

多条件查询
List<Brand> selectByCondition(@Param("status") int status, @Param("companyName") String companyName, @Param("brandName") String brandName);

List<Brand> selectByCondition(Brand brand);
List<Brand> selectByCondition(Map map);
// 散装 参数  对象 参数  map集合
<select id="selectByCondition" resultMap="brandResultMap">
	select * from tb_brand where status = #{status} and
    company_name like #{companyName} and
    brand_name like #{brandName}
</select>
//多参数
int status = 1;
String companyName = "华为";
String brandName = "华为";

companyName = "%" + companyName + "%"
brandName = "%" + brandName + "%"
    
List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName)
//对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);

List<Brand> brands = brandMapper.selectByCondition(brand)
//map参数
Map map = new HashMap();
map.put("status", status);
map.put("companyName", companyName);
map.put("brandName", brandName);

List<Brand> brands = brandMapper.selectByCondition(map)

上面查询方式 三个查询条件都符合 才能查询到数据 不然返回空数组

动态条件查询
<select id="selectByCondition" resultMap="brandResultMap">
	select * from tb_brand where 
    <if test="status != null">
    	status = #{status}
    </if>
     <if test="companyName != null and companyName != ''">
    	and company_name like #{companyName}
    </if>
     <if test="brandName != null and brandName != ''">
    	and brand_name like #{brandName}
    </if>
</select>

if条件判断 test 逻辑表达式

解决and问题 可以添加恒等式 或 标签 替换where

<select id="selectByCondition" resultMap="brandResultMap">
	select * from tb_brand where 1 = 1
    <if test="status != null">
    	and status = #{status}
    </if>
     <if test="companyName != null and companyName != ''">
    	and company_name like #{companyName}
    </if>
     <if test="brandName != null and brandName != ''">
    	and brand_name like #{brandName}
    </if>
</select>
<select id="selectByCondition" resultMap="brandResultMap">
    select * from tb_brand
    <where>
        <if test="status != null">
            and status = #{status}
        </if>
        <if test="companyName != null and companyName != ''">
            and company_name like #{companyName}
        </if>
        <if test="brandName != null and brandName != ''">
            and brand_name like #{brandName}
        </if>
    </where>
</select>

Mybatis 对动态sql有很强大的支撑 比如 if choose (when, otherwise) trim(where, set) foreach

单条件动态查询

image-20250503172758064

<select id="selectByConditionSingle" resultMap="brandResultMap">
	select * from tb_brand 
    <where>
    	<choose>  //类似于switch
        	<when test="status != null">  //类似于case
            	status = #{status}
            </when>
            <when test="companyName != null and companyName != ''">
            	company_name like #{companyName}
            </when>
            <when test="brandName != null and brandName != ''">
            	brand_name like #{brandName}
            </when>
            <otherwise>  //类似于default  避免不传查询条件导致语句出错
            	1=1
            </otherwise>
        </choose>
    </where>
</select>
List selectByConditionSingle(Brand brand)
添加修改

image-20250503211306198

<insert id="add">
	insert into tb_brand(brand_name, company_name, status) values(#{brandName}, #{companyName}, #{status})
</insert>

提交操作需要开启事务

添加 主键返回

image-20250503220107642

设置 useGeneratedKeys 和 keyProperty 就返回mybatis添加项的主键ID

<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO users (username, password, email)
    VALUES (#{username}, #{password}, #{email})
</insert>

修改全部字段

void update(Brand brand);
<update id="update">
	update tb_brand
    set brand_name = #{brandName},
    company_name = #{companyName},
    status = #{status}
    where id = #{id}
</update>

image-20250503221028123

修改动态字段

<update id="update">
	update tb_brand
    <set>
    	<if test="brandName != null and brandName != ''">
        	brand_name = #{brandName}
        </if>
        <if test="companyName != null and companyName != ''">
        	company_name = #{companyName}
        </if>
        <if test="status != null">
        	status = #{status}
        </if>
    </set>
    where id = #{id}
</update>
删除功能(单个删除 批量删除 )
void deleteById(int id);
<delete id="deleteById">
	delete from tb_brand where id = #{id}
</delete>

批量删除

image-20250503231221018

void delteByIds(@Param("ids") int[] ids);
<delete id="deleteByIds">
	delete from tb_brand where id in 
    <foreach collection="ids" item="id" separator="." open="(" close=")">
    	#{id}
    </foreach>
</delete>

collection一般是array 数组 添加@param参数 可以改为ids

separator分隔符 open 开始符 close 结束符

参数传递

image-20250503235017656

mybatis会将多个参数封装为Map集合 可以使用@Param注解 替换Map集合中默认的arg键名

image-20250503235828839

建议都使用 @Param注解来修改Map集合中 默认的键名 使用修改后的名称来获取值

注解完成增删改查

image-20250504000056871

@Select("selct * from tb_user where id = #{id}")
public User selectById(int id);

复杂操作还是建议使用xml来使用映射

posted @ 2025-05-08 19:23  一剑浮尘为谁  阅读(35)  评论(0)    收藏  举报