Java Web(二)Mybatis

举报
浅辄 发表于 2022/11/11 11:10:02 2022/11/11
【摘要】 MyBatis一.MyBatis简介1.什么是MyBatisMyBatis是一款优秀的持久层框架,用于简化 JDBC 开发MyBatis本是Apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github官网:https://mybatis.org/my...

MyBatis

一.MyBatis简介

1.什么是MyBatis
  • MyBatis是一款优秀的持久层框架,用于简化 JDBC 开发

  • MyBatis本是Apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github

  • 官网:https://mybatis.org/mybatis-3/zh/index.html

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

  • JavaEE三层架构:表现层、业务层、持久层

3.框架
  • 框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型

  • 在框架的基础之上构建软件编写更加高效、规范、通用、可扩展

二.MyBatis简化

1.JDBC缺点

1.硬编码

注册驱动,获取连接 SQL语句

2.操作繁琐

手动设置参数 手动封装结果集

//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取Connection.连接
String url = "jdbc:mysql:///db1?useSSL=false";
String uname "root";
String pwd ="1234";
Connection conn = DriverManager.getConnection(url,uname,pwd);
∥接收输入的查询条件
String gender="男";
∥定义sql
String sql "select from tb_user where gender = ?";
∥获取pstmt对象
PreparedStatement pstmt =  conn.prepareStatement(sql);
∥设置?的值
pstmt.setString(1,gender);
∥执行sql
ResultSet rs = pstmt.executeQuery();
∥遍历Result,获取数据
User user = null;
ArrayList<User>users new ArrayList<>();
while (rs.next(){
∥获取数据
    int id rs.getInt("id");
    String username = rs.getString("username");
    String password = rs.getString("password");
    ∥创建对象,设置属性值
    user = new User();
    user.setld(id);
    user.setUsername(username);
    user.setPassword(password);
    user.setGender(gender);
    ∥装入集合
    users.add(user);
}

MyBatis免除了几乎所有的JDBC代码 以及设置参数和获取结果集的工作

三.MyBatis快速入门

1.查询user表中所有数据

1.创建user表,添加数据

2.创建模块,导入坐标

3.编写小yBatis核心配置文件->替换连接信息解决硬编码问题

4.编写SQL映射文件->统一管理sq语句,解决硬编码问题

5.编码

        1.定义P0J0类
        2.加载核心配置文件,获取SqlSessionFactory对象
        3.获取SqlSession对象,执行SQL语句
        4.释放资源
create database mybatis;
use mybatis;
​
drop table if exists tb_user;
​
create table tb_user(
        id int PRIMARY key auto_increment,
        username varchar(20),
        password varchar(20),
        gender char(1),
        addr varchar(30)
);
​
​
insert into tb_user values(1,'张三','123','男','北京');
insert into tb_user values(2,'李四','345','女','上海');
insert into tb_user values(3,'王五','567','男','成都');
2.解决SQL映射文件的警告提示
  • 产生原因:Idea和数据库没有建立连接,不识别表信息

  • 解决方式:在ldea中配置MySQL数据库连接

四.Mapper代理开发

1.目的

解决原生方式中的硬编码

简化后期执行SQL

        List<User> users = sqlSession.  selectList("test.selectAll");
        System.out.println(users);
        //3.获取接口代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //4.执行方法,其实就是执行sgL语句
        List<User>users = userMapper.selectAll();
2.使用Mapper代理方式完成入门案例

1.定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下

2.设置SQL映射文件的namespace)属性为Mapper接口全限定名

3.在Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致 4.编码

4.1.通过SqlSession的getMapper方法获取Mapper接口的代理对象 4.2.调用对应方法完成sq的执行

细节:如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载

五.MyBatis核心配置文件

1.environments

配置数据库连接环境信息.可以配置多个environment,通过不同的default属性切换不同的environment

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!-- 数据库连接信息 -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
2.mappers
    </environments>
    <mappers>
        <!-- 加载sql映射文件 -->
        <mapper resource="com/gbx/mapper/UserMapper.xml"/>
​
        <!-- Mapper代理方式 -->
        <package name="com.gbx.mapper"/>
    </mappers>
3.typeAliases

类型别名可为Java类型设置一个缩写名字。它仅用于XML配置,意在降低冗余的全限定类名书写。

    <typeAliases>
        <package name="com.gbx.pojo"/>
    </typeAliases>

六.MyBatis完成CURD

查询

  • 查询所有数据

  • 查看条件

  • 条件查询

添加

修改

  • 修改全部字段

  • 修改动态字段

删除

  • 删除一个

  • 批量删除

1.通过配置xml文件
1.1准备环境

数据库表tb_ brand 实体类Brand 测试用例 安装MyBatisX:插件

#删除tb_brand表
drop table if exists tb_brand;
#创建tb_brand表
create table tb_brand
(
    #id  主键
    id  int primary key auto_increment,
    # 品牌名称
    brand_name  varchar(20),
    # 企业名称
    company_name  varchar(20),
    #排序字段
    ordered  int,
    # 描述信息
    description  varchar(100),
    #状态: 0 :禁用  1: 启动
    status int
);
insert into tb_brand(brand_name,company_name,ordered,description,status)
values('三只松鼠','三只松鼠股份有限公司',5,'好吃不上火',0),
      ('华为','华为技术有限公司',100,'华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界',1),
      ('小米','小米科技有限公司',50,'are you ok',1);
select * from tb_brand;
@Data
public class Brand {
    //id 主键
    private Integer id;
    //品牌名称
    private String brandName;
    //企业名称
    private String companyName;
    //排序字段
    private Integer ordered;
    //描述信息
    private String description;
    //状态:0:禁用1:启用
    private Integer status;
}
1.2MyBatisX

MyBatisX是一款基于IDEA的快速开发插件,为效率而生。

主要功能:

  • XML和接口方法相互跳转

  • 根据接口方法生成statement

1.3查询

查询所有

1.编写接口方法:Mapper接口

  • 参数:无

  • 结果:List<Brand>

2.编写SQL语句:SQL映射文件: 3.执行方法,测试

public interface BrandMapper {
    /**
     * 查询所有
     */
    public List<Brand> selectAll();
}
​
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace:名称空间
-->
<mapper namespace="com.gbx.mapper.BrandMapper">
    <select id="selectAll" resultType="brand">
        select * from
        tb_brand;
    </select>
</mapper>
public class MyBatisTest {
    @Test
    public void testSelectAll() throws IOException {
        //1.获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        List<Brand> brands = brandMapper.selectAll();
        System.out.println(brands);
        //5.释放资源
        sqlSession.close();
​
    }
}

MyBatis完成操作需要几步? 三步:编写接口方法>>编写>>执行方法

实体类属性名和数据库表列名不一致,不能自动封装数据 1)起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样 可以定义<sql>片段,提升复用性 2)resultMap:定义<resultMap>完成不一致的属性名和列名的映射

<!--
    数据库表的字段名称  和  实体类的属性名称不一样,则不能自动封装数据
       *起别名: 对不一样的列名起别名,让别名和实体类的属性名一样
            *缺点:每次查询都要定义一次别名
                *解决办法:sql 片段
                    缺点:不灵活
-->
<select id="selectAll" resultType="com.gbx.pojo.Brand">
    select id,brand_name as brandName,company_name as companyName,ordered,description,status
    from tb_brand;
</select>
<!--
  sql 片段
-->
<sql id="brand_column">
    id,brand_name as brandName,company_name as companyName,ordered,description,status
</sql>
<select id="selectAll" resultType="com.gbx.pojo.Brand">
    select 
        <include refid="brand_column"/>
    from tb_brand;
</select>
<!--
    数据库表的字段名称  和  实体类的属性名称不一样,则不能自动封装数据
    *resultMap:
        1.定义<resultMap>标签
        2.使用resultMap属性替换 resultType属性
-->
<!--
    id:唯一标识
    type:映射的类型,支持别名
 -->
<resultMap id="brandResultMap" type="brand">
    <!--
        id:完成主键的映射
            column:表的列名
            property:实体类的属性名
        result:完成一般字符的映射
     -->
    <result column="brand_name" property="brandName"/>
    <result column="company_name" property="companyName"/>
</resultMap>
<select id="selectAll" resultType="brandResultMap">
    select
    *
    from tb_brand;
</select>

查看详情

1.编写接口方法:Mapper接口 参数:id 结果:Brand 2.编写SQL语句:SQL映射文件 3.执行方法,测试

<!--
 *参数占位符:
            1.#{}:会将其替换成 ? .为了防止sql注入
            2.${}:拼sql 会存在sql注入问题
            3.使用时机:
                    *在参数传递的时候: #{}
                    *表明或者列名不固定的情况下:${}会存在sql注入问题
            *参数类型:parameterType:可以省略
            *特殊字符处理:
                    1.转义字符:
                    2.CDATA区
                    <I[CDATA[内容]>
 -->
<select id="selectById" parameterType="int" resultMap="brandResultMap">
    select * from tb_brand where id = #{id};
</select>

条件查询

1.多条件查询

1.编写接口方法:Mapper接口

参数:所有查询条件 结果:List<Brand>

2.编写SQL语句:SQL映射文件 3.执行方法,测试

    List<Brand> selectByCondition(@Param("status")int status,@Param("companyName") String companyName,@Param("brandName")String brandName);
​
    <select id="selectByCondition" resultType="brandResultMap">
        select * from tb_brand
        where status = #{status} and company_name like #{companyName}
        and brand_name like #{brandName}
    </select>
        
    @Test
    public void testSelectByCondition() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "华为";
        String brandName = "华为";
​
        //处理参数
        companyName="%"+companyName+"%";
        brandName="%"+brandName+"%";
        //1.获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
        System.out.println(brands);
        //5.释放资源
        sqlSession.close();
    }
​
    List <Brand> selectByCondition(Brand brand);
​
    <select id="selectByCondition" resultType="brandResultMap">
        select * from tb_brand
        where status = #{status} and company_name like #{companyName}
        and brand_name like #{brandName}
    </select>
    
    @Test
    public void testSelectByCondition() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "华为";
        String brandName = "华为";
​
        //处理参数
        companyName="%"+companyName+"%";
        brandName="%"+brandName+"%";
​
        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        //1.获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        List<Brand> brands = brandMapper.selectByCondition(brand);
        System.out.println(brands);
        //5.释放资源
        sqlSession.close();
    }
    List <Brand> selectByCondition(Map map);
​
    <select id="selectByCondition" resultType="brandResultMap">
        select * from tb_brand
        where status = #{status} and company_name like #{companyName}
        and brand_name like #{brandName}
    </select>
    
    @Test
    public void testSelectByCondition() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "华为";
        String brandName = "华为";
​
        //处理参数
        companyName="%"+companyName+"%";
        brandName="%"+brandName+"%";
​
        //Map集合
        Map map = new HashMap();
        map.put("status",status);
        map.put("companyName",companyName);
        map.put("brandName",brandName);
        //1.获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        List<Brand> brands = brandMapper.selectByCondition(map);
        System.out.println(brands);
        //5.释放资源
        sqlSession.close();
    }
2.动态查询

SQL语句会随着用户的输入或外部条件的变化而变化,我们称为动态SQL

<select id="selectByCondition"resultMap="brandResultMap">
    select  *
    from tb_brand
    where
            if(status!=null)
                      status =#status)
        and company name like #{companyName}
        and brand name like #{brandName)
<select>

MyBatis对动态SQL有很强大的支撑:

  • if

  • choose (when,otherwise)

  • trim (where,set)

  • foreach

2.1if查询
    <!--
    动态条件查询
        *if:条件判断
            *test:逻辑表达式
        *问题:第一个条件不需要逻辑运算符
            *恒等式
            *<where>替换where关键字
    -->
    <select id="selectByCondition" resultType="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>
2.2choose(when,otherwise)查询

从多个条件中选择个.

类似于Java中的switch语句

<select id="selectByConditionSingle"resultMap="brandResultMap">
    select
    from tb_brand
    where
    <choose><!-类似于switch->
        <when test=:"status=nul"><!-类似于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><I-类似于default->
            1=1
        </otherwise>
    </choose>
</select>
3.添加

1.编写接口方法:Mapper接口

  • 参数:除了id之外的所有数据

  • 结果:void

2.编写SQL语句:SQL映射文件

3.执行方法,测试

MyBatis事务:

  • openSession0:默认开启事务,进行增删改操作后需要使用sqlSession.commit0;手动提交事务

  • openSession(true):可以设置为自动提交事务(关闭事务)

    /**
     * 添加
     */
    void add(Brand brand);
    <insert id="add">
        insert into tb_brand (brand_name,company_name,ordered,description,status)
        values (#{brandName},#{companyName},#{ordered},#{description},#{status});
    </insert>
<insert id="add">
    insert into tb_brand (brand_name,company_name,ordered,description,status)    
    values (#{brandName},#{companyName},#{ordered},#{description},#{status});
</insert>
    @Test
    public void testAdd() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "菠萝手机";
        String brandName = "菠萝";
        String description = "菠萝手机,手机中的战斗机";
        int ordered = 100;
        
        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setDescription(description);
        brand.setOrdered(ordered);
        
        //1.获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        //方式一
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //方式二  自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        brandMapper.add(brand);
        //提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
3.1主键返回

在数据添加成功后,需要获取插入数据库数据的主键的值

  • 比如:添加订单和订单项

1.添加订单

2.添加订单项,订单项中需要设置所属订单的id

<insert id="add" useGeneratedKey="true" keyProperty="id">
    insert into tb_brand (brand_name,company_name,ordered,description,status)    
    values (#{brandName},#{companyName},#{ordered},#{description},#{status});
</insert>
    @Test
    public void testAdd2() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "菠萝手机";
        String brandName = "菠萝";
        String description = "菠萝手机,手机中的战斗机";
        int ordered = 100;
        
        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setDescription(description);
        brand.setOrdered(ordered);
        
        //1.获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        //方式一
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //方式二  自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        brandMapper.add(brand);
        Integer id = brand.getId();
        System.out.println(id);
        //提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }

返回添加数据的主键 <insert useGeneratedKeys="true"keyProperty="id">

4.修改
4.1修改全部字段

1.编写接口方法:Mapper接口

  • 参数:所有数据

  • 结果:void

2.编写SQL语句:SQL映射文件 3.执行方法,测试

    /**
     * 修改
     */
    
    int update(Brand brand);
<update id="update">
    update tb_brand
    set 
    brand_name=#{brandName},
    company_name=#{companyName},
    ordered=#{brandName},
    description=#{description},
    status=#{status}
    where id = #{id};
</update>
    @Test
    public void testUpdate() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "菠萝手机";
        String brandName = "菠萝";
        String description = "手机中的战斗机";
        int ordered = 200;
        int id = 5;
        
        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setDescription(description);
        brand.setOrdered(ordered);
        brand.setId(id);
        
        //1.获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        //方式一
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //方式二  自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        int count = brandMapper.update(brand);
        System.out.println(count);
        //提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
4.2修改动态字段

1.编写接口方法:Mapper接口

  • 参数:部分数据,封装到对象中

  • 结果:void

2.编写SQL语句:SQL映射文件 3.执行方法,测试

<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="ordered !=null">
            ordered=#{fordered},
        </if>
        <if test="description !=null and description !=''>
            description=#{description},
        </if>
        <if test="status !=null>
            status=#{status}
        </if>
    </set>
    where id #{id};
</update>
5.删除
5.1删除一个

1.编写接口方法:Mapper接口

  • 参数:id

  • 结果:void

2.编写SQL语句:SQL映射文件

3.执行方法,测试

    void deleteById(int id);
<delete id="deleteById">
    delete from tb_brand where id = #{id};
</delete>
    @Test
    public void testDeleteById() throws IOException {
        //接收参数
        int id = 6;
​
        //1.获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        //方式一
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //方式二  自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        brandMapper.deleteById(id);
        //提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
5.2批量删除

1.编写接口方法:Mapper接口

  • 参数:id数组

  • 结果:void

2.编写SQL语句:SQL映射文件

3.执行方法,测试

void deleteByIds(@Param("ids")int[]ids);

mybatis会将数组参数,封装为一个Map集合。 *默认:array=数组

*使用@Param注解改变map集合的默认key的名称

<delete id="deleteByIds">
    delete from tb_brand where id 
    in
        <foreach collection="array" separator="," open="(" close=")">
            #{id}
        </foreach>
    ;
</delete>
    @Test
    public void testDeleteByIds() throws IOException {
        //接收参数
        int ids = {5,7,8};
​
        //1.获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        //方式一
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //方式二  自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4.执行方法
        brandMapper.deleteByIds(ids);
        //提交事务
        sqlSession.commit();
        //5.释放资源
        sqlSession.close();
    }
6.MyBatis参数传递

MyBatis接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式

  • 单个参数:

    1.POO类型:直接使用,属性名和参数占位符名称一致 2.Map集合:直接使用,键名和参数占位符名称一到 3.Collection:封装为Map集合

    map.put("arg0",collection集合); map.put("collection",collection集合);

    4.List:封装为Map集合

    map.put("arg0",List集合): map.put("collection",List集合); map.put("List",List集合);

    5.Array:封装为Map集合

    map.put("argo",数组); map.put("array",数组);

    6.其他类型:直接使用

  • 多个参数:封装为Map集合

    map.put("arg0",参数值1)

    map.put("param1",参数值1)

    map.put("param2",参数值2)

    map.put("arg1",参数值2)

MyBatisj提供了ParamNameResolver类来进行参数封装

User select(String username,String password);
<select id="select"resultType="user">
    select *
    from tb_user
    where
        username = #{arg0}
    and password = #{arg1}
</select>
7.通过注解开发

使用注解开发会比配置文件开发更加方便

@Select("select from tb_user where id =#{id}")
public User seectByld(int id);


  • 查询:@Select

  • 添加:@Insert

  • 修改:@Update

  • 删除:@Delete

提示: 注解完成简单功能 配置文件完成复杂功能

使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java注解不仅力不从心,还会让你本就复杂的SQL语句更加混乱不堪。因此,如果你需要做一些很复杂的操作,最好用XML来映射语句 选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和XML的语句映射方式间自由移植和切换

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。