MyBatis核心配置文件与注解开发

MyBatis核心配置文件

1.环境配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
<!--    环境配置,默认选择,配置数据库连接环境信息,可以配置多个environmrnt,通过default属性切换-->
    <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://localhost:3306/test"/>
<!--                密码-->
                <property name="username" value="root"/>
<!--                这是你自己的数据库密码-->
                <property name="password" value="12345678"/>
            </dataSource>
        </environment>
<!--                测试环境-->
        <environment id="test">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--                数据库连接信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <!--                这是你自己的数据库密码-->
                <property name="password" value="12345678"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        加载sql映射文件-->
<!--        <mapper resource="com/itheima/mapper/UserMapper.xml"/>-->
<!--        mapper代理方式-->
        <package name="com.itheima.mapper"/>
    </mappers>
</configuration>

2.类型别名(typeAiases)

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

<typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
  <typeAlias alias="Blog" type="domain.blog.Blog"/>
  <typeAlias alias="Comment" type="domain.blog.Comment"/>
  <typeAlias alias="Post" type="domain.blog.Post"/>
  <typeAlias alias="Section" type="domain.blog.Section"/>
  <typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>

当这样配置时,Blog 可以用在任何使用 domain.blog.Blog 的地方。

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:

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

在这里插入图片描述

上面的resultType直接省略了包名

  • 注:配置别名的时候需要注意顺序

配置文件完成增删改查

环境准备:

1.安装MyBatisX插件

在IDEA的file-setting-plugins中搜索mybatisx,然后安装即可,可能需要适当重启IDEA

在这里插入图片描述

红色小鸟是映射文件,蓝色是Mapper接口,点击可以直接跳转

作用:

①如在映射文件中写上sql语句,点击后可以直接跳转到mapper接口方法中去

②在mapper中写好接口方法可以自动生成statement的标签

2.数据库表tb_brand.sql

-- 删除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;

3.实体类Brand.java

package com.itheima.pojo;

/**
 * 品牌
 *
 * alt + 鼠标左键:整列编辑
 *
 * 在实体类中,基本数据类型建议使用其对应的包装类型
 */

public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Integer getOrdered() {
        return ordered;
    }

    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}

4.测试用例

在test/java目录下创建com.itheima.test包,在包下创建一个测试类MyBatisTest.java,这只是环境准备。

增删改查

1.练习查询所有数据

1.编写接口方法Mapper接口
  • 参数:无
  • 结果:List

List<Brand> selectAll();

①在mapper包下创建BrandMapper接口

package com.itheima.mapper;

import com.itheima.pojo.Brand;

import java.util.List;

public interface BrandMapper {
    List<Brand> selectAll();
}
2.编写SQL语句:SQL映射文件

<select id="selectAll" resultType="brand">select * from tb_brand</select>

①在resources目录的mapper下创建映射文件:BrandMapper.xml,回到BrandMapper接口,创建statement

,然后书写sql语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
    namespace:名称空间
-->
<mapper namespace="com.itheima.mapper.BrandMapper">

    <select id="selectAll" resultType="brand">
        select * from tb_brand;
    </select>
</mapper>
3.执行方法:测试

在MyBatisTest中书写代码:

(在spring整合后只需要写 List<Brand> brands = brandMapper.selectAll();),然后进行测试

package com.itheima.test;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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完成操作的步骤:

三步:编写接口方法–>编写SQL语句–>执行方法

4.相关问题的解决
数据库表的字段名称和实体类的属性名称不一样,则不能自动封住数据

解决方案一:

起别名,让别名和实体类的属性名一样,缺点是每次查询都要定义一次别名

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
    namespace:名称空间
-->
<mapper namespace="com.itheima.mapper.BrandMapper">
<!--
    数据库表的字段名称和实体类的属性名称不一样,则不能自动封住数据
    * 解决方案:
    1.起别名,让别名和实体类的属性名一样,缺点是每次查询都要定义一次别名

-->

    <sql id="brand_column"></sql>

    <select id="selectAll" resultType="brand">
#         原始方法
#         select * from tb_brand;
#         起别名方法
        select id,brand_name as brandName,company_name as companyName,ordered,description,status from tb_brand;
    </select>
</mapper>

sql片段:


<!--
    sql片段
-->
    <sql id="brand_column">
        id,brand_name as brandName,company_name as companyName,ordered,description,status
    </sql>

    <select id="selectAll" resultType="brand">

#         起别名方法,使用sql片段
        select <include refid="brand_column"/> from tb_brand;
    </select>

解决方案二:

ResultMap

<!--    ResiltMap方法
        id:唯一标识
        type:映射的类型,支持别名
-->
    <resultMap id="brandResultMap"  type="brand">
<!--        对主键的映射-->
<!--        <id></id>-->
<!--        对一般字段的映射:result-->
<!--        column:表的列名-->
<!--        property:属性名;别名-->
        <result column="brand_name" property="brandName"></result>
        <result column="company_name" property="companyName"></result>
    </resultMap>
<!--    使用resultMap属性替换原本的resultType属性-->
    <select id="selectAll" resultMap="brandResultMap">
        select * from tb_brand;
    </select>

2.练习通过id查询

1.编写接口方法:Mapper接口
  • 参数:id
  • 结果:Brand
2.编写SQL语句:SQL映射文件
<!--    * 参数占位符:-->
<!--        1.#{}:会替换成?,相当于PrepareStatement,可以防止sql注入-->
<!--        2.${}:不会换成?,而是直接等号替换,存在sql注入问题-->
<!--        2.使用时机:-->
<!--            一般使用#{}-->
<!--            表名或者列名不固定时使用${}-->
    
<!--        参数类型:parameterType:可以省略,会一直往上找数据类型-->
<!--        特殊字符的处理:-->
<!--            1.转义字符:&lt;  &gt;-->
<!--            2.CDATA区:<![CDATA[  <或者 > ]]>-->
    
    <select id="selectById" parameterType="int" resultMap="brandResultMap">
        select *
        from tb_brand where id=#{id};
    </select>
3.执行方法测试

3.条件查询

1.多条件查询

1.编写接口方法

  • 参数:所有查询条件
  • 结果:List
    /**
     * 条件查询
     * 1.散装参数:如果方法中有多个参数,需要使用@Param("SQL占位符名称")
     * 2.对象参数:对象的属性名称要与参数占位符名称一致
     * 3.map集合参数
     */
//    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);

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

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

3.执行方法,测试

    @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);

        //封装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);
//        List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
        System.out.println(brands);

        //5.释放资源
        sqlSession.close();

    }
相关问题:

如果某一个条件为空,就会出现问题

4.动态条件查询(多条件)

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

2.MyBatis对动态SQL的支撑:

  • if–
    
<select id="selectByCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        where
              <if test="status!=null">
                  status=#{status}
              </if>
#             这里写属性值而不是数据库里面的字段,test是逻辑表达式
    #这里有一个问题就是如果第一个条件不存在,and就会使SQL语句报错
    #解决方案:1.添加一个恒等式:1=1,为了满足语法条件
    #		 2.使用where标签
    
            <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>

使用where标签:

#         where,这里的where需要注释掉
#             1 = 1
            <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>

5.单条件动态条件查询

  • choose(when,otherwise)
<!--    单条件动态查询-->
    <select id="selectByConditionSingle" resultMap="brandResultMap">
        select *
        from tb_brand
            <!--防止用户都不选择-->
        <where>
<!--         相当于switch-->
        <choose>
                     <!--相当于case-->
            <when test="status!=null">
                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>-->
<!--                &lt;!&ndash;相当于default,防止用户都没有选择&ndash;&gt;-->
<!--                1=1-->
<!--            </otherwise>-->

        </choose>
        </where>
    </select>

6.添加

1.添加方法

    /**
     * 添加
     */
    void add(Brand brand);

2.SQL映射

<!--    添加-->
    <insert id="add">
        insert into tb_brand(brand_name, company_name, ordered, description, status)
        values(#{brandName},#{brandName},#{ordered},#{description},#{status})
    </insert>

3.测试方法(注意提交事务)


    @Test
    public void testAdd() throws IOException {
        //接受参数
        int status=1;
        String companyName="波导手机";
        String brandName="波导";
        String description = "手机中的战斗机";
        int orderd=100;

        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setDescription(description);
        brand.setOrdered(orderd);

        //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();

    }
  • 添加–主键返回

1.修改映射,添加两个属性useGenerateKeyskeyProperty

<!--    添加-->
    <insert id="add" useGeneratedKeys="true" keyProperty="id">
        insert into tb_brand(brand_name, company_name, ordered, description, status)
        values(#{brandName},#{brandName},#{ordered},#{description},#{status})
    </insert>

2.在测试方法提交后可以获取到id属性

        //4.执行方法
        brandMapper.add(brand);
        System.out.println(brand.getId());

7.修改

  • 修改全部字段

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

参数:所有数据

结果:void

/**
     * 修改,如果返回值是int表示影响行数,void表示不返回
     */
    int update(Brand brand);

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

<!--    修改-->
    <update id="update">
        update tb_brand
        set brand_name=#{brandName},
            company_name=#{companyName},
            ordered=#{ordered},
            description=#{description},
            status=#{status}
        where id=#{id};

    </update>

3.执行方法:测试

    @Test
    public void testupdate() throws IOException {
        //接受参数
        int status=1;
        String companyName="波导手机";
        String brandName="波导";
        String description = "波导手机,手机中的战斗机";
        int orderd=200;

        int id=7;

        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setDescription(description);
        brand.setOrdered(orderd);

        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();

    }
  • 修改动态字段–修改部分字段(如:只需要修改密码)

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

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

结果:void/int

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

主要是标签和标签的使用

    <!--    修改-->
    <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=#{ordered},
            </if>
            <if test="description!=null and description!=''">
                description=#{description},
            </if>
            <if test="status!=null">
                status=#{status}
            </if>
        </set>

        where id=#{id};

    </update>

3.执行方法:测试

tips:Ctrl+Alt+L格式化代码

8.删除

  • 删除单个

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

参数:id

结果:void/int

    /**
     * 通过id删除数据
     */
    void deleteById(Brand brand);

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


    <!--    通过id删除-->

    <delete id="deleteById">
        delete from tb_brand where id=#{id}
    </delete>

3.执行方法,测试

    @Test
    public void testdeleteById() throws IOException {
        //接受参数
        int id=6;

        //封装对象
        Brand brand = new Brand();
        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.执行方法
        brandMapper.deleteById(brand);

        //手动提交事务
//        sqlSession.commit();

        //5.释放资源
        sqlSession.close();

    }
  • 批量删除

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

参数:id数组

结果:void


    /**
     * 通过id批量删除
     * @param ids
     */
    void deleteByIds(@Param("ids") int[] ids);

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

    <!--    mybtatis会将数组参数,封装为一个Map集合-->
    <!--    默认:array=数组-->
    <!--    或者使用@Params("arrayname")修改集合默认名称-->
    <!--    seperator表示分隔符-->
    <delete id="deleteByIds">
        delete from tb_brand where id in
        <!--    (-->
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
        <!--         )-->
    </delete>

3.执行方法:测试

  @Test
    public void testdeleteByIds() throws IOException {
        //接受参数
        int[] ids = {5, 7};

        //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();

    }

参数传递

1.在UserMapper中写下以下方法(知识点在注释里面)

/**
     * Mybatis参数封装
     * 单个参数:
     * 1.POJO类,直接使用,属性名和参数占位符名称一致
     * 2.Map集合,直接使用,键名和参数占位符名称一致
     * 3.Collection:疯转为Map集合,可以使用@Param注解
     * map.put("arg0",collection集合)
     * map.put("collection",collection集合)
     * 4.List,封装为Map集合,可以使用@Param注解
     * map.put("arg0",list集合)
     * map.put("collection",List集合)
     * map.put("list",List集合)
     * 5.Array封装为map集合,可以使用@Param注解
     * map.put("arg0",数组)
     * map.put("array",数组)
     * 6.其他类型,直接使用
     * 多个参数:封装为Map集合,可以使用@Param注解,替换集合注解中默认的arg键名
     * map.put("arg0",参数值1)
     * map.put("param1",参数值1)
     * map.put("param2",参数值2)
     * map.put("arg1",参数值2)
     * ------------@Param
     * map.put("username",参数值1)
     * map.put("param1",参数值1)
     * map.put("param2",参数值2)
     * map.put("password",参数值2)
     *
     * 结论:使用@Param注解修改Map集合中的默认键名
     */
    User select(@Param("username") String username, @Param("password") String password);

    User select(Collection collection);

2.写相应映射

  <select id="select" resultType="User">
        select *
        from t_user
        where username=#{username}
        and password=#{password}
    </select>

3.测试方法

    @Test
    public void testselect() throws IOException {
        //接受参数
       String username="admin";
       String password="admin";

        //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接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);


        //4.执行方法
//        User user = userMapper.select(username, password);
        User user = userMapper.select(new HashSet());
        System.out.println(user);


        //手动提交事务
//        sqlSession.commit();

        //5.释放资源
        sqlSession.close();

    }
  • 相关知识点解读,在源码中查看相应操作:

    ①在IDEA中快速点击两下Shift键进入搜索,搜索ParamNameResolver.class文件,注意要搜索文件,没有源码需要下载源码

    ②找到getNamedParams方法,在第一行加断点

在这里插入图片描述

​ ③调试测试方法,细品里面的方法,通过步入进入下一步,查看变量

​ ④里面有个wrapToMapCollection方法需要注意,Ctrl+鼠标左键点进去后在第一行添加断点

在这里插入图片描述

注解开发

官网解释:

​ 使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。

​ 所以,注解可以完成简单开发,XML适合复杂一点的开发

1.注解开发不要写xml文件,所以通过在Mapper接口中点击小红鸟把UserMapper.xml文件中相应方法selectById注释掉

在这里插入图片描述

2.在UserMapper方法中添加注解

    @Select("select * from t_user where id=#{id}")
    User selectById(int id);

3.测试方法


    @Test
    public void testselectById() 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();
//        开启自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //3.获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);


        //4.执行方法

        User user = userMapper.selectById(1);
        System.out.println(user);


        //手动提交事务
//        sqlSession.commit();

        //5.释放资源
        sqlSession.close();

    }

4.此外共有四种注解,在注解里面填写相应的简单sql语句即可:

  • 查询@Select
  • 添加@Insert
  • 修改@Update
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值