JavaWeb学习

创建数据库 判断 如果不存在就进行创建

create database if not exists dbq;

删除数据库

drop database  dbq;

如果存在这个数据库 就删除

drop database if exists dbq;

查看当前正在使用的数据库

select database();

展示当前数据库所有表

show tables;

查询表结构

desc tb_area;

删除表

drop tb_aera;

如果存在 再删除

drop if exists tb_aera;

修改表

修改表名 rename to

alter table user rename to tb_user;
alter table 旧表名 rename to 新表名;

添加一列字段 add

alter table tb_user add address varchar(45);

修改数据类型 关键词 modify

alter table tb_user modify address char(45);

修改列名和数据类型 change

alter table tb_user change address addr varchar(22);
alter table 表名 change 旧字段名 新字段名 新数据类型;

删除列 drop

alter table tb_user drop addr;
alter table tb_user drop 列名;

DML添加数据insert into values

1、给指定列添加

insert into tb_user(id,name) values(1,'张三');

2、给全部列添加

insert into tb_user(id,name,pwd) values(1,'张三','111');
或者这样 不建议 insert into tb_user values(1,'张三','111');

3、批量添加数据

insert into tb_user(id,name,pwd) values(2,'黎明','22'),(2,'黎明','22'),(2,'黎明','22'),(2,'黎明','22');

修改数据 update set

注意:如果没加where条件 则会修改表中的全部字段条件

update tb_user set name='李四' where name='张三';
update tb_user set id=3,name='赵云',pwd='1234' where id=1; 

DML删除语句 delete from

不加where条件 会删除表中所有数据

delete from tb_user where name='黎明';

基础查询

查询语法
select
字段列表
from
表明列表
where
条件列表
group by
分组字段
having
分组后条件
order by
排序字段
limit
分页限定

基础查询

1、查询多个字段

select name,adr from tb_user;

2、去除重复记录 使用distinct 关键字

select distinct name,adr from tb_user;

3、起别名 使用as关键字 也可以省略

select  distinct name as'姓名',adr as'地址' from tb_user;

条件查询(where)

在sql中 并且 建议使用and关键字 而不是&&

查询年龄20到30之间的用户

select *from tb_users where age>=20 and age<=30;
或者是 select*from tb_users where age between 20 and 30;

查询年纪不等于20的用户 可以用!= 或者<>

select *from tb_users where age !=20;
select*from tb_users where age <>20;

查询等于age等于18 或者20 或者22 或者用or关键字
也可以用 in() 括号集合填想要查的数据

select*from tb_users where age=20 or age=18 or age=22;
这种也可以  select *from tb_users where age in(20,18,22);

查询是否为null值 用 is 跟is not

select*from tb_users where age is null;
select*from tb_users where age is not null;

模糊查询 like
通配符:1、_代表单个任意字符
2、%代表任意个数字符

查第一个字是李的
select *from tb_users where tb_name like '李%';
查第二个字是四的
select *from tb_users where tb_name like '_四%';
只要包含李的就查
select *from tb_users where tb_name like '%李%';

在这里插入图片描述

分组查询(group by)

聚合函数
概念:将一列作为一个整体,进行纵向计算
分类: count 统计个数(不统计null值)
max求最大值
min求最小值
sum求和
avg平均值
注意 null值不参与所有计算

select count(id)from tb_users;
select max(age) from tb_users;
select min(age)from tb_users;
select avg(age)from tb_users;

根据性别进行分组,查男女平均年龄

select sex,avg(age) from tb_users group by sex;

根据性别进行分组,查男女平均年龄跟各自个数

select sex,avg(age),count(sex) from tb_users group by sex;

年龄大于20的参与分组

select sex,avg(age),count(sex) from tb_users where age>20 group by sex;

where与having的区别
执行的时机不一样:where是分组之前进行限定,不满住where条件则不参与分组,而having是对分组之后对结果进行过滤。
可判断的条件也不一样:where不能对聚合函数进行判断,having可以
执行顺序:where>聚合函数>having

排序查询(order by)

排序方式:asc:升序排序 (默认值)
desc:降序排序
注意: 如果多条件排序 ,当前边条件一样时,才会根据第二个条件进行排序

升序排序
select*from tb_users order by age asc ;
降序排序
select *from tb_users order by age desc;

分页查询(limit)

select 字段列表 from 表名 limit 起始索引,查询条数目
起始索引从0开始
起始索引计算公式:起始索引=(当前页码-1)*每页显示的条数

select *from tb_users limit 0,3;

在这里插入图片描述

约束

约束的概念和分类

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

约束的分类:
约束名称 描述 关键字
非空约束 保证列中的所有数据不能有null值 not null
唯一约束 保证列中的所有数据各不相同 unique
主键约束 主键是一行数据的唯一标识,要求非空且唯一 primary key
检查约束 保证列中的值满足某一条件 check
默认约束 保存数据时,未指定值则采用默认值 default
外键约束 外键用来让两个表的数据之间建立链接,保证数据的一致性和完整性
foreign key
注意:mysql不支持检查约束

-- 员工表
CREATE TABLE emp (
id INT primary key auto_increment, -- 员工id,主键且自增长
ename VARCHAR (50) not null unique, -- 员工姓名,非空并且唯一
joindate DATE not null,-- 入职日期,非空
salary DOUBLE (7,2) not null, -- 工资,非空
bonus DOUBLE (7,2) default 0  -- 奖金,如果没有奖金默认为0
);
insert into emp(ename,joindate,salary,bonus)values ('李四','2007-4-25',5000,1000);

外键约束

创建员工与部门的外键

constraint fk_emp_dept foreign key(dep_id) references dept(id) -- 创建员工与部门的外键

删除外键

alter table emp drop foreign key fk_emp_dept; -- 删除外键

建表后添加外键

alter table emp add constraint fk_emp_dept foreign key(dep_id) references dept(id);-- 建表后添加外键

多对多表建立外键 通常通过第三方表进行建立

-- 订单表
create table tb_order(
id int primary key auto_increment,
payment double(10,2),
payment_type tinyint,
status tinyint
);
-- 商品表
create table tb_goods(
id int primary key auto_increment,
title varchar(100),
price double(10,2)
);
-- 订单商品中间表
create table  tb_order_goods(
id int primary key auto_increment,
order_id int,
goods_id int,
count int
);

alter table tb_order_goods add constraint fk_order foreign key(order_id) references tb_order(id);
alter table tb_order_goods add constraint fk_goods foreign key (goods_id)references tb_goods(id);

在这里插入图片描述

多表查询

当多表查询出现了笛卡尔积的情况(笛卡尔积:有ab两个集合,取ab两个集合组合的所有情况)通常使用下列查询消除

这种情况叫做连接查询的内连接

select*from emp,dept where emp.dep_id=dept.id;

笛卡尔积:取a b集合所有组合情况
多表查询:从多张表查询数据
连接查询:内连接:相当于查询 a b相交集数据
外连接:左外链接:相当于查询a表所有数据和交集部分数据
右外链接:相当于查询b表所有数据和交集部分数据
子查询:查询中嵌套查询,称嵌套查询为子查询
子查询根据查询结果不同,作用不同:单行单列
多行单列
多行多列

内连接查询语法
内连接
隐士内连接:select 字段列表 from 表一 ,表二 where 条件;

select emp.ename,dept.name from emp,dept where emp.dep_id=dept.id;
可以给表取别名
select t1.ename,t2.name from emp t1,dept t2 where t1.dep_id=t2.id;

显示内连接(inner join on ):select 字段列表 from 表一 【inner】join 表二 on 条件;

select emp.ename,dept.name from emp inner join dept on emp.dep_id=dept.id;

外连接
左外连接: select 字段列表 from 表一 left 【outer】 join 表二 on 条件
右外链接: select 字段列表 from 表一 right【outer】 join 表二 on 条件

-- 左外链接
select*from emp left join dept on emp.dep_id=dept.id;
-- 右外连接
select*from emp right join dept on emp.dep_id=dept.id;

子查询

-- 子查询 查询id大于张三的员工
select id from emp where ename='张三';
select*from emp where id>2;
-- 子查询写法
select*from emp where id>(select id from emp where ename='张三');

子查询根据结果的不同,作用不同:
单行单列:作为条件值,使用 = != > <等条件进行判断
select 字段列表 from 表 where 字段名=(子查询);
多行单列:作为条件值,使用in等关键字进行条件判断
select 字段列表 from 表 where 字段名 in(子查询);

-- 查询研发部和财务部的人员信息
select *from emp where dep_id in(select id from dept where name='研发部' or name='财务部');

多行多列:作为虚拟表
select 字段列表 from(子查询) where 条件;

-- 查询入职时间大于'2005-04-05'员工和部门
select *from emp where joindate >'2005-04-05';
select *from (select *from emp where joindate >'2005-04-05') t1,dept where t1.dep_id=dept.id;

数据库事务

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

– 开启事务
start transaction 或者begin

–提交事务
commit

–回滚事务
rollback

JDBC

JDBC简介
JDBC快速入门
1、创建工程,导入驱动jar包
在这里插入图片描述
2、注册驱动

Class.forName("com.mysql.jdbc.Driver");

3、获取连接

       Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/a", "root", "root1234");

4、定义SQL语句

  String sql="update account set money=2000 where id=1";

5、获取执行SQL对象

 Statement stat = conn.createStatement();

6、执行SQL

 int count = stat.executeUpdate(sql);

7、处理返回结果

   System.out.println(count);

8、释放资源

stat.close();
 conn.close();

全篇

/*jdbc快速入门*/
public class JDBC {
    public static void main(String[] args) throws Exception {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        //String url="jdbc:mysql://localhost:3306/a";
       // String username="root";
       // String password="root1234";
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/a", "root", "root1234");
        //定义sql
        String sql="update account set money=2000 where id=1";
        //获取执行sql的对象
        Statement stat = conn.createStatement();
        //执行sql
        int count = stat.executeUpdate(sql);
        //处理结果
        System.out.println(count);
        //释放资源
        stat.close();
        conn.close();
    }
}

JDBC API详解

DriverManager
Connection
Statement
ResultSet
PreparedStatement

DriverManager(驱动管理类)作用:

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

查看Driver类源码

    static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }

提示:MYSQL5之后的驱动包,可以省略注册驱动的步骤 因为自动加载了jar包中的META-INF/service/java.sql.Driver文件中的驱动类在这里插入图片描述

2、获取数据库连接
static Connection getConnection(String url,String user,String password)
参数:1、url:连接路径
语法:jdbc:mysql://ip地址(域名):端口号/数据库名称?参数键值对1&参数键值对2…
示例:jdbc:mysql://127.0.0.1:3306/a
细节:如果连接的是本机mysql服务器,并且mysql服务器默认端口号是3306,则url可以简写为:jdbc:mysql:///数据库名称?参数键值对

//获取连接  如果连接的是本机mysql并且端口默认为3306 可以简化书写为以下格式
        //String url="jdbc:mysql:///a";
					配置useSSL=false参数,禁用安全连接方式,解决警告安全 
String url="jdbc:mysql:///a"?useSSL=false;

2、user:用户名
3、password:密码

Connection(数据库连接对象)作用:

1、获取执行SQL对象
2、管理事务

1、获取执行SQL对象
普通执行SQL对象
Statement createStatement()
预编译SQL的执行SQL对象:防止SQL注入
PreparedStatement prepareStatement(sql)
执行存储过程的对象
CallableStatement prepareCall(sql)
2、事务管理
MYSQL事务管理:
开启事务:BEGIN; 或者START TRANCACTION;
提交事务:COMMIT;
回滚事务:ROLLBACK;
MYSQL默认提交事务

JDBC事务管理:Connection接口定义了三个对应的方法
开启事务:setAutoCommit(boolean autoCommit):true 为自动提交事务:false为手动提交事务,即为开启事务
提交事务:commit();
回滚事务:rollback();

Statement
Statement作用:
1、执行SQL语句
int executeUpdate(sql):执行DML(对数据的增删改操作) DDL(对表、库的增删改查操作)语句
返回值:(1)DML语句影响的行数 一般进行判断是否大于0 大于就说明成功,反之亦然 (2) DDL语句执行后,执行成功也可能返回0

ResultSet executeQuery(sql):执行DQL(对数据的查询操作)语句
返回值:ResultSet结果集对象

ResultSet
ResultSet(结果集对象)作用:
1、封装了DQL查询语句的结果
ResultSet stmt.executeQuery(sql):执行DQL语句,返回Result对象
获取查询结果
boolean next():(1)将光标从当前位置向前移一格 (2) 判断当前行是否为有效行
返回值:true:有效行,当前行有数据
false:无效行,当前行没有数据

Result的使用

  @Test
    public void test_Result() throws Exception {
        //注册驱动
//        Class.forName("com.mysql.jdbc.Driver");
        //获取连接  如果连接的是本机mysql并且端口默认为3306 可以简化书写为以下格式
        //String url="jdbc:mysql:///a";
        // String username="root";
        // String password="root1234";
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/a?useSSL=false", "root", "root1234");
        //定义sql
        String sql="select*from account";

        //获取执行sql 对象
        Statement stat = conn.createStatement();
        //执行sql
        ResultSet resultSet = stat.executeQuery(sql);
        //处理结果,遍历resultSet的所有数据
//        while (resultSet.next()){
//            int id = resultSet.getInt(1);
//            String string = resultSet.getString(2);
//            double double1 = resultSet.getDouble(3);
//            System.out.println(id);
//            System.out.println(string);
//            System.out.println(double1);
//            System.out.println("=========================");
//        }
        while (resultSet.next()){
            int id = resultSet.getInt("id");
            String string = resultSet.getString("name");
            double double1 = resultSet.getDouble("money");
            System.out.println(id);
            System.out.println(string);
            System.out.println(double1);
            System.out.println("=========================");
        }
        //释放资源
        resultSet.close();
        stat.close();
        conn.close();
    }

ResultSet案例
需求:查询account账户表数据,封装在Account对象中,并且存储到ArrayList集合中

/*ResultSet案例
需求:查询account账户表数据,封装在Account对象中,并且存储到ArrayList集合中
1.定于实体类Account
public class Account {
    private int id;
    private String name;
    private double money;
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getMoney() {
        return money;
    }
    public void setMoney(double money) {
        this.money = money;
    }
}
2、查询数据 封装到account对象中
3、将Account封装到ArrayList集合中
*/
    @Test
    public void test_Result1() throws Exception {
        //注册驱动
//        Class.forName("com.mysql.jdbc.Driver");
        //获取连接  如果连接的是本机mysql并且端口默认为3306 可以简化书写为以下格式
        //String url="jdbc:mysql:///a";
        // String username="root";
        // String password="root1234";
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/a?useSSL=false", "root", "root1234");
        //定义sql
        String sql="select*from account";

        //获取执行sql 对象
        Statement stat = conn.createStatement();
        //执行sql
        ResultSet resultSet = stat.executeQuery(sql);

        //创建集合
        List<Account> list = new ArrayList<Account>();
        //处理结果,遍历resultSet的所有数据  1、.next()方法的作用:指针指向下一条记录,有记录(有值)返回true并把记录内容存入到对应的对象中,也就是obj.next()的obj中。如果没有返回false。
        //2、.next()方法的应用:一般和ResultSet对象和while循环一起使用,去迭代结果集,并在循环中调用getXXX(intfieldIndex)/getXXX(String columnName)方法获取字段值。

        while (resultSet.next()){
            Account account = new Account();

            //获取数据
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            double money = resultSet.getDouble("money");
            //赋值
            account.setId(id);
            account.setName(name);
            account.setMoney(money);
            list.add(account);
        }
        System.out.println(list);
        //释放资源
        resultSet.close();
        stat.close();
        conn.close();
    }

PreparedStatement
作用:1、预编译sql语句并执行,防止sql注入问题
sql注入:是指通过操作输入来修改事先定义好的sql语句,用以达到执行代码对服务器进行攻击的方法
步骤:1、获取PreparedStatement对象
//sql语句中的参数值,使用?占位符代替
String sql=“select*from tb_user where name= ? and pwd= ?”;
//通过Connection对象获取prepareStatement()并传入对应的sql语句
PreparedStatement pstat = conn.prepareStatement(sql);
2、设置参数值
PreparedStatement对象:setXxx(参数1,参数2) 给?赋值
Xxx:数据类型;
//设置?的值
pstat.setString(1,name);
pstat.setString(2,pwd);
3、执行SQL
executeQuery(); 不再需要传递sql

    public void test_inject() throws Exception {
        //注册驱动
//        Class.forName("com.mysql.jdbc.Driver");
        //获取连接  如果连接的是本机mysql并且端口默认为3306 可以简化书写为以下格式
        //String url="jdbc:mysql:///a";
        // String username="root";
        // String password="root1234";
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/a?useSSL=false", "root", "root1234");

        //接收输入的用户名 密码
        String name="张三";
        String pwd="123";
        //定义sql
        String sql="select*from tb_user where name= ? and pwd= ?";
        //获取prepareStatement对象
        PreparedStatement pstat = conn.prepareStatement(sql);
        //设置?的值
        pstat.setString(1,name);
        pstat.setString(2,pwd);
        //执行sql
        ResultSet resultSet = pstat.executeQuery();
        if(resultSet.next()){
            System.out.println("成功");
        }else{
            System.out.println("失败");
        }
        //关闭资源
        resultSet.close();
        pstat.close();
        conn.close();
    }

数据库连接池

数据库连接池简介:
数据库连接池是个容器,负责分配、管理数据库连接(Connection);
它允许应用程序重复使用一个现有的数据库连接,而不是在重新建立一个;
释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏
好处:资源重用
提升系统响应速度
避免数据库连接遗漏

Druid(德鲁伊)数据库连接池
使用步骤:
1、导入jar包druid-1.1.12.jar
2、定义配置文件 druid.propertis

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///a?useSSL=false&useServerPrepStmts=true
username=root
password=root1234
#初始化连接数量
initialSize=5
#最大连接数量
maxActive=10
#最大等待时间
maxWait=3000

3、加载配置文件

    //加载配置文件   load()方法用于从本地文件系统中加载名为fn(filename)的给定参数的Java文件。
       Properties prop = new Properties();
       //FileInputStream流被称为文件字节输入流,意思指对文件数据以字节的形式进行读取操作如读取图片视频等
        prop.load(new FileInputStream("src/druid.properties"));

4、获取数据库连接池对象

 //获取连接池工程对象
       DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

5、获取连接

        //获取数据库连接Connection
        Connection connection = dataSource.getConnection();

全部流程

//druid数据库连接池演示
public class druidDemo {
    public static void main(String[] args) throws Exception {
        //导入jar包

        //定于配置文件

        //加载配置文件   load()方法用于从本地文件系统中加载名为fn(filename)的给定参数的Java文件。
       Properties prop = new Properties();
       //FileInputStream流被称为文件字节输入流,意思指对文件数据以字节的形式进行读取操作如读取图片视频等
        prop.load(new FileInputStream("src/druid.properties"));

       //获取连接池工程对象
       DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        //获取数据库连接Connection
        Connection connection = dataSource.getConnection();
    }
}

练习

Brand实体类/*
* alt + 鼠标左键:整列编辑
* alt+r 查找替换
*
* 在实体类中 基本数据类型建议使用其对应的包装类型
* */
public class Brand {
  private Integer  id;                 // id主键
  private String  brandName;         // 品牌名称
  private String  companyName;           // 企业名称
  private Integer  ordered;          // 排序字段
  private String  description;        // 描述信息
  private Integer  status;            // 状态 0为禁用 1为可用
    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 +
                '}';
    }
}

   /*查询所有
1、SQL:select*from tb_Brand
2、参数:不需要
3、结果 List<Brand>
* */
public class TestBrand {
    /*1、获取Connection
    * 2、定义SQL :select*from tb_brand
    * 3、获取PreparedStatemrnt对象
    * 4、设置参数:不需要
    * 5、执行SQL
    * 6、处理结果:List<Brand>
    7、释放资源*/
    @Test
    public  void TestSelectAll() throws Exception {
       //加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //获取数据库连接Connection
        Connection conn = dataSource.getConnection();
        String sql="select*from tb_brand";
        //获取sql对象
        PreparedStatement pstat = conn.prepareStatement(sql);
        //设置参数

        //执行sql对象
        ResultSet resultSet = pstat.executeQuery();
        //处理结果LIst<Brand> 封装到Brand对象 然后装载到集合中
        ArrayList<Brand> list = new ArrayList<Brand>();
        while (resultSet.next()){
            //获取数据
            int id = resultSet.getInt("id");
            String brandName = resultSet.getString("brand_name");
            String companyName = resultSet.getString("company_name");
            int ordered = resultSet.getInt("ordered");
            String description = resultSet.getString("description");
            int status = resultSet.getInt("status");
            //封装Brand对象
            Brand 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);
        //资源释放
        resultSet.close();
        pstat.close();
        conn.close();
    }
       /*添加
1、SQL:insert into
2、参数:需要除了id之外的所有参数
3、结果 :返回boolean
* */
    @Test
    public  void TestAdd() throws Exception {
        //模拟接收页面提交的参数
        String brandName="香飘飘";
        String companyName="香飘飘有限公司";
        int ordered=2;
        String description="暖暖的很贴心";
        int status=1;

        //加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //获取数据库连接Connection
        Connection conn = dataSource.getConnection();
        String sql="insert into tb_brand(brand_name,company_name,ordered,description,status)values(?,?,?,?,?)";
        //获取sql对象
        PreparedStatement pstat = conn.prepareStatement(sql);
        //设置参数
        pstat.setString(1,brandName);
        pstat.setString(2,companyName);
        pstat.setInt(3,ordered);
        pstat.setString(4,description);
        pstat.setInt(5,status);

        //执行sql对象
        int count = pstat.executeUpdate();  //影响的行数
        //处理结果
        if(count>0){
            System.out.println("添加成功");
        }else{
            System.out.println("false");
        }

        //资源释放

        pstat.close();
        conn.close();
    }


    /*修改
1、SQL:update set
2、参数:需要所有参数
3、结果 :返回boolean
* */
    @Test
    public  void TestUpdate() throws Exception {
        //模拟接收页面提交的参数
        String brandName="真果粒";
        String companyName="蒙牛有限公司";
        int ordered=2;
        String description="果泥暖暖的很贴心";
        int status=1;
        int id=4;

        //加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //获取数据库连接Connection
        Connection conn = dataSource.getConnection();
        String sql="update  tb_brand set brand_name=?,company_name=?,ordered=?,description=?,status=? where id=?";
        //获取sql对象
        PreparedStatement pstat = conn.prepareStatement(sql);
        //设置参数
        pstat.setString(1,brandName);
        pstat.setString(2,companyName);
        pstat.setInt(3,ordered);
        pstat.setString(4,description);
        pstat.setInt(5,status);
        pstat.setInt(6,id);
        //执行sql对象
        int count = pstat.executeUpdate();  //影响的行数
        //处理结果
        if(count>0){
            System.out.println("true");
        }else{
            System.out.println("false");
        }

        //资源释放

        pstat.close();
        conn.close();
    }


    /*删除
1、SQL:delete
2、参数:id
3、结果 :返回boolean
* */
    @Test
    public  void TestDelete() throws Exception {
        //模拟接收页面提交的参数

        int id=1;

        //加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //获取数据库连接Connection
        Connection conn = dataSource.getConnection();
        String sql="delete from tb_brand where id=?";
        //获取sql对象
        PreparedStatement pstat = conn.prepareStatement(sql);
        //设置参数

        pstat.setInt(1,id);
        //执行sql对象
        int count = pstat.executeUpdate();  //影响的行数
        //处理结果
        if(count>0){
········            System.out.println("true");
        }else{
            System.out.println("false");
        }

        //资源释放

        pstat.close();
        conn.close();
    }
}

MyBatis

MyBatis快速入门
1、导入mybatis依赖jar包

-<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>

<!--mysql 驱动-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
-<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>

<!--junit单元测试-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
-<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>tset</scope>
</dependency>

<!-- 添加slf4j日志api-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
-<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<!-- 添加logback-classic依赖-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
-<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>

<!-- 添加logback-core依赖-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
-<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>

2、配置mybatis核心配置文件

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--数据库连接信息     -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!-- 后面的参数不能省略,&符号需要使用"& amp;"转义(注意中间没有空格) -->
                <property name="url" value="jdbc:mysql://localhost:3306/a?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai&amp;allowPublicKeyRetrieval=true"/>
                <property name="username" value="root"/>
                <property name="password" value="root1234"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--      加载sql映射文件  -->
        <mapper resource="UserMapper.xml"/>
        <mapper resource="Users.xml"/>
    </mappers>


</configuration>

3、数据库建库建表,创建实体类
4、UserMapper配置文件

<?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的全路径-->
<mapper namespace="Users">
    <select id="selectAll" resultType="Li.Users">
    select * from users;
  </select>
</mapper>

5、测试代码

    @Test
    public void testUsers() throws Exception {
     //加载mybatis核心配置文件 获取SqlsessionFactory
        String resource="mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获取sqlSession对象 用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行sql
        List<Users> users = sqlSession.selectList("Users.selectAll");
        System.out.println(users);
        //释放资源
        sqlSession.close();
    }

Mapper代理开发
步骤:使用Mapper代理方式完成入门案例
1、定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下 (用斜杠作为分隔符号)
2、设置SQL映射文件的namespace属性为Mapper接口全限定名(接口的权限路径名)
3、在Mapper接口中定方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致
4、编码:1通过SqlSession的getMapper方法获取Mapper接口的代理对象
2、调用对应方法完成sql的执行

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

MyBatis配置文件完成增删改查
准备环境:数据库表tb_brand
实体类Brand
测试用例
安装MyBatisX插件

练习:查询—查询所有数据
1、编写接口方法:Mapper接口
参数:无
结果:List
2、编写SQL语句:SQL映射文件
3、执行方法:测试

编写接口方法: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"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace:名称空间 -->
<mapper namespace="LI.mapper.BrandMapper">
    <select id="selectAll" resultType="LI.pojo.Brand">
        select *from tb_brand;
    </select>

</mapper>

mybatis-congif.xml配置文件

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--数据库连接信息     -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!-- 后面的参数不能省略,&符号需要使用"& amp;"转义(注意中间没有空格) -->
                <property name="url" value="jdbc:mysql://localhost:3306/a?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai&amp;allowPublicKeyRetrieval=true"/>
                <property name="username" value="root"/>
                <property name="password" value="root1234"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--      加载sql映射文件  -->
        <mapper resource="LI/mapper/BrandMapper.xml"/>
    </mappers>
</configuration>

总结:完成mybatis操作需要几步:三步:编写接口方法 -->编写SQL -->执行方法

实体类属性名和数据库表列名不一致,不能自动封装数据
解决方法:两种
第一种:取别名:在sql语句中对不一样的列名取别名,让别名和实体类的属性名一样
可以定于片段,提升复用性

 select id,brand_name as brandName,company_name as companyName,ordered,description, status from tb_brand;
        *起别名:对不一样的列名取别名,让别名和实体类的属性名一样
          *缺点:每次查询都要定义别名
            *解决方法:sql片段
                *缺点:不灵活
<sql id="brand_column">id,brand_name as brandName,company_name as companyName,ordered,description, status</sql>
         <select id="selectAll" resultType="LI.pojo.Brand">
            select
                 <include refid="brand_column"/>
            from tb_brand;
         </select>

第二种:resultMap:定义完成不一致的属性名和列名的映射 1、定义标签 2、在标签中,使用resultMap属性替换掉resultType属性

<mapper>
	<!--id:唯一标识  type:映射的类型(实体类),支持别名-->
    <resultMap id="brandResultMap" type="LI.pojo.Brand">
    <!-- resultMap 中有两个属性 id完成主键的映射  column:数据库表的列名  property:实体类的属性名  -->
	<!--resultMap 中有两个属性 result完成一般字段的的映射  column:数据库表的列名  property:实体类的属性名 -->
        <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>
</mapper>

练习:查询–查看详情
1、编写接口方法:Mapper接口
–>参数:id
–>结果:Brand
2、编写SQL语句:SQL映射文件
3、执行方法

<!--    /*查看详情:根据id查询*/
        *参数占位符:1、#{}:会将传进来的参数替换为?,为了防止sql注入
                    2、${}:拼sql,会存在sql注入问题
                    3、使用时机:*参数传递的时候:#{}
                                *表名或者列名不固定的情况下:${} 会存在SQL注入问题
                     *mapper中特殊字符的处理:
                                1、转义字符:例如‘<’ 用 &lt;
                                2、CDATA区:
-->
    <resultMap id="BrandResultMap" type="LI.pojo.Brand">
        <result column="brand_name" property="brandName"></result>
        <result column="company_name" property="companyName"></result>
    </resultMap>
    <select id="selectById" resultMap="BrandResultMap">
        select *from tb_brand where id
         <![CDATA[
         >
         ]]>
         #{id};

    </select>

总结:1、参数占位符
1)#{}:执行SQL时 ,会将#{}占位符替换为? ,将来自动设置参数值
2)KaTeX parse error: Expected 'EOF', got '#' at position 39: ….使用时机:*参数传递的时候:#̲{} …{}进行sql拼接
2、parameterType:用于设置参数类型,该参数可以省略
3、SQL语句中特殊字符处理:
*转义字符
* <![CDATA[内容 ]]> :直接写CD 会有提示

条件查询

查询:多条件查询
1、编写接口方法:Mapper接口
(1、散装参数:区分多个参数值传递采用散装方式进行,使用注解@Param(“SQL参数占位符名称”)
2、实体类封装参数:假如多个参数同属于一个对象的话,直接封装进一个对象就行 ,只需要保证SQL中的参数名和实体类属性名对应上,即可设置成功
3、map集合:封装成Map集合,子需要保证SQL中的参数名和map集合的键的名称对应上,即可设置成功)
–>参数:所查询的条件
–>条件:List
2、编写SQL语句:SQL映射文件
3、执行方法,测试

SQL映射文件

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

BrandMapper接口

public interface BrandMapper {
    /*查询所有*/
    List<Brand> selectAll();

    /*查看详情:根据id查询*/
    Brand selectById(int id);
    /* 条件查询
    * 参数接收:1、散装参数
    *           2、对象参数
    *           3、map集合参数
    * */
    /* 1、散装参数:如果方法中有多个参数,需要使用@Param("SQL参数占位符名称")*/
    //List<Brand>selectByCondition(@Param("status") int status,
     //                 @Param("companyName") String companyName,@Param("brandName")String brandName);

    /*2、对象参数:对象的属性名称要和参数占位符一致*/
    // List<Brand>selectByCondition(Brand brand);

    /*3、Map集合*/
       List<Brand>selectByCondition(Map map);
}

Test测试方法

@Test
    public void TestSelectByCondition1() throws Exception {
        //加载mybatis核心配置文件 获取SqlsessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取sqlsession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取mapper接口的代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //执行方法
        //模拟接受参数
       int status=1;
       String companyName="华为";
       String brandName="华为";
       //处理参数
        companyName="%"+companyName + "%";
        brandName="%"+brandName+"%";
        List<Brand> brands = mapper.selectByCondition(status, companyName, brandName);
        System.out.println(brands);
        //释放资源
        sqlSession.close();
    }

    @Test
    public void TestSelectByCondition2() throws Exception {
        //加载mybatis核心配置文件 获取SqlsessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获取sqlsession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //获取mapper接口的代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //执行方法
        //模拟接受参数
        int status=1;
        String companyName="华为";
        String brandName="华为";
        //处理参数
        companyName="%"+companyName + "%";
        brandName="%"+brandName+"%";
        Brand brand=new Brand();
        brand.setStatus(status);
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        List<Brand> brands = mapper.selectByCondition(brand);
        System.out.println(brands);
        //释放资源
        sqlSession.close();
    }

    @Test
    public void TestSelectByCondition3() throws Exception {

        //加载mybatis核心配置文件 获取SqlsessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获取sqlsession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //获取mapper接口的代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //执行方法
        //模拟接受参数
        int status=1;
        String companyName="华为";
        String brandName="华为";
        //处理参数
        companyName="%"+companyName + "%";
        brandName="%"+brandName+"%";
        Map map=new HashMap();
        map.put("status",status);
        map.put("companyName",companyName);
        map.put("brandName",brandName);
        List<Brand> brands = mapper.selectByCondition(map);
        System.out.println(brands);
        //释放资源
        sqlSession.close();
    }

查询-多条件-动态条件查询
*SQL语句会随着用户的输入或外部条件的变化而变化,我们称之为动态SQL
MyBatis对动态SQL有很强大的支撑:
if ,choose(when,otherwise),trim(where,set),foreach

if:用于判断参数是否有值,使用test属性进行条件判断
存在的问题:第一个条件不需要逻辑运算符
解决办法:*使用恒等式 1=1让所有条件格式都一样
*标签 替换where关键字
SQL映射文件 别的和上面案例相同

<!--动态条件查询
        *if:条件判断
         *test:逻辑表达式
        *问题:
            解决办法:*恒等式 1=1
                     *<where></where> 替换where关键字
    -->

    <select id="selectByCondition" resultMap="BrandResultMap">
    select *from tb_brand /*where 1=1*/
    <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>
    </where>
    </select>

练习-单条件-动态条件查询
从多个条件中选择一个

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

SQL映射文件

<!--    /*单条件动态查询*/-->
    <select id="selectByConditionSingle" resultMap="BrandResultMap">
    select *from tb_brand /*where*/
    <where>
    <choose>  <!--    相当于switch-->
        <when test="status != null and status != '' ">status=#{status}</when> <!--    相当于case-->
        <when test="companyName != null and companyName != '' "> company_name like #{companyName}</when><!--    相当于case-->
        <when test="brandName != null and brandName != '' ">  brand_name like #{brandName}</when><!--    相当于case-->
          <otherwise>1=1</otherwise> <!-- 相当于default-->
    </choose>
    </where>

    </select>

练习:添加、添加-返回主键
添加

1、编写Mapper接口方法:Mapper接口
参数:除了id之外的所有数据
结果:void
2、编写SQL语句:SQL映射文件

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

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

//普通添加
    @Test
    public void TestAdd() throws Exception {

        //加载mybatis核心配置文件 获取SqlsessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获取sqlsession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //获取mapper接口的代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //执行方法
        //模拟接受参数
         int status=0;
        String companyName="鸭梨冒牌有限公司";
         String brandName="鸭梨2代";
         String description="手机中的冒牌机";
         int ordered=132;

        Brand brand=new Brand();
         brand.setStatus(status);
         brand.setCompanyName(companyName);
         brand.setBrandName(brandName);
         brand.setDescription(description);
         brand.setOrdered(ordered);

        mapper.add(brand);

        //提交事务
       // sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

添加-返回主键
在数据添加成功后,需要获取插入数据库数据的主键的值
比如:添加订单和订单项
1、添加订单
2、添加订单项,订单项中需要设置所属订单的id

<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>

总结:返回添加数据的主键
<useGeneratedKeys=“true” keyProperty=“id”>

练习:修改-修改全部字段
1、编写接口方法:Mapper接口
参数:除id外所有参数
返回结果:void或者int
2、编写SQL语句:SQL映射文件
3、执行方法,测试


Mapper接口的方法
/*普通修改*/
    int update(Brand brand);
    
SQL映射文件
 <!--普通修改-->
    <update id="update">
        update tb_brand set brand_name = #{brandName}, company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status}
        where id=#{id};
    </update>

测试方法
 //普通修改
    @Test
    public void TestUpdate() throws Exception {

        //加载mybatis核心配置文件 获取SqlsessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获取sqlsession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //获取mapper接口的代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //执行方法
        //模拟接受参数
        int status=0;
        String companyName="鸭梨冒牌有限公司";
        String brandName="鸭梨2代";
        String description="鸭梨2代,手机中的冒牌机";
        int ordered=132;
        int id=9;
        Brand brand=new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setDescription(description);
        brand.setOrdered(ordered);
        brand.setId(id);

        int count = mapper.update(brand);

        System.out.println(count);

        //提交事务
        // sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

修改-修改动态字段
1、编写接口方法:Mapper接口
参数:部分数据封装到对象中
返回结果:void
2、编写SQL语句:SQL映射文件
可以使用标签代替set
3、执行方法,测试

test测试方法

 <!--动态修改-->
    <update id="updateOne">
           update tb_brand /*set*/
            <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 and ordered != ''  ">ordered = #{ordered},</if>
        <if test="description != null and description != '' ">description = #{description},</if>
        <if test="status != null and status != '' ">status = #{status}</if>
            </set>
        where id=#{id};

    </update>

练习:删除一个,批量删除

删除一个
1、编写接口方法:Mapper接口
参数:id
返回结果:void
2、编写SQL语句:SQL映射文件
3、执行方法,测试

test测试方法

  <!--普通删除-->
    <delete id="deleteById">
        delete from tb_brand where id=#{id};
    </delete>

批量删除
1、编写接口方法:Mapper接口
参数:id数组
返回结果:void
2、编写SQL语句:SQL映射文件
3、执行方法,测试

使用@Param注解取别名后 SQL映射文件的collection就得使用ids
没使用注解就得使用array;SQL映射文件中的in后面的 (); 可以使用属性open 和close 填上对应的 ( ) 就行
Mapper接口
/*动态删除*/
    void deleteByIds(@Param("ids") int ids[]);

SQL映射文件
  <!--动态删除  separator分隔符 用 , 分割开来
    mybatis会将数组参数默认封装为一个Map集合
    默认使用array数组
    可以使用@Param注解改变map集合的默认key值-->
    <delete id="deleteByIds">

        delete from tb_brand where id
        in(
        <foreach collection="ids" item="id" separator=",">
            #{id}
        </foreach>
        );
    </delete>

MyBatis参数传递
MyBatis接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式
单个参数:
1、POJO类型:直接使用,但注意的是pojo的属性名得和SQL语句的参数占位符得一致
2、Map集合:直接使用,但注意的是Map的键名得和SQL语句的参数占位符得一致
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注解,替换Map集合中默认的arg键名
map.put(“arg0”,参数值1)
map.put(“arg1”,参数值2)
map.put(“param1”,参数值1)
map.put(“param2”,参数值2)
在这里插入图片描述

注解开发–注解完成增删改查
使用注解开发会比配置文件开发更加方便
查询:@Select
添加:@Insert
修改:@Update
删除:@Delete

*简单的功能用注解,复杂的功能用xml配置文件

在这里插入图片描述

JavaScript简介and引入方式

在这里插入图片描述
引入方式
![在这里插入图片描述](https://img-blog.csdnimg.cn/0cd6e1459a724858bb1f0047e38bf013.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5aSp5aSpJibng63niLFqYXZh5byA5Y-R,size_20,color_FFFFFF,t_70](https://img-blog.csdnimg.cn/ac4fa62415ae44acaa3b49cc3315262c.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5aSp5aSpJibng63niLFqYXZh5byA5Y-R,size_20,color_FFFFFF,t_70,g_se,x_16)
在这里插入图片描述

书写语法and输出语句
在这里插入图片描述
在这里插入图片描述

变量and数据类型
在这里插入图片描述
在这里插入图片描述
运算符
在这里插入图片描述
在这里插入图片描述
函数
在这里插入图片描述
在这里插入图片描述
JavaScript对象

Array对象
在这里插入图片描述

String对象
在这里插入图片描述
trim() 去除字符串前后两端的空白字符

自定义对象
在这里插入图片描述
DOM概述
在这里插入图片描述

获取Element
在这里插入图片描述
事件监听
在这里插入图片描述
事件绑定
在这里插入图片描述

在这里插入图片描述
正则表达式
在这里插入图片描述

JavaWeb技术栈
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

Tomcat基本使用
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

Servlet
在这里插入图片描述

在这里插入图片描述
servlet执行流程and生命周期
在这里插入图片描述
在这里插入图片描述
servlet方法介绍and体系结构
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

urlPattern 访问路径的配置
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

request response介绍and request继承体系
在这里插入图片描述
在这里插入图片描述
request获取请求数据
在这里插入图片描述
在这里插入图片描述

request通用方式获取请求参数
在这里插入图片描述
请求参数中文乱码问题dopost解决方式
在这里插入图片描述
doget乱码解决方式
在这里插入图片描述
在这里插入图片描述

请求转发
在这里插入图片描述

response设置响应数据功能介绍
在这里插入图片描述
重定向
在这里插入图片描述
路径问题的虚拟目录
在这里插入图片描述
在这里插入图片描述
response响应字符and字节数据
在这里插入图片描述
在这里插入图片描述

SqlSessionFactoryUtils 工具类

public class SqlSessionFactoryUtils {
    //提升作用域
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //静态代码块会随着类的加载而自动执行 且只执行一次
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //2.2获取sqlSession、对象
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值