JavaWeb基础学习总结(上)

225 阅读14分钟

来源:www.bilibili.com/video/BV1Qf…

JavaWeb介绍

网页:展现数据
数据库:存储和管理数据
JavaWeb程序:逻辑处理 image.png

数据库

一、数据库相关概念

1、数据库:存储数据,有组织的存储,DataBase,简称DB;
2、数据库管理系统:管理数据库的大型软件,DataBase Management System,简称DBMS;
3、SQL,结构化查询语言,Structured Query Language,操作关系型数据库的编程语言,定义操作所有关系型数据库的统一标准。

image.png

二、MySQL数据库

关系型数据库

关系型数据库是建立在关系模型基础上的数据库,简单说,关系型数据库是由多张能互相连接的二维表组成的数据库

image.png 优点:

  • 表结构,格式一致,易于维护。
  • 使用通用的SQL语言操作,使用方便,可用于复杂查询。
  • 数据存储在磁盘中,安全。

MySQL数据模型 image.png

三、SQL

简介

英文: Structured Query Language,简称SQL
结构化查询语言,一门操作关系型数据库的编程语言,定义操作所有关系型数据库的统一标准。
对于同一个需求,每一种数据库操作的方式可能会存在一些不一样的地方,我们称为“方言”

SQL通用语法
SQL语句可以单行或多行书写,以分号结尾。
MySQL数据库的SQL语句不区分大小写,关键字建议使用大写。

注释

  • 单行注释:--注释内容 或 #注释内容(MySQL特有)
  • 多行注释: / * 注释 * /

SQL分类
定义、操作、查询、控制 image.png

DDL 定义操作数据库

  • 1、查询show databases;
  • 2、创建
    create database 数据库名;
    create database if not exists 数据库名;
  • 3、删除
    drop database 数据库名;
    drop database if exists 数据库名;
  • 4、使用数据库
    查看当前使用的数据库select database();
    使用数据库use 数据库名;

DDL 定义操作表

  • 1、查询表 show
    查询当前数据库下所有表的名称 show tables;
    查询表结构desc 表名
  • 2、创建表 create
    image.png

数据类型很多,可以分为三类:数值、日期、字符串 image.png image.png

  • 3、删除 drop
    drop table 表名;
    drop table if exists 表名;
  • 4、修改 alter
    修改表名alter table 表名 rename to 新表名;
    添加一列alter table 表名 add 列名 数据类型;
    修改数据类型alter table 表名 modify 列名 新数据类型;
    修改列名和数据类型alter table 表名 change 列名 新列名 新数据类型;
    删除列alter table 表名 drop 列名;

图形化客户端工具 image.png

DML 操作数据

  • 1、添加数据 insert
    给指定列添加数据 insert into 表名(列名1,列名2..) values (值1,值2...);
    给全部列添加数据insert into 表名 values(值1,值2);
    给指定列批量添加数据insert into 表名(列名1,列名2...) values(值1,值2..),(值1,值2..),(值1,值2..)...;
    给全部列批量添加数据insert into 表名 values(值1,值2..),(值1,值2...),(值1,值2..)...;
  • 2、修改数据 update update 表名 set 列名1=值1,列名2=值2,,,[where 条件]; 如果不加条件,所有数据都被修改!
  • 3、删除数据 delete delete from 表名 [where 条件]; 如果不加条件,所有数据都会删除!

DQL 查询数据

image.png

1、基础查询

  • 查询多个字段select 字段列表 from 表名;
  • 查询所有数据select * from 表名;
  • 去除重复记录 select distinct 字段列表 from 表名;
  • 起别名as

2、条件查询where

select 字段列表 from 表名 where 条件列表;
条件: image.png

3、分组查询group by

聚合函数:把一列数据作为一个整体,纵向计算。
select 聚合函数名(列名) from 表; image.png image.png 分组查询:select 字段列表 from 表名 [where 分组前条件限定] group by 分组字段名 [having 分组后条件过滤];
分组之后,查询的字段为聚合函数和分组字段,查询其他字段无任何意义。执行顺序:where>聚合函数>having image.png

4、排序查询order by

select 字段列表 from 表名 order by 排序字段名1 [排序方式1],排序字段名2,[排序方式2]...;
排序方式:asc升序排列(默认)、desc降序排列
如果多个排序条件,当前边的条件值一样时,才会根据第二条件排序

5、分页查询limit

select 字段列表 from 表名 limit 起始索引,查询条目数; 索引从0开始。 image.png 分页查询limit是MySQL数据库的方言. Oracle分页查询使用rownumber. SQL Server分页查询使用top。

四、数据库

一、约束

约束的概念:
约束是作用于表中列上的规则,用于限制加入表的数据。约束的存在保证了数据库中数据的正确性、有效性和完整性。

约束的分类
Tips: MySQL不支持检查约束 image.png 外键约束 image.png

二、数据库设计

数据库设计简介
软件的研发步骤: image.png

数据库设计就是根据业务系统的具体需求,结合我们所选用的DBMS,为这个业务系统构造出最优的数据存储模型。建立数据库中的表结构以及表与表之间的关联关系的过程。有哪些表?表里有哪些字段?表和表之间有什么关系?

数据库设计的步骤

  • 需求分析(数据是什么?数据具有哪些属性?数据与属性的特点是什么)
  • 逻辑分析(通过ER图对数据库进行逻辑建模,不需要考虑我们所选用的数据库管理系统)
  • 物理设计(根据数据库自身的特点把逻辑设计转换为物理设计)
  • 维护设计(对新的需求进行建表;表优化)

表关系

  • 表关系之一对多 image.png 实现方式:在多的一方建立外键,指向一的一方的主键 image.png
  • 表关系之多对多 image.png 实现方式:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键 image.png
  • 表关系之一对一(常用于拆分不常用字段) image.png 实现方式:在任意一方加入外键,关联另一方主键,并且设置外键为唯一(UNIQUE) image.png 数据库设计案例

image.png

三、多表查询

笛卡儿积image.png 多表查询image.png

  • 内连接 image.png image.png
  • 外连接 image.png image.png

子查询

子查询概念:
查询中嵌套查询,称嵌套查询为子查询

子查询根据查询结果不同,作用不同:
·单行单列 image.png ·多行单列 image.png ·多行多列 image.png

四、事务

数据库的事务(Transaction)是一种机制、一个操作序列,包含了一组数据库操作命令。事务把所有的命令作为一个整体一起向系统提交或撤销操作请求,即这一组数据库命令要么同时成功,要么同时失败。事务是一个不可分割的工作逻辑单元。 BEGIN;COMMIT;ROLLBACK;

事务四大特征: image.png MySQL事务默认自动提交 image.png

JDBC

一、JDBC简介

JDBC概念:
JDBC就是使用Java语言操作关系型数据库的一套API。全称:(Java DataBase Connectivity) Java数据库连接
JDBC本质:
官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口。各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类。
JDBC 好处:
各数据库厂商使用相同的接口,Java代码不需要针对不同数据库分别开发。可随时替换底层数据库,访问数据库的Java代码基本不变。

image.png

二、JDBC快速入门

image.png

//        1、注册驱动
        Class.forName("com.mysql.jdbc.Driver");
//        2、获取连接 DriverManager
        String url="jdbc:mysql://localhost:3306/db1?useSSL=false";
        String user="root";
        String password="123456";
        Connection conn = DriverManager.getConnection(url,user,password);
//        3、定义SQL
        String sql = "UPDATE account SET money=3000 WHERE id=1;";
//        4、获取执行SQL的对象 Statement
        Statement stmt = conn.createStatement();
//        5、执行SQL
        int count = stmt.executeUpdate(sql);
//        6、处理结果
        System.out.println("受影响的行数:"+count);
//        7、释放资源
        stmt.close();
        conn.close();

三、JDBC API详解

DriverManager

作用:

  • 1、注册驱动
Class.forName("com.mysql.jdbc.Driver");

image.png 提示:
MySQL 5之后的驱动包,可以省略注册驱动的步骤。自动加载jar包中META-INF/services/java.sql.Driver文件中的驱动类。

  • 2、获取数据库连接 image.png

image.png

Connection

作用:

  • 1、获取执行SQL的对象

image.png

  • 2、管理事务 image.png
try {
    conn.setAutoCommit(false);
    int count1 = stmt.executeUpdate(sql1);
    System.out.println("受影响的行数:"+count1);
    count1=count1/0;//出错会回滚到最初的状态
    int count2 = stmt.executeUpdate(sql2);
    System.out.println("受影响的行数:"+count2);
    conn.commit();
} catch (SQLException e) {
    conn.rollback();
    throw new RuntimeException(e);
}

Statement

作用:执行SQL语句 image.png

@Test//执行DML语句 对数据的操作
public void testDML() throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    String url="jdbc:mysql:///db1?useSSL=false";
    String user="root";
    String password="123456";
    Connection conn = DriverManager.getConnection(url,user,password);
    String sql = "UPDATE account SET money=9999 WHERE id=1;";
    Statement stmt = conn.createStatement();
    int count = stmt.executeUpdate(sql);//执行完DML语句 受影响的行数
    if(count>0){
        System.out.println("修改成功!");
    }else {
        System.out.println("修改失败!");
    }
    stmt.close();
    conn.close();
}
@Test//执行DDL语句 对库和表的操作
public void testDDL() throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    String url="jdbc:mysql:///db1?useSSL=false";
    String user="root";
    String password="123456";
    Connection conn = DriverManager.getConnection(url,user,password);
    String sql = "drop database db2;";
    Statement stmt = conn.createStatement();
    int count = stmt.executeUpdate(sql);//执行完DDL语句 可能返回0
    System.out.println(count);
    stmt.close();
    conn.close();
}

ResultSet

作用:封装了DQL查询语句的结果 image.png image.png

Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql:///db1?useSSL=false";
String user="root";
String password="123456";
Connection conn = DriverManager.getConnection(url,user,password);
String sql = "select * from account;";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
List<Account> list = new ArrayList<>();
while (rs.next()) {
    Account account = new Account();
    int id = rs.getInt(1);
    String name = rs.getString(2);
    double money = rs.getDouble(3);
    account.setId(id);
    account.setName(name);
    account.setMoney(money);
    list.add(account);
}
System.out.println(list);
rs.close();
stmt.close();
conn.close();

PreparedStatement

作用:预编译SQL语句并执行:预防SQL注入问题

SQL注入:SQL注入是通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法。

演示sql注入:

 Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql:///db1?useSSL=false";
        String username="root";
        String password="123456";
        Connection c = DriverManager.getConnection(url, username, password);
//        String user ="anan";
//        String pwd = "123";正确的账号密码
        String user ="xxx";
        String pwd = "' or '1'='1";//黑客的账号密码
        String sql = "select * from tb_user where username = '"+user+"' and password = '"+pwd+"';";
        Statement stmt = c.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        if(rs.next()){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");
        }
        rs.close();
        stmt.close();
        c.close();

使用PreparedStatement的步骤: image.png

String user ="anan";
String pwd = "123";//正确的账号密码
String sql = "select * from tb_user where username = ? and password = ?;";
PreparedStatement pstmt = c.prepareStatement(sql);
pstmt.setString(1,user);
pstmt.setString(2,pwd);
ResultSet rs = pstmt.executeQuery();

PreparedStatement原理:
1.在获取PreparedStatement对象时,将sql语句发送给mysql服务器进行检查,编译(这些步骤很耗时)
2.执行时就不用再进行这些步骤了,速度更快
3.如果sql模板一样,则只需要进行一次检查、编译

四、数据库连接池

数据库连接池是个容器,负责分配、管理数据库连接(Connection)。

它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;
释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。

好处:
1、资源重用
2、提升系统响应速度。避免数据库连接遗漏

image.png

数据库连接池实现 image.png

Driud使用步骤
1.导入jar包, druid-1.1.12.jar
2.定义配置文件
3.加载配置文件
4.获取数据库连接池对象
5.获取连接 image.png

Properties prop = new Properties();
prop.load(new FileInputStream("jdbc-demo/src/druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
Connection connection = dataSource.getConnection();
System.out.println(connection);//com.mysql.jdbc.JDBC4Connection@6979e8cb

五、品牌增删改查的案例

//查询
@Test
public void testSelectAll() throws Exception {
    //获取Connection
    Properties prop = new Properties();
    prop.load(new FileInputStream("src/druid.properties"));
    DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
    Connection conn = dataSource.getConnection();
    //定义sql
    String sql = "select * from tb_brand;";
    //获取PreparedStatement对象
    PreparedStatement pstmt = conn.prepareStatement(sql);
    //执行sql
    ResultSet rs = pstmt.executeQuery();
    //处理结果
    Brand brand = null;
    List<Brand> list=new ArrayList<>();
    while (rs.next()){
        int id = rs.getInt("id");
        String brandName = rs.getString("brand_name");
        String companyName = rs.getString("company_name");
        int ordered = rs.getInt("ordered");
        String description = rs.getString("description");
        int status = rs.getInt("status");
        brand=new Brand();
        brand.setId(id);
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(ordered);
        brand.setDescription(description);
        brand.setStatus(status);
        list.add(brand);
    }
    System.out.println(list);
    //释放资源
    rs.close();
    pstmt.close();
    conn.close();
}

//增加
@Test
public void testAdd() throws Exception {
    String brandName = "TFBOYS";
    String companyName = "时代峰峻";
    int ordered = 1;
    String description = "天下第一好";
    int status = 1;
    Properties prop = new Properties();
    prop.load(new FileInputStream("src/druid.properties"));
    DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
    Connection conn = dataSource.getConnection();
    String sql = "insert into tb_brand (brand_name,company_name,ordered,description,status) values(?,?,?,?,?);";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    pstmt.setString(1,brandName);
    pstmt.setString(2,companyName);
    pstmt.setInt(3,ordered);
    pstmt.setString(4,description);
    pstmt.setInt(5,status);
    //受影响的行数
    int count = pstmt.executeUpdate();
    System.out.println(count>0);
    pstmt.close();
    conn.close();
}

//修改
@Test
public void testUpdate() throws Exception {
    String brandName = "捕鱼小灵通";
    String companyName = "强盛集团";
    int ordered = 1;
    String description = "风浪越大,鱼越贵";
    int status = 1;
    int id=2;
    Properties prop = new Properties();
    prop.load(new FileInputStream("src/druid.properties"));
    DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
    Connection conn = dataSource.getConnection();
    String sql = "update tb_brand\n" +
            "set brand_name = ?,\n" +
            "company_name = ?,\n" +
            "ordered = ?,\n" +
            "description = ?,\n" +
            "status = ?\n" +
            "where id =?;";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    pstmt.setString(1,brandName);
    pstmt.setString(2,companyName);
    pstmt.setInt(3,ordered);
    pstmt.setString(4,description);
    pstmt.setInt(5,status);
    pstmt.setInt(6,id);
    //受影响的行数
    int count = pstmt.executeUpdate();
    System.out.println(count>0);
    pstmt.close();
    conn.close();
}

//删除
@Test
public void testDeleteById() throws Exception {
    int id=1;
    Properties prop = new Properties();
    prop.load(new FileInputStream("src/druid.properties"));
    DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
    Connection conn = dataSource.getConnection();
    String sql = "delete from tb_brand where id = ?;";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    pstmt.setInt(1,id);
    //受影响的行数
    int count = pstmt.executeUpdate();
    System.out.println(count>0);
    pstmt.close();
    conn.close();
}

Maven

Maven是专门用于管理和构建Java项目的工具,它的主要功能有:
提供了一套标准化的项目结构
提供了一套标准化的构建流程(编译,测试,打包,发布......)
提供了一套依赖管理机制

标准化的项目结构 image.png

image.png

标准化的构建流程 Maven提供了一套简单的命令来完成项目构建 image.png

依赖管理机制 依赖管理其实就是管理你项目所依赖的第三方资源(jar包、插件...)

before image.png now image.png

一、Maven简介

image.png image.png

二、Maven安装配置

image.png

三、Maven基本使用

常用命令

  • compile:编译
  • clean:清理
  • test:测试
  • package:打包
  • install:安装

生命周期

image.png

四、IDEA配置Maven

更多详细的maven的配置在网络上搜教程吧~(包括maven的setting.xml中添加本地仓库、添加镜像阿里云仓库;maven的环境变量配置;idea中的setting中的jdk配置等。)
注意本地仓库的文件权限一定要打开!!!排错一天一夜后血与泪的教训~ image.png Maven坐标详解 image.png

五、依赖管理

使用坐标导入jar包的步骤 image.png 自动导入: image.png 已知本地仓库有,快捷方式: image.png

依赖范围 image.png

MyBatis

MyBatis的概述 image.png JDBC的缺点 image.png MyBatis简化
因此在持久层框架,MyBatis使用比例占比最高 image.png

一、MyBatis快速入门

案例:查询user表所有数据 image.png

image.png

    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.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
//        3.执行sql
        List<User> users = sqlSession.selectList("test.selectAll");

        System.out.println(users);

//        4.释放资源
        sqlSession.close();
    }

image.png image.png

二、Mapper代理开发

image.png image.png image.png

三、MyBatis核心配置文件

mybatis-config.xml

image.png image.png

<?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>
<!--    别名-->
    <typeAliases>
        <package name="com.itheima.pojo"/>
    </typeAliases>

    <!--        environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
<!--                数据库连接信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        加载sql映射-->
<!--        <mapper resource="UserMapper.xml"/>-->
        <mapper resource="com/itheima/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

四、配置文件完成增删改查的案例

image.png 准备环境
1.数据库表tb_brand
2.实体类Brand
3.测试用例MyBatisTest
4.安装MyBatisX插件 image.png

查询所有数据

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

  • 参数:无
  • 结果: List< Brand >

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

image.png

image.png

image.png

image.png

image.png MyBatis完成操作需要几步?
三步:编写接口方法-->编写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">


<!--
数据库表的字段名称﹑和实体类的属性名称不一样,则不能自动封装数据
-->
<!--3、resultMap-->
<mapper namespace="com.itheima.mapper.BrandMapper">
    <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>


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


<!--        <select id="selectAll" resultType="Brand">-->
<!--    #         select * from tb_brand;-->
<!--    &lt;!&ndash;        1、起别名&ndash;&gt;-->
<!--    # select id,brand_name,company_name,ordered,description,status from tb_brand;-->
<!--    # select id,brand_name as brandName,company_name as companyName,ordered,description,status from tb_brand;-->
<!--    &lt;!&ndash;        2、sql片段&ndash;&gt;-->
<!--            select <include refid="brand_column"></include> from tb_brand;-->
<!--        </select>-->

</mapper>

查询详情

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

  • 参数: id
  • 结果:Brand
    2.编写SQL语句: SQL映射文件
    3.执行方法,测试
//BrandMapper
List<Brand> selectById(int id);

//BrandMapper.xml
// 参数占位符:
//1.#{}:将其替换为?,为了防止SQL注入
//2.${}:拼sql。会存在SQL注入问题

<select id="selectById" resultMap="brandResultMap">
    select * from tb_brand where id = #{id};
</select>

//MyBatisTest
int id =1;
List<Brand> brand = brandMapper.selectById(id);
System.out.println(brand);

image.png

条件查询

多条件查询
1.编写接口方法: Mapper接口

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

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

//BrandMapper
    //    ☆条件查询参数接收 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);

//BrandMapper.xml
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
where status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName}
</select>

//MyBatisTest
//        List<Brand> brands = brandMapper.selectByCondition(status, brandName, companyName);
//        List<Brand> brands = brandMapper.selectByCondition(brand);
        List<Brand> brands = brandMapper.selectByCondition(map);
        System.out.println(brands);

多条件动态查询

动态sql:
用户输入条件时,是否所有条件都会填写?可能只会输入部分条件!SQL语句会随着用户的输入或外部条件的变化而变化,我们称为动态SQL!

image.png

<!--    动态条件查询-->
<!--    if:条件判断-->
<!--    test:逻辑表达式-->
<!--    解决and问题: 恒等式 或者 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 company_name like #{companyName}
        </if>
        <if test="brandName !=null and brandName!=''">
            and brand_name like #{brandName}
        </if>
    </where>

</select>

单条件动态查询

image.png

// BrandMapper   单条件查询
    List<Brand> selectByConditionSingle(Brand brand);
 
// BrandMapper.xml
 <select id="selectByConditionSingle" resultMap="brandResultMap">
        select * from tb_brand
#                  where
        <where>
            <choose>
                <when test="status !=null">
                    status = #{status}
                </when>
                <when test="companyName !=null and company_name!=''">
                    company_name like #{companyName}
                </when>
                <when test="brandName !=null and brandName!=''">
                    brand_name like #{brandName}
                </when>
                <!--            <otherwise>-->
                <!--                1=1-->
                <!--            </otherwise>-->
            </choose>
        </where>
    </select>
    
  //MyBatisTest
  
List<Brand> brands = brandMapper.selectByConditionSingle(brand);
System.out.println(brands);

添加

image.png

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

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


//BrandMapper.xml
<!--    添加-->
<!--    返回主键的值-->
    <insert id="add" useGeneratedKeys="true" keyProperty="id">
        insert into tb_brand(brand_name, company_name, ordered, description, status)
        values(#{brandName},#{companyName},#{ordered},#{description},#{status});
    </insert>
    
 //MyBatisTest
//        4、执行方法
        brandMapper.add(brand);
        System.out.println(brand.getId());

修改全部字段

image.png

//BrandMapper
//    修改
    int update(Brand brand);
//BrandMapper.xml

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

//MyBatisTest

    @Test
    public void testUpdate() throws IOException {
        int status =0;
        String brandName = "塔斯丁";
        String companyName="蟹黄汉堡公司";
        int ordered=128;
        String description="香辣鸡腿堡,抄袭中国味的汉堡~";
        int id =6;
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setDescription(description);
        brand.setOrdered(ordered);
        brand.setBrandName(brandName);
        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();
    }

修改动态字段

image.png

<update id="update">
    update tb_brand
    <set>
        <if test="status !=null">
            status = #{status}
        </if>
        <if test="companyName !=null and company_name!=''">
            company_name= #{companyName},
        </if>
        <if test="brandName !=null and brandName!=''">
            brand_name= #{brandName},
        </if>
        <if test="description !=null">
            description = #{description}
        </if>
        <if test="ordered !=null">
            status = #{ordered}
        </if>
    </set>
    where id =#{id};
</update>

删除一个

image.png

//BrandMapper
void  deleteById(int id);

//BrandMapper.xml
<!--    删除-->
    <delete id="deleteById">
        delete from tb_brand where id = #{id};
    </delete>
    
//MyBatisTest
brandMapper.deleteById(id);

批量删除

image.png

//BrandMapper
//    批量删除
    void deleteByIds(@Param("ids") int[] ids);
    
//BrandMapper.xml
    <!--    批量删除-->
    <delete id="deleteByIds">
        delete from tb_brand where id in
#        (
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
#            )
;

//MyBatisTest
    
//        4、执行方法
        brandMapper.deleteByIds(ids);

MyBatis参数传递 image.png

image.png

五、注解完成增删改查

image.png

@Select("select id,brand_name as brandName, company_name as companyName,ordered,description,status from tb_brand where id = #{id};")
List<Brand> selectById(int id);