JavaWeb核心笔记(持续更新)-JavaWeb原来这么简单!

Maven

Maven简介

Maven是专门用于管理和创建Java项目的工具,它的主要功能有:

  1. 提供了一套标准化的项目结构
    请添加图片描述

  2. 提供了一套标准化的构建流程(编译,测试,打包,发布…)

  3. 提供了一套依赖管理机制

Maven模型
请添加图片描述

仓库分类

  • 本地仓库:自己计算机上的一个目录
  • 中央仓库:由Maven团队维护的全球唯一的仓库
  • 远程仓库(私服):一半由公司团队搭建的私有仓库

当项目中使用坐标引入对应依赖jar包后,首先会查找本地仓库是否有对应的jar包:如果有,则在项目中直接引用;如果没有,则去中央仓库中下载对应的jar包到本地仓库。

还可以搭建远程仓库,将来jar包的查找顺序则变为:本地仓库->远程仓库->中央仓库

Maven的基本使用

Maven常用命令
  • compile:编译(生成target)
  • clean:清理(清除target)
  • test:测试(运行test目录下的代码)
  • package:打包(打成jar包)
  • install:安装(到本地仓库)
Mavn生命周期

Maven构建项目生命周期描述的是第一次构建过程经历经历了多少个事件

Maven对项目构建的生命周期划分为3套

  • clean:清理工作
    请添加图片描述

  • default:核心工作,例如编译,测试,打包,安装等

请添加图片描述

  • site:产生报告,发布站点等

请添加图片描述

同一生命周期内,执行后边的命令,前边的所有命令会自动执行

附表:

请添加图片描述

Maven坐标详解

Maven中的坐标是资源的唯一标识,使用坐标来定义项目或引入项目中需要的依赖

Maven坐标主要组成

  • groupld:定义当前Maven项目隶属组织名称(通常是域名反写,例如com.example)
  • artifactld:定义当前Maven项目名称(通常是模块名称,例如order-service、goods-service)
  • version:定义当前项目版本号

请添加图片描述

请添加图片描述

依赖管理

使用坐标导入jar包

1.在pom.xml中编写标签

2.在标签中使用引入坐标

定义坐标的groupld,artifactld,version

4.点击刷新按钮使坐标生效

依赖范围

通过设置坐标的依赖范围(scope),可以设置对应jar包的作用范围:编译环境、测试环境、运行环境

<dependency>
    <groupeId>junit</groupeId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>

请添加图片描述

默认值:compile

编译环境:主工程(main)的java目录下

测试环境:test目录下所有类

运行环境:打包后lib中有无对应jar包

MyBatis

简介

MyBatis是一款优秀的持久层框架,用于简化JDBC开发。

持久层:负责将数据保存到数据库的那一层代码。JavaEE三层架构:表现层(页面展示)、业务层(逻辑处理)、持久层(数据持久化)。

框架:框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型。在框架的基础之上构建软件编写更加高效、规范、通用、可扩展

步骤

查询user表中所有数据

  1. 创建user表,添加数据

  2. 创建模块,导入坐标

    <!--pom.xml-->
    <dependencies>
            <!--mybatis依赖-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.13</version>
            </dependency>
    
            <!--mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.32</version>
            </dependency>
    
            <!--junit单元测试-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <scope>test</scope>
            </dependency>
    
            <!--添加slf4j日志api-->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>2.0.5</version>
            </dependency>
    
            <!--添加logback-core依赖-->
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
                <version>1.4.6</version>
            </dependency>
    
            <!--添加logback-classic依赖-->
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>1.4.6</version>
            </dependency>
        </dependencies>
    

    logback除了坐标信息,还需要在main中的resource添加logback.xml配置文件:

    <!--logback.xml-->
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <!--
            CONSOLE :表示当前的日志信息是可以输出到控制台的。
        -->
        <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>【%level】 %blue(%d{HH:mm:ss.SSS}) %cyan(【%thread】) %boldGreen(%logger{15}) - %msg %n</pattern>
            </encoder>
        </appender>
    
        <logger name="com.hello" level="DEBUG" additivity="false">
            <appender-ref ref="Console"/>
        </logger>
    
        <root level="DEBUG">
            <appender-ref ref="Console"/>
        </root>
    </configuration>
    
  3. 编写Mybatis核心配置文件 --> 替换连接信息 解决硬编码问题

    在main中的resource添加mybatis-config.xml配置文件:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <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>
        <!--指定当前SQL映射文件路径-->
        <mappers>
            <!--加载SQL映射文件-->
            <mapper resource="UserMapper.xml"/>
        </mappers>
    </configuration>
    
  4. 编写SQL映射文件 --> 统一管理sql语句,解决硬编码问题

    在main中的resource添加 表名Mapper.xml配置文件(UserMapper.xml):

    <?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="test">
        <select id="selectAll" resultType="com.hellhyo.pojo.User">  <!--resultType即要返回的类型-->
            select * from tb_user;
        </select>
    </mapper>
    
  5. 编码

    1. 定义POJO类

      创建User类

    2. 加载核心配置文件,获取SqlSessionFactory对象

    3. 获取SqlSession对象,执行SQL语句

    4. 释放资源

    public static void main(String[] args) throws IOException {
            //1.加载Mybatis核心配置文件,获取SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
            //2.获取SqlSessionFactory对象,用它执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
    
            //3.执行sql语句
            List<User> users = sqlSession.selectList("test.selectAll");//namespace.id
    
            System.out.println(users);
    
            //4.释放资源
            sqlSession.close();
        }
    

解决SQL映射文件警告提示(在idea中配置MySQL数据库连接)

请添加图片描述
请添加图片描述

可编写SQL语句并运行

请添加图片描述

Mapper代理开发

目的:1.解决原生方法中的硬编码问题;2.简化后期执行SQL

步骤:

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

请添加图片描述

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

请添加图片描述

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

请添加图片描述

  1. 编码

    1. 通过SqlSession的getMapper方法获取Mapper接口的代理对象

      //3.获取UserMapper接口的代理对象
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
              List<User> users = userMapper.selectAll();
      
    2. 调用对应方法完成sql的执行

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

请添加图片描述

Mybatis核心配置文件

Mybatis核心配置文件的顶层结构如下:

请添加图片描述

类型别名(typeAliases):

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

注意:配置各个标签时,需要注意前后顺序,即顶层结构顺序

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

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

    <!--
    environment:配置数据库连接环境信息,可以配置多个environment,通过default属性切换不同的environment(指向对应environment的id)
    -->
    <environments default="development">
        <environment id="test">
            <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>

        <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>
    <!--指定当前SQL映射文件路径-->
    <mappers>
        <!--加载SQL映射文件-->
        <!--<mapper resource="com/hellhyo/mapper/UserMapper.xml"/>-->

        <!--Mapper代理方法-->
        <package name="com.hellhyo.mapper"/>
    </mappers>
</configuration>

Mybatis案例

配置文件完成增删改查
环境准备
  1. 数据库表

  2. 实体类

  3. 测试用例

  4. 安装MyBatisX插件

    主要功能:

    • XML和接口方法相互跳转
    • 更具接口方法生成statement

请添加图片描述

查询

查询所有数据

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

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

    <?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">
    <mapper namespace="com.hellhyo.mapper.BrandMapper">
        <!--
        数据库表的字段名称 和 实体类的属性名称 不一样,则不能自动封装数据
            *起别名:对不一样的列名起别名,让别名和实体类的属性名一样
                *缺点:每次查询都要定义一次别名
                    *sql片段
                        *缺点:不灵活
            *resultMap:
                1.定义<resultMap>标签
                2.在<select>标签中使用resultMap属性替换resultType属性
        -->
        <!--
            id:唯一标识
            type:映射的类型,支持别名
        -->
        <resultMap id="brandResultMap" type="com.hellhyo.pojo.Brand">
            <!--id是来完成主键字段的映射,result是来完成一般字段的映射-->
            <!--column为数据库中列名,property为实体类对应属性名-->
            <result column="brandName" property="brandName"/>
            <result column="companyName" property="companyName"/>
        </resultMap>
        <select id="selectAll" resultMap="brandResultMap">
            select
            *
            from tb_brand;
        </select>
    
        <!--定义sql片段
        <sql id="brand_column">
            id, brandName as brandName, companyName as companyName, ordered, description, status
        </sql>
        <select id="selectAll" resultType="com.hellhyo.pojo.Brand">
            select
                <include refid="brand_column"/>
            from tb_brand;
        </select>
        -->
    
        <!--常规方法
        <select id="selectAll" resultType="com.hellhyo.pojo.Brand">
            select id from tb_brand;
        </select>
        -->
    </mapper>
    
  3. 执行方法,测试

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

实体类属性名和数据库表列名不一致,不能自动封装数据

  1. 起别名:在sql语句中,对不一样的列名起别名,别名和实体类属性名一样

    *可以定义片段,提升复用性

  2. resultMap:定义完成不一致的属性名和列名的映射

查看详情

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

    • 参数:id
    • 结果:Brand
    public interface BrandMapper {
        //查询所有
        List<Brand> selectAll();
    
        //查看详情
        Brand selectById(int id);
    }
    
  2. 编写SQL语句:SQL映射文件

    <!--
            *参数占位符:
                1.#{} : 会将其替换为?,为了防止sql注入
                2.${} :拼sql,会存在sql注入问题
                3.使用时机:
                    *参数传递时:#{}
                    *表名或列名不固定的情况下:${}
    
            *参数类型:parameterType(可以省略)
            *特殊字符处理:
                1.转义字符:'<' -> '&lt;'
                2.CDATA区:CD提示
                    <![CDATA[
                        特殊字符
                    ]]>
        -->
    <select id="selectById" parameterType="int" resultMap="brandResultMap">
        select * from tb_brand where id
        <![CDATA[
            <
            ]]>
        #{id};
    </select>
    
  3. 执行方法,测试

    @Test
        public void testSelectById() throws IOException {
            //接收参数
            int id = 1;
    
            //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.执行方法
            Brand brand = brandMapper.selectById(id);
            System.out.println(brand);
    
            //5.释放资源
            sqlSession.close();
        }
    

参数占位符:
​ 1.#{} : 会将占位符替换为?,将来自动设置参数值,为了防止sql注入
​ 2.KaTeX parse error: Expected 'EOF', got '#' at position 67: … *参数传递时:#̲{} ​ …{}

参数类型:parameterType(用于设置参数类型,可以省略)

SQL语句中特殊字符处理:
​ *转义字符:‘<’ -> ‘<’
​ *CDATA区:CD提示:<![CDATA[特殊字符]]>

条件查询

  1. 多条件查询

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

      • 参数:所有查询条件
      • 结果:List
      //条件查询
      /*
          * 参数接收
          *   1.散装参数:如果方法中有多个参数,需要使用@Param("SQL参数占位符名称")注解来标注参数的值
          *   2.对象参数:对象属性名称要和参数占位符名称一致,才能封装上对应参数的值
          *   3.Map集合参数:sql中的参数名和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
                  companyName like #{companyName} and
                  brandName 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.setBrandName(brandName);
          brand.setCompanyName(companyName);
      
          //封装对象 - 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(status, companyName, brandName);
          System.out.println(brands);
      
          List<Brand> brands1 = brandMapper.selectByCondition(brand);
          System.out.println(brands1);
      
          List<Brand> brands2 = brandMapper.selectByCondition(map);
          System.out.println(brands2);
      
          //5.释放资源
          sqlSession.close();
      }
      
  2. 多条件-动态条件查询

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

    <!--动态条件查询
            *if:条件判断
                *test:逻辑表达式
            *问题:第一个条件不需要逻辑运算符
                *恒等式
                *<where> 替换 where 关键字
        -->
    <select id="selectByCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        /*where 1 = 1*/
        <where>
            <if test="status != null">
                and status = #{status}
            </if>
            <if test="companyName != null and companyName != '' ">
                and companyName like #{companyName}
            </if>
            <if test="brandName != null and brandName != '' ">
                and brandName like #{brandName}
            </if>
        </where>
    </select>
    

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

    • if
    • choose(when, otherwise)
    • trim(where, set)
    • foreach
  3. 单条件-动态条件查询

    从多个条件中选择一个

    choose(when, otherwise):选择,类似于Java中的switch语句

    <select id="selectByConditionSingle" resultMap="brandResultMap">
        select *
        from tb_brand
        <where>
            <choose><!--相当于switch-->
                <when test="status != null">
                    status = #{status}
                </when><!--相当于case-->
                <when test="companyName != null and companyName != ''">
                    companyName like #{companyName}
                </when>
                <when test="brandName != null and brandName != ''">
                    brandName like #{brandName}
                </when>
                <!--<otherwise>
                        1 = 1
                    </otherwise>-->
            </choose>
        </where>
    </select>
    
    @Test
    public void testSelectByConditionSingle() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "华为";
        String brandName = "华为";
    
        //处理参数
        companyName = "%" + companyName + "%";
        brandName = "%" + brandName + "%";
    
        //封装对象 - 对象参数
        Brand brand = new Brand();
        //        brand.setStatus(status);
        //        brand.setBrandName(brandName);
        //        brand.setCompanyName(companyName);
    
        //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.selectByConditionSingle(brand);
        System.out.println(brands);
    
        //5.释放资源
        sqlSession.close();
    }
    
添加

添加

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

    void add(Brand brand);
    
    • 参数:除了id之外的所有数据
    • 结果:void
  2. 编写SQL语句:SQL映射文件

    <!--添加-->
    <insert id="add">
        insert into tb_brand (brandName, companyName, ordered, description, status)
        values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
    </insert>
    
  3. 执行方法,测试

    @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.setBrandName(brandName);
        brand.setCompanyName(companyName);
        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();  //括号内设置为true表示自动提交事务,则之后不需要手动提交
    
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    
        //4.执行方法
        brandMapper.add(brand);
    
        //5.提交事务(手动)
        sqlSession.commit();
    
        //6.释放资源
        sqlSession.close();
    }
    

MyBatis事务:

  • openSession():默认开启事务,进行增删改操作后需要使用sqlSession.commit();手动提交事务
  • openSession(true):可以设置为自动提交事务(关闭事务)

主键返回

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

<insert id="add" useGeneratedKeys="true" keyProperty="id">
修改

修改全部字段

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

    void update(Brand brand);
    
    • 参数:所有数据
    • 结果:void
  2. 编写SQL语句:SQL映射文件

    <update id="update">
        update tb_brand
        set
        brandName = #{brandName},
        companyName = #{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 ordered = 200;
        int id = 1;
    
        //封装对象 - 对象参数
        Brand brand = new Brand();
        brand.setStatus(status);
        //        brand.setBrandName(brandName);
        //        brand.setCompanyName(companyName);
        //        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();  //括号内设置为true表示自动提交事务,则之后不需要手动提交
    
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    
        //4.执行方法
        int count = brandMapper.update(brand);
        System.out.println(count);
        //5.提交事务(手动)
        sqlSession.commit();
    
        //6.释放资源
        sqlSession.close();
    }
    

修改动态字段

SQL映射文件

<!--修改动态字段-->
<update id="update">
    update tb_brand
    <set>
        <if test="brandName != null and brandName != ''">
            brandName = #{brandName}
        </if>
        <if test="companyName != null and companyName != ''">
            companyName = #{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>
删除

删除一个

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

    void deleteById(int id);
    
    • 参数:id
    • 结果:void
  2. 编写SQL语句:SQL映射文件

    <!--删除一个-->
    <delete id="deleteById">
        delete
        from tb_brand
        where id = #{id};
    </delete>
    
  3. 执行方法,测试

    @Test
    public void testDeleteById() throws IOException {
        //接收参数
        int id = 4;
    
        //1.获取SqlSessionFactory对象,加载核心配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();  //括号内设置为true表示自动提交事务,则之后不需要手动提交
    
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    
        //4.执行方法
        brandMapper.deleteById(id);
    
        //5.提交事务(手动)
        sqlSession.commit();
    
        //6.释放资源
        sqlSession.close();
    }
    

批量删除

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

    void deleteByIds(int[] id);
    
    • 参数:ids[]
    • 结果:void
  2. 编写SQL语句:SQL映射文件

    <!--
            mybatis会将数组参数封装为一个map集合
                *默认: array = 数组
                *使用@Param注解改变map集合的默认key的名称
        -->
    <delete id="deleteByIds">
        delete
        from tb_brand
        where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">  <!--collection:集合名称;item:每个元素;separator:分隔符-->
            #{id}
        </foreach>
        ;
    </delete>
    
  3. 执行方法,测试

    @Test
    public void testDeleteByIds() throws IOException {
        //接收参数
        int ids[] = {1, 2};
    
        //1.获取SqlSessionFactory对象,加载核心配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();  //括号内设置为true表示自动提交事务,则之后不需要手动提交
    
        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    
        //4.执行方法
        brandMapper.deleteByIds(ids);
    
        //5.提交事务(手动)
        sqlSession.commit();
    
        //6.释放资源
        sqlSession.close();
    }
    
注解完成增删改查

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

@select("select * from tb_user where id = #{id}")
public User selectById(int id);
  • 查询:@Select
  • 添加:@Insert
  • 修改:@Update
  • 删除:@Delete

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

MyBatis参数传递

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

  • 单个参数:

    1. POJO类型:直接使用,实体类属性名要和参数占位符名称一致

    2. Map集合:直接使用,键名要和参数占位符名称一致

    3. Collection:封装为Map集合,可以使用@Param注解设置对应参数名称,替换Map集合中默认的键名

      map.put(“arg0”,collection集合);
      
      map.put(“collection”,collection集合);
      
    4. List:封装为Map集合,可以使用@Param注解设置对应参数名称,替换Map集合中默认的键名

      map.put(“arg0”,list集合);
      
      map.put(“collection”,list集合);
      
      map.put(“list”,list集合);
      
    5. Array:封装为Map集合,可以使用@Param注解设置对应参数名称,替换Map集合中默认的键名

      map.put(“arg0”,数组);
      map.put(“array”,数组);
      
    6. 其他类型:直接使用

  • 多个参数:封装为Map集合,可以使用@Param注解设置对应参数名称,替换Map集合中默认的键名

    map.put(“arg0”,参数值1);
    map.put(“param1”,参数值1);
    map.put(“param2”,参数值2);
    map.put(“arg1”,参数值2);
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值