From 3a5c052054edafa3eb8a14c65fe56ae863a35c7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=96=E5=BF=83=E5=A6=8D?= <2392642810@qq.com> Date: Mon, 1 Jan 2024 22:54:12 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../20231221 Mybatis.md" | 315 -------- ...43\347\220\206\345\274\200\345\217\221.md" | 691 ++++++++++++++++ ...36\345\210\240\346\224\271\346\237\245.md" | 765 ++++++++++++++++++ ...36\345\210\240\346\224\271\346\237\245.md" | 508 ------------ ... mybatis\346\225\264\345\220\210spring.md" | 318 ++++++++ ...0231229 \346\225\264\345\220\210spring.md" | 265 ++++++ 6 files changed, 2039 insertions(+), 823 deletions(-) delete mode 100644 "03 \350\265\226\345\277\203\345\246\215/20231221 Mybatis.md" create mode 100644 "03 \350\265\226\345\277\203\345\246\215/20231221 Mybatis\344\273\243\347\220\206\345\274\200\345\217\221.md" create mode 100644 "03 \350\265\226\345\277\203\345\246\215/20231222 \344\273\243\347\220\206\345\274\200\345\217\221\345\242\236\345\210\240\346\224\271\346\237\245.md" delete mode 100644 "03 \350\265\226\345\277\203\345\246\215/20231222 \345\242\236\345\210\240\346\224\271\346\237\245.md" create mode 100644 "03 \350\265\226\345\277\203\345\246\215/20231228 mybatis\346\225\264\345\220\210spring.md" create mode 100644 "03 \350\265\226\345\277\203\345\246\215/20231229 \346\225\264\345\220\210spring.md" diff --git "a/03 \350\265\226\345\277\203\345\246\215/20231221 Mybatis.md" "b/03 \350\265\226\345\277\203\345\246\215/20231221 Mybatis.md" deleted file mode 100644 index 0d0c080..0000000 --- "a/03 \350\265\226\345\277\203\345\246\215/20231221 Mybatis.md" +++ /dev/null @@ -1,315 +0,0 @@ -## Mybatis (Mapper代理方式) - -**可做优化:** - -1. 设置别名 - -2. 参数写到专属文件,解除硬编码【写死在源代码中,而源代码有所改动,就要重新编译,测试,打包,整个流程,耦合度太高,好比把电池焊死在手机主板上了,不方便换电池,而且只能用专用品牌的电池,解耦,或解除硬编码编程方式,就好比可以随意换电池的玩具,只认型号,不认品牌,只要是5号电池就可以用。】 - -### 总结 - -使用Mapper代理方式,必须满足以下要求: - -1. 定义与SQL映射文件同名的Mapper接口, -2. 在 Mapper 接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致 -3. 设置SQL映射文件的namespace属性为Mapper接口全限定名 -4. 核心配置文件中的mapper路径要根据sql映射文件的实际路径改变(具体文件或包扫描) -5. 执行sql的方法改成getMapper()的方法 - -### 例题: - -**1.** **创建 brand 表,添加数据** - -~~~ mysql --- 删除tb_brand表 -drop table if exists tb_brand; --- 创建tb_brand表 -create table tb_brand( - id int primary key auto_increment, -- id 主键 - brand_name varchar(20), -- 品牌名称 - company_name varchar(20), -- 企业名称 - ordered int, -- 排序字段 - description varchar(100), -- 描述信息 - status int -- 状态:0:禁用 1:启用 -); --- 添加数据 -insert into tb_brand (brand_name, company_name, ordered, description, status) -values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0), - ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1), - ('小米', '小米科技有限公司', 50, 'are you ok', 1); - -SELECT * FROM tb_brand; -~~~ - -**2.** **创建模块,根据数据表,编写对应的 java 类** - -在 com.mdd.pojo 包下创建 User类 - -~~~ java -package com.mdd.pojo; - -/** - * 品牌 - * - * alt + 鼠标左键:整列编辑 - * - * 在实体类中,基本数据类型建议使用其对应的包装类型 - */ - -public class Brand { - // id 主键 - private Integer id; - // 品牌名称 - private String brandName; - // 企业名称 - private String companyName; - // 排序字段 - private Integer ordered; - // 描述信息 - private String description; - // 状态:0:禁用 1:启用 - private Integer status; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getBrandName() { - return brandName; - } - - public void setBrandName(String brandName) { - this.brandName = brandName; - } - - public String getCompanyName() { - return companyName; - } - - public void setCompanyName(String companyName) { - this.companyName = companyName; - } - - public Integer getOrdered() { - return ordered; - } - - public void setOrdered(Integer ordered) { - this.ordered = ordered; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - @Override - public String toString() { - return "Brand{" + - "id=" + id + - ", brandName='" + brandName + '\'' + - ", companyName='" + companyName + '\'' + - ", ordered=" + ordered + - ", description='" + description + '\'' + - ", status=" + status + - '}'; - } -} -~~~ - -**3.** **导入坐标** - -在创建好的模块中的 pom.xml 配置文件中添加依赖的坐标 - -~~~ xml - - - 4.0.0 - - com.mdd - mybatis_02 - 1.0-SNAPSHOT - - - 17 - 17 - UTF-8 - - - - - - com.mysql - mysql-connector-j - 8.1.0 - - - - org.mybatis - mybatis - 3.5.13 - - - - junit - junit - 4.13.2 - test - - - - -~~~ - -**4.** **编写 MyBatis 核心配置文件 - > 替换连接信息** - -在模块下的 resources 目录下创建mybatis的配置文件 mybatis-config.xml ,内容如下: - -~~~ xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -~~~ - -**5. 编写 SQL 映射文件 —> 统一管理 sql 语句,在resources下创建与代理商文件路径相同** - -将sql映射文件(改成与mapper接口同名)移动到该目录,并将namespace属性为Mapper接口完整路径(引用) - -~~~ xml - - - - - - - - - - - - - - - - -~~~ - -**6.定义与 SQL 映射文件同名的 Mapper 接口** - -~~~ java -package com.mdd.mapper; - -import com.mdd.pojo.Brand; - -import java.util.List; - -public interface BrandMapper { - // 方法名就是SQL映射文件中sql语句的id,并保持返回值类型一致 - // 查询所有 - List selectAll(); - // 按照id查询 - Brand selectById(Integer id); - // 查询id大于某个值的 - List selectAllById(Integer id); -} -~~~ - -**7. 编写测试类** - -~~~ java -package com.mdd; - -import com.mdd.mapper.BrandMapper; -import com.mdd.pojo.Brand; -import org.apache.ibatis.io.Resources; -import org.apache.ibatis.session.SqlSession; -import org.apache.ibatis.session.SqlSessionFactoryBuilder; -import org.junit.Test; - -import java.io.IOException; -import java.util.List; - -public class TestBrand { - @Test - public void selectAll() throws IOException { - //1. 加载mybatis的核心配置文件,获取 sqlSession 对象 - SqlSession sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")).openSession(); - //2. 获取UserMapper接口的代理对象,执行SQL语句 - BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); - // 查询所有 - List brands = mapper.selectAll(); - System.out.println(brands); - - // 指定id查询 - Brand brand = mapper.selectById(1); - System.out.println(brand); - - // 查询id大于某个值的 - List list = mapper.selectAllById(1); - System.out.println(list); - - //3. 释放资源 - sqlSession.close(); - } -} -~~~ \ No newline at end of file diff --git "a/03 \350\265\226\345\277\203\345\246\215/20231221 Mybatis\344\273\243\347\220\206\345\274\200\345\217\221.md" "b/03 \350\265\226\345\277\203\345\246\215/20231221 Mybatis\344\273\243\347\220\206\345\274\200\345\217\221.md" new file mode 100644 index 0000000..270cc3b --- /dev/null +++ "b/03 \350\265\226\345\277\203\345\246\215/20231221 Mybatis\344\273\243\347\220\206\345\274\200\345\217\221.md" @@ -0,0 +1,691 @@ +## Mybatis 代理开发 + +### 1.配置pom.xml + +```xml + + + 4.0.0 + + org.example + untitled + 1.0-SNAPSHOT + + + 8 + 8 + UTF-8 + + + + + + junit + junit + + 4.13.2 + + test + + + + com.mysql + mysql-connector-j + 8.1.0 + + + + + org.mybatis + mybatis + 3.5.13 + + + + + +``` + +### 2.mysql建库建表 + +### 3.main包下java包建一个域名pojo包(com.yina.pojo)里建一个User类 + +与mysql的tb_user表里字段名对应 + +```java +package com.yina.pojo; + +public class User { + private Integer id; + private String username; + private Integer age; + private String gender; + + // javaBean + + public User(Integer id, String username, Integer age, String gender) { + this.id = id; + this.username = username; + this.age = age; + this.gender = gender; + } + + public User() { + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", username='" + username + '\'' + + ", age=" + age + + ", gender='" + gender + '\'' + + '}'; + } +} +``` + +### 4.main包下java包下的域名包(com.yina)包下创建mapper包下创建UserMapper接口 + +```java +package com.yina.mapper; + +import com.yina.pojo.User; + +import java.util.List; + +public interface UserMapper { + // 1 这个接口就是我们创建的代理类 + List findAll(); // UserMapper.xml的id +} +``` + +### 5.mian包里的resources包里创建mybatis-config.xml文件 + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +### 6.mian包里的resources包里创建域名.mapper包(com.yina.mapper)下创建UserMapper.xml文件 + +```xml + + + + + + + + + + + + + + + insert into tb_user (id,username,age,gender) values (#{id},#{username},#{age},#{gender}); + + + + delete from tb_user where id = #{id}; + + + + update tb_user + set username = #{username}, + age = #{age}, + gender = #{gender} + where id = #{id}; + + + +``` + +### 7.main包下java包下创建App类 + +```java +package com.yina; + +import com.yina.mapper.UserMapper; +import com.yina.pojo.User; +import org.apache.ibatis.io.Resources; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +public class App { + public static void main(String[] args) throws IOException { + // 1 加载mybatis的核心配置文件 + 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 list = sqlSession.selectList("test.selectAll"); // namespace.id +// System.out.println(list); +// User user = sqlSession.selectOne("test.selectById", 9); +// System.out.println(user); + // 为了解决这里硬编码的问题,采用代理开发,因为test.selectById这个路径是写死的,如果UserMapper.xml的namespace一改这里就要跟着改 + UserMapper mapper = sqlSession.getMapper(UserMapper.class); + List users = mapper.findAll(); + System.out.println(users); + + // 4 释放资源 + sqlSession.close(); + } +} + +``` + +6.test包下java包下创建域名包(com.yina)下创建TestUser类(应该是不用这部了) + +```java +package com.yina; + +import com.yina.pojo.User; +import org.apache.ibatis.io.Resources; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +// 因为每用一个方法都要重复执行所以把这一部分代码封装成一个方法 +public class TestUser { + private SqlSessionFactory getSqlSessionFactory() throws IOException { + String resource = "mybatis-config.xml"; + InputStream inputStream = Resources.getResourceAsStream(resource); + SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); + return sqlSessionFactory; + } + + // 查询所有 + @Test + public void testSelectAll() throws IOException { + // 1 加载mybatis的核心配置文件,调用刚刚封装的方法 + SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); + // 2 创建sqlSession对象,用来执行SQL语句 + SqlSession sqlSession = sqlSessionFactory.openSession(); + // 3 执行SQL语句,test是UserMapper.xml文件的namespace,selectAll为id,执行不同的mysql语句 + List list = sqlSession.selectList("test.selectAll"); // namespace.id + System.out.println(list); + // 4 释放资源 + sqlSession.close(); + } + + // 查询一个 + @Test + public void testSelectById() throws IOException { + // 1 加载mybatis的核心配置文件 + SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); + // 2 创建sqlSession对象,用来执行SQL语句 + SqlSession sqlSession = sqlSessionFactory.openSession(); + // 3 执行SQL语句 + User list = sqlSession.selectOne("test.selectById",3); // namespace.id + System.out.println(list); + // 4 释放资源 + sqlSession.close(); + } + + // 增 + @Test + public void insert() throws IOException { + SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); + SqlSession sqlSession = sqlSessionFactory.openSession(); + User user = new User(); + user.setId(1); + user.setUsername("李四"); + user.setAge(18); + user.setGender("男"); + sqlSession.insert("test.insert",user); + // 默认事务是开启的,要手动提交事务 + sqlSession.commit(); // 手动提交事务 + System.out.println("添加成功"); + sqlSession.close(); + } + + // 删 + @Test + public void delete() throws IOException { + SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); + SqlSession sqlSession = sqlSessionFactory.openSession(true); // 自动提交事务 + sqlSession.delete("test.deleteById",1); + System.out.println("删除成功"); + sqlSession.close(); + } + + // 改 + @Test + public void update() throws IOException { + SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); + SqlSession sqlSession = sqlSessionFactory.openSession(true); // 自动提交事务 + User user = new User(9,"李四",18,"男"); + sqlSession.update("test.update",user); + System.out.println("修改成功"); + sqlSession.close(); + } +} +``` + +## Mybatis练习1 + +### 1.添加数据库 + +```mysql +- 删除tb_brand表 +drop table if exists tb_brand; +- 创建tb_brand表 +create table tb_brand +( +- id 主键 +id int primary key auto_increment, +- 品牌名称 +brand_name varchar(20), +- 企业名称 +company_name varchar(20), +- 排序字段 +ordered int, +- 描述信息 +description varchar(100), +- 状态:0:禁用 1:启用 +status int +); +- 添加数据 +insert into tb_brand (brand_name, company_name, ordered, +description, status) +values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', +0), +('华为', '华为技术有限公司', 100, '华为致力于把数字世界 +带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1), +('小米', '小米科技有限公司', 50, 'are you ok', 1); +``` + +### 2.给pom.xml文件建好坐标 + +```xml + + + 4.0.0 + + com + untitled3 + 1.0-SNAPSHOT + + + 8 + 8 + UTF-8 + + + + + com.mysql + mysql-connector-j + 8.1.0 + + + junit + junit + 4.13.2 + test + + + org.mybatis + mybatis + 3.5.13 + + + +``` + +### 3.在域名(com)包下创建pojo包创建Brand实体类 + +```java +package com.pojo; + +public class Brand { +// 和数据库字段一一对应 + private Integer id; + private String brandName; + private String companyName; + private Integer ordered; + private String description; + private Integer status; + + @Override + public String toString() { + return "Brand{" + + "id=" + id + + ", brandName='" + brandName + '\'' + + ", companyName='" + companyName + '\'' + + ", ordered=" + ordered + + ", description='" + description + '\'' + + ", status=" + status + + '}'; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getBrandName() { + return brandName; + } + + public void setBrandName(String brandName) { + this.brandName = brandName; + } + + public String getCompanyName() { + return companyName; + } + + public void setCompanyName(String companyName) { + this.companyName = companyName; + } + + public Integer getOrdered() { + return ordered; + } + + public void setOrdered(Integer ordered) { + this.ordered = ordered; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public Brand() { + } + + public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) { + this.id = id; + this.brandName = brandName; + this.companyName = companyName; + this.ordered = ordered; + this.description = description; + this.status = status; + } +} +``` + +### 4.在maina包下的resources包下创建jdbc.properties + +事先设置好变量放在jdbc.properties,然后放在mybatis-config.xml文件 + +``` +jdbc.driver = com.mysql.cj.jdbc.Driver +jdbc.url = jdbc:mysql:///db_2023?useSSL=false +jdbc.username = root +jdbc.password = root +``` + +### 5.在main包下的resources包下创建mybatis-config.xml文件 + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +### 6.在main包的resources包下创建域名包(com)创建mapper包创建BrandMapper.xml文件 + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +### 7.在java包下域名包(com)下创建mapper包创建BrandMapper代理接口 + +```java +package com.mapper; + +import com.pojo.Brand; + +import java.util.List; + +public interface BrandMapper { +// selectAll是BrandMapper.xml的id,Brand是Brand类,因为返回的是数组 +// 查询所有 + List selectAll(); +// 查询一个 +// Brand selectById(int id); +// void delete(); +// 按id查询品牌 + Brand selectById(int id); +} +``` + +### 8.在test包下创建域名包(com)下创建MybatisTest测试类 + +```java +package com; + +import com.mapper.BrandMapper; +import com.pojo.Brand; +import org.apache.ibatis.io.Resources; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +public class MybatisTest { +// 因为要测试所以注解test + @Test + public void findAll() throws IOException { + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 +// String resource = "mybatis-config.xml"; +// InputStream inputStream = Resources.getResourceAsStream(resource); +// SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(); + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + List brands = mapper.selectAll(); + System.out.println(brands); + // 5 释放资源 + sqlSession.close(); + } + @Test + public void findOne() throws IOException { + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 +// String resource = "mybatis-config.xml"; +// InputStream inputStream = Resources.getResourceAsStream(resource); +// SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(); + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + Brand brand = mapper.selectById(1); + System.out.println(brand); + // 5 释放资源 + sqlSession.close(); + } +} +``` + diff --git "a/03 \350\265\226\345\277\203\345\246\215/20231222 \344\273\243\347\220\206\345\274\200\345\217\221\345\242\236\345\210\240\346\224\271\346\237\245.md" "b/03 \350\265\226\345\277\203\345\246\215/20231222 \344\273\243\347\220\206\345\274\200\345\217\221\345\242\236\345\210\240\346\224\271\346\237\245.md" new file mode 100644 index 0000000..a3ae458 --- /dev/null +++ "b/03 \350\265\226\345\277\203\345\246\215/20231222 \344\273\243\347\220\206\345\274\200\345\217\221\345\242\236\345\210\240\346\224\271\346\237\245.md" @@ -0,0 +1,765 @@ +## 代理开发增删改查 + +### 1.配置pom.xml导入坐标 + +```xml + + + 4.0.0 + + com + untitled04 + 1.0-SNAPSHOT + + + 8 + 8 + UTF-8 + + + + + com.mysql + mysql-connector-j + 8.1.0 + + + junit + junit + 4.13.2 + test + + + org.mybatis + mybatis + 3.5.13 + + + +``` + +### 2.建库建表(略过) + +### 3.在java包下创建域名包(com)下创建pojo包创建Brand实体类 + +```java +package com.pojo; + +public class Brand { +// 和数据库字段一一对应 + private Integer id; + private String brandName; + private String companyName; + + @Override + public String toString() { + return "Brand{" + + "id=" + id + + ", brandName='" + brandName + '\'' + + ", companyName='" + companyName + '\'' + + ", ordered=" + ordered + + ", description='" + description + '\'' + + ", status=" + status + + '}'; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getBrandName() { + return brandName; + } + + public void setBrandName(String brandName) { + this.brandName = brandName; + } + + public String getCompanyName() { + return companyName; + } + + public void setCompanyName(String companyName) { + this.companyName = companyName; + } + + public Integer getOrdered() { + return ordered; + } + + public void setOrdered(Integer ordered) { + this.ordered = ordered; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public Brand() { + } + + public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) { + this.id = id; + this.brandName = brandName; + this.companyName = companyName; + this.ordered = ordered; + this.description = description; + this.status = status; + } + + private Integer ordered; + private String description; + private Integer status; +} + +``` + +### 4.在java包下resources包下创建jdbc.properties文件 + +这是方便给mybatis-config.xml文件配置jdbc,所以这是变量 + +```properties +jdbc.driver = com.mysql.cj.jdbc.Driver +jdbc.url = jdbc:mysql:///db_2023?useSSL=false&allowPublicKeyRetrieval=true +jdbc.username = root +jdbc.password = root +``` + +### 5.在java包下resources包下创建mybatis-config.xml文件 + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +### 6.在java包下域名包(com)下创建mapper包下创建BrandMapper代理接口 + +```java +package com.mapper; + +import com.pojo.Brand; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +public interface BrandMapper { +// selectAll是BrandMapper.xml的id,Brand是Brand类,因为返回的是数组 +// 查询所有 + List selectAll(); + +// 查询一个 +// Brand selectById(int id); +// void delete(); +// 按id查询品牌 + Brand selectById(int id); + +// 用@Param("里面放名字给BrandMapper.xml接收变量") +// 散装参数 + List selectByCondition( + @Param("status") int status, + @Param("companyName") String companyName, + @Param("brandName") String brandName + ); + +// 对brand对象做参数,这个最好用(通用) + List selectByCondition(Brand brand); + +// 使用Map集合对象做参数 + List selectByCondition(Map map); + +// 单条件查询 + List selectByConditionSingle(Brand brand); + +// 添加品牌 + void insert(Brand brand); + +// 修改品牌 + void update(Brand brand); + +// 删除品牌 + void deleteById(int id); +// 删除多个 + void deleteByIds(@Param("ids") int[] id); +} +``` + +### 7.在resources包下的域名包(com)创建mapper包下创建BrandMapper.xml + +```xml + + + + + + + + + + + + + + + + + + + insert into tb_brand (brand_name, company_name, ordered, description, status) + values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status}); + + + + update tb_brand + + + status = #{status}, + + + brand_name = #{brandName}, + + + company_name = #{companyName}, + + + ordered = #{ordered}, + + + description = #{description} + + + where id = #{id}; + + + + delete + from tb_brand + where id = #{id}; + + + + + delete + from tb_brand + where id in + + #{id} + ; + + + + + + + + + + + + + + + + + + + + +``` + +### 8.在test包下java包下创建域名包(com)创建MybatisTest测试类 + +```java +package com; + +import com.mapper.BrandMapper; +import com.pojo.Brand; +import org.apache.ibatis.io.Resources; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MybatisTest { +// 因为要测试所以注解test + @Test + public void findAll() throws IOException { + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 +// String resource = "mybatis-config.xml"; +// InputStream inputStream = Resources.getResourceAsStream(resource); +// SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(); + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + List brands = mapper.selectAll(); + System.out.println(brands); + // 5 释放资源 + sqlSession.close(); + } + @Test + public void findOne() throws IOException { + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 +// String resource = "mybatis-config.xml"; +// InputStream inputStream = Resources.getResourceAsStream(resource); +// SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(); + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + Brand brand = mapper.selectById(1); + System.out.println(brand); + // 5 释放资源 + sqlSession.close(); + } + @Test + public void findByCondition() throws IOException { + // 接收参数,模拟从浏览器接收数据 + int status = 1; + String companyName = "华为"; + String brandName = "华为"; +// 模糊查询的通配符是%,所以查的时候加上% + companyName = "%" + companyName + "%"; + brandName = "%" + brandName + "%"; + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 +// String resource = "mybatis-config.xml"; +// InputStream inputStream = Resources.getResourceAsStream(resource); +// SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(); + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + List brands = mapper.selectByCondition(status, companyName, brandName); + System.out.println(brands); + // 5 释放资源 + sqlSession.close(); + } + @Test + public void findByCondition2() throws IOException { + // 接收参数,模拟从浏览器接收数据 + int status = 1; + String companyName = "华为"; + String brandName = "华为"; +// 模糊查询的通配符是%,所以查的时候加上% + companyName = "%" + companyName + "%"; + brandName = "%" + brandName + "%"; +// 将传递的散装参数,封装成一个对象 + Brand brand = new Brand(); + brand.setBrandName(brandName); + brand.setCompanyName(companyName); + brand.setStatus(status); + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 +// String resource = "mybatis-config.xml"; +// InputStream inputStream = Resources.getResourceAsStream(resource); +// SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(); + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + List brands = mapper.selectByCondition(brand); + System.out.println(brands); + // 5 释放资源 + sqlSession.close(); + } + @Test + public void findByCondition3() throws IOException { + // 接收参数,模拟从浏览器接收数据 + int status = 1; + String companyName = "华为"; + String brandName = "华为"; + +// 模糊查询的通配符是%,所以查的时候加上% + companyName = "%" + companyName + "%"; + brandName = "%" + brandName + "%"; + +// 将传递的散装参数,封装成一个对象 +// Brand brand = new Brand(); +// brand.setBrandName(brandName); +// brand.setCompanyName(companyName); +// brand.setStatus(status); + +// 将传递的散装参数,封装成一个map对象 + Map map = new HashMap(); + //map.put("status",status); +// 这里的"brandName"是和BrandMapper.xml的#{brandName}匹配的 + map.put("brandName",brandName); + map.put("companyName",companyName); + + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 +// String resource = "mybatis-config.xml"; +// InputStream inputStream = Resources.getResourceAsStream(resource); +// SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(); + + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + List brands = mapper.selectByCondition(map); + System.out.println(brands); + + // 5 释放资源 + sqlSession.close(); + } + @Test + public void findByCondition4() throws IOException { + // 接收参数,模拟从浏览器接收数据 + int status = 1; + String companyName = "华为"; + String brandName = "华为"; + String description = "好吃"; + +// 模糊查询的通配符是%,所以查的时候加上% + companyName = "%" + companyName + "%"; + brandName = "%" + brandName + "%"; + description = "%" + description + "%"; + +// 将传递的散装参数,封装成一个对象 + Brand brand = new Brand(); + // brand.setBrandName(brandName); + // brand.setCompanyName(companyName); + brand.setDescription(description); + // brand.setStatus(status); + +// 将传递的散装参数,封装成一个map对象 +// Map map = new HashMap(); +// //map.put("status",status); +//// 这里的"brandName"是和BrandMapper.xml的#{brandName}匹配的 +// map.put("brandName",brandName); +// map.put("companyName",companyName); + + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 +// String resource = "mybatis-config.xml"; +// InputStream inputStream = Resources.getResourceAsStream(resource); +// SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(); + + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + List brands = mapper.selectByConditionSingle(brand); + System.out.println(brands); + + // 5 释放资源 + sqlSession.close(); + } + @Test + public void insert() throws IOException { + // 接收参数,模拟从浏览器接收数据 + int status = 1; + String companyName = "IST"; + String brandName = "得啵椅子"; + String description = "会所"; + int ordered = 11; + +// 模糊查询的通配符是%,所以查的时候加上% +// 因为是添加不是查询语句所以不需要弄这个 +// companyName = "%" + companyName + "%"; +// brandName = "%" + brandName + "%"; +// description = "%" + description + "%"; + +// 将传递的散装参数,封装成一个对象 + Brand brand = new Brand(); + brand.setBrandName(brandName); + brand.setCompanyName(companyName); + brand.setDescription(description); + brand.setStatus(status); + brand.setOrdered(ordered); + + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + + // 2 sqlSession,true代表开启自动提交事务 + SqlSession sqlSession = sessionFactory.openSession(true); + + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + mapper.insert(brand); + System.out.println(brand); + + // 手动提交事务 +// sqlSession.commit(); + System.out.println(brand.getId()); + + // 5 释放资源 + sqlSession.close(); + } + @Test + public void deleteById() throws IOException { + // 接收参数,模拟从浏览器接收数据 + int id = 6; + + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + + // 2 sqlSession,true代表开启自动提交事务 + SqlSession sqlSession = sessionFactory.openSession(true); + + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + mapper.deleteById(id); + System.out.println(id); + + // 5 释放资源 + sqlSession.close(); + } + @Test + public void deleteByIds() throws IOException { + // 接收参数,模拟从浏览器接收数据 + int[] ids = {1,2,3}; + + // 1 sqlSessionFactory +// 放入mybatis-config.xml的路径 +// 简化此步骤 + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + + // 2 sqlSession,true代表开启自动提交事务 + SqlSession sqlSession = sessionFactory.openSession(true); + + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + + // 4 执行sql +// 这里的selectAll是BrandMapper接口里的方法也是BrandMapper.xml里的id + mapper.deleteByIds(ids); + System.out.println(ids); + + // 5 释放资源 + sqlSession.close(); + } +} +``` + +## 一点点的注解开发 + +### 1.把BrandMapper.xml删掉 + +### 2.修改BrandMapper接口 + +```java +package com.mapper; + +import com.pojo.Brand; +import org.apache.ibatis.annotations.Delete; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; + +public interface BrandMapper { + // 这样就可以了,对于简单的mysql语句有效 + @Select("select * from tb_brand") + List findAll(); + + @Select("select * from tb_brand where id = #{id}") + Brand findOne(int id); + + @Delete("delete from tb_brand where id = #{id}") + void deleteById(int id); +} +``` + +### 3.修改测试类 + +```java +package com; + +import com.mapper.BrandMapper; +import com.pojo.Brand; +import org.apache.ibatis.io.Resources; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MybatisTest { +// 因为要测试所以注解test + @Test + public void findAll() throws IOException { + // 1 sqlSessionFactory + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(); + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + // 4 执行sql + List all = mapper.findAll(); + System.out.println(all); + // 5 释放资源 + sqlSession.close(); + } + @Test + public void findOne() throws IOException { + // 1 sqlSessionFactory + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(); + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + // 4 执行sql + Brand one = mapper.findOne(7); + System.out.println(one); + // 5 释放资源 + sqlSession.close(); + } + @Test + public void deleteOne() throws IOException { + // 1 sqlSessionFactory + SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); + // 2 sqlSession + SqlSession sqlSession = sessionFactory.openSession(true); + // 3 获取代理 + BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); + // 4 执行sql + mapper.deleteById(7); + // 5 释放资源 + sqlSession.close(); + } +} +``` + diff --git "a/03 \350\265\226\345\277\203\345\246\215/20231222 \345\242\236\345\210\240\346\224\271\346\237\245.md" "b/03 \350\265\226\345\277\203\345\246\215/20231222 \345\242\236\345\210\240\346\224\271\346\237\245.md" deleted file mode 100644 index 6392af1..0000000 --- "a/03 \350\265\226\345\277\203\345\246\215/20231222 \345\242\236\345\210\240\346\224\271\346\237\245.md" +++ /dev/null @@ -1,508 +0,0 @@ -# 笔记 - -1.导入maven环境 - 2.创建dao接口,里面定了你需要对数据库执行什么操作 - 3.编写mapper文件,sql映射文件,写上你的sql语句 - 4.创建mybatis主配置文件,读取配置文件中的内容,连接到数据库 - 5.使用mybatis对象执行sql语句:sqlSession对象 - 6.关闭连接:sqlSession.close(); - - -# 作业 - -数据库表 - -```java -CREATE TABLE `t_user` ( - `id` int NOT NULL AUTO_INCREMENT, - `username` varchar(255) DEFAULT NULL, - `password` varchar(255) DEFAULT NULL, - `email` varchar(255) DEFAULT NULL, - `phone` varchar(255) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; - -INSERT INTO `t_user`(`id`, `username`, `password`, `email`, `phone`) VALUES (1, 'admin', 'admin', 'admin@qq.com', '1008611'); -INSERT INTO `t_user`(`id`, `username`, `password`, `email`, `phone`) VALUES (2, 'root', 'root', 'root@qq.com', '1008622'); -INSERT INTO `t_user`(`id`, `username`, `password`, `email`, `phone`) VALUES (19, 'admin2', 'root2', 'root@qq.com2', '1008644'); - - -``` - -创建实体类 - -```java -public class User { - private Integer id; - private String username; - private String password; - private String email; - private String phone; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public User() { - } - - public User(Integer id, String username, String password, String email, String phone) { - this.id = id; - this.username = username; - this.password = password; - this.email = email; - this.phone = phone; - } - @Override - public String toString() { - return "User{" + - "id=" + id + - ", username='" + username + '\'' + - ", password='" + password + '\'' + - ", email='" + email + '\'' + - ", phone='" + phone + '\'' + - '}'; - } - -} - - -``` - -创建maven项目 - -```java - - - 4.0.0 - - org.example - mybatis - 1.0-SNAPSHOT - - - UTF-8 - 1.9 - 1.9 - - - - - - junit - junit - 4.11 - test - - - - mysql - mysql-connector-java - 8.0.19 - - - - org.mybatis - mybatis - 3.5.4 - - - - org.junit.jupiter - junit-jupiter - RELEASE - compile - - - - - - - - - - - src/main/java - - **/*.properties - **/*.xml - - false - - - - - - -``` - -配置mybatis的主配置文件 - -```java - - - - - - - ---> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -``` - -编写mybatis工具类 - -```java -public class MyBatisUtils { - - private static SqlSessionFactory factory = null; - - static { - //读取mybatis.xml配置文件 - String config="mybatis.xml"; - try { - //将配置文件加入到流中 - InputStream in = Resources.getResourceAsStream(config); - //创建factory对象 - factory = new SqlSessionFactoryBuilder().build(in); - - } catch (IOException e) { - e.printStackTrace(); - } - - - } - public static SqlSession getSqlSession(){ - SqlSession sqlSession = null; - if (factory!=null){ - //如果 factory!=null 就创建 sqlSession对象 - sqlSession = factory.openSession(false);//非自动提交事务 - } - - return sqlSession; - } -} - -``` - -定义接口 - -```java -public interface UserManagerDao { - - /** - * 查询所有的数据 用于视图展示 - * @return 返回一个List集合 - */ - public List queryUser(); - - - /** - * 添加 - * @param user 一个user对象 - * @return 成功返回true 失败返回false - */ - public Boolean addUser(User user); - - /** - * 删除用户 - * @param id 需要删除的用户id - * @return 成功返回true 失败返回false - */ - public Boolean delUser(String id); - - /** - * 修改用户信息 - * @param user 需要一个user对象 - * @return 成功返回true 失败返回false - */ - public Boolean updateUser(User user); - - /** - * 按照用户名查找用户 - * @param name 需要查找的用户名 - * @return 返回一个List集合 - */ - public List likeUser(String name); - - - -} - -``` - -xml文件 - -```java - - - - - - - - - - insert into t_user values(#{id},#{username},#{username},#{email},#{phone}) - - - - delete from t_user where id=#{id} - - - - update t_user set username=#{username},password=#{password},email=#{email},phone=#{phone} where id=#{id} - - - - -``` - -编写daoImpl - -```java - -public class UserManagerDaoImpl implements UserManagerDao { - - /** - * 查询所有的数据 用于视图展示 - * - * @return 返回一个List集合 - */ - @Override - public List queryUser() { - //获取sqlSession对象 - SqlSession sqlSession = MyBatisUtils.getSqlSession(); - String sqlId = "com.mybatis.dao.UserManagerDao.queryUser"; - //执行sql语句 - List userList = sqlSession.selectList(sqlId); - // sqlSession.commit(); //mybatis默认不会手动提交事务,在修改数据之后要 提交事务 - //关闭连接 - sqlSession.close(); - return userList; - } - - - /** - * 添加 - * - * @param user 一个user对象 - * @return 成功返回true 失败返回false - */ - @Override - public Boolean addUser(User user) { - //获取sqlSession对象 - SqlSession sqlSession = MyBatisUtils.getSqlSession(); - String sqlId = "com.mybatis.dao.UserManagerDao.addUser"; - //执行sql语句 - int updateCount = sqlSession.update(sqlId,user); - sqlSession.commit(); //mybatis默认不会手动提交事务,在修改数据之后要 提交事务 - //关闭连接 - sqlSession.close(); - if(updateCount>0){ - return true; - }else{ - return false; - } - - } - - /** - * 删除用户 - * - * @param id 需要删除的用户id - * @return 成功返回true 失败返回false - */ - @Override - public Boolean delUser(String id) { - //获取sqlSession对象 - SqlSession sqlSession = MyBatisUtils.getSqlSession(); - String sqlId = "com.mybatis.dao.UserManagerDao.delUser"; - //执行sql语句 - int delete = sqlSession.delete(sqlId, id); - sqlSession.commit(); //设置为自动提交事务 - //关闭连接 - sqlSession.close(); - if(delete>0){ - return true; - }else { - return false; - } - - } - - /** - * 修改用户信息 - * - * @param user 需要一个user对象 - * @return 成功返回true 失败返回false - */ - @Override - public Boolean updateUser(User user) { - //获取sqlSession对象 - SqlSession sqlSession = MyBatisUtils.getSqlSession(); - String sqlId = "com.mybatis.dao.UserManagerDao.updateUser"; - //执行sql语句 - int updateCount = sqlSession.update(sqlId,user); - sqlSession.commit(); //设置为自动提交事务 - //关闭连接 - sqlSession.close(); - if(updateCount>0){ - return true; - }else { - return false; - } - - } - - /** - * 按照用户名查找用户 - * - * @param name 需要查找的用户名 - * @return 返回一个List集合 - */ - @Override - public List likeUser(String name) { - SqlSession sqlSession = MyBatisUtils.getSqlSession(); - String sqlId = "com.mybatis.dao.UserManagerDao.likeUser"; - List userList = sqlSession.selectList(sqlId, name); - sqlSession.commit(); - //关闭连接 - sqlSession.close(); - return userList; - } -} - -``` - -Test类 - -```java -class UserManagerDaoImplTest { - - UserManagerDaoImpl userManagerDao = new UserManagerDaoImpl(); - - @Test - void queryUser() { - List userList = userManagerDao.queryUser(); - for (User user : userList) { - System.out.println(user); - } - } - @Test - void ListUser() { - - SqlSession sqlSession = MyBatisUtils.getSqlSession(); - UserManagerDao userDao = sqlSession.getMapper(UserManagerDao.class); - List userList = userDao.queryUser(); - for (User user : userList) { - System.out.println(user); - } - } - - @Test - void addUser() { - User user = new User(null,"admin","root","root@qq.com","1008644"); - Boolean flag = userManagerDao.addUser(user); - System.out.println(flag); - - } - - @Test - void delUser() { - Boolean flag = userManagerDao.delUser("23"); - System.out.println(flag); - } - - @Test - void updateUser() { - User user = new User(19,"admin2","root2","root@qq.com2","1008644"); - Boolean flag = userManagerDao.updateUser(user); - System.out.println(flag); - } - - @Test - void likeUser() { - List userList = userManagerDao.likeUser("admin"); - for (User user : userList) { - System.out.println(user); - } - } -} - -``` \ No newline at end of file diff --git "a/03 \350\265\226\345\277\203\345\246\215/20231228 mybatis\346\225\264\345\220\210spring.md" "b/03 \350\265\226\345\277\203\345\246\215/20231228 mybatis\346\225\264\345\220\210spring.md" new file mode 100644 index 0000000..c9b0192 --- /dev/null +++ "b/03 \350\265\226\345\277\203\345\246\215/20231228 mybatis\346\225\264\345\220\210spring.md" @@ -0,0 +1,318 @@ +1. 打开IDEA,新建一个项目(模块),开启MySQL + +2. 编写Pom.mxl文件,导入相关依赖的坐标 + +~~~ xml + + + 4.0.0 + + com.mdd + spring_02 + 1.0-SNAPSHOT + + + 8 + 8 + UTF-8 + + + + + org.springframework + spring-context + 5.1.10.RELEASE + + + + org.springframework + spring-jdbc + 5.1.10.RELEASE + + + org.springframework + spring-test + 5.1.10.RELEASE + + + + org.mybatis + mybatis + 3.5.13 + + + + org.mybatis + mybatis-spring + 2.0.5 + + + + com.mysql + mysql-connector-j + 8.1.0 + + + + junit + junit + 4.13.2 + test + + + + com.alibaba + druid + 1.1.23 + + + +~~~ + +3. 创建数据库的相关表,列,并导入数据 +4. 在src下的 main下的 java里新建包com.mdd.domain,并在 domain下创建实体类 Brand + +~~~ java +public class Brand { + // id 主键 + private Integer id; + // 品牌名称 + private String brandName; + // 企业名称 + private String companyName; + // 排序字段 + private Integer ordered; + // 描述信息 + private String description; + // 状态:0:禁用 1:启用 + private Integer status; + // 无参、全参、get,set方法、tostring方法 +~~~ + +5. 编写代理接口 com.mdd.mapper.BrandMapper.java ,用来从数据库从获取数据 + +~~~ java +public interface BrandMapper { + // 给不符字段添加别名(解决数据为null的问题) + @Select("select id, brand_name brandName, company_name companyName, ordered, description, status from tb_brand") + // 查询所有数据 + List findAll(); + // 根据相应条件查询,动态SQL + List selectByCondition(Brand brand); +} +~~~ + +6. 在 com.mdd.config 目录下,编写Spring核心配置类文件SpringConfig.java,写上@Configuration注解,将这个类变成配置类 + +~~~ java +@Configuration +// 引入 JdbcConfig,MybatisConfig 配置文件 +@Import({JdbcConfig.class, MybatisConfig.class}) +public class SpringConfig { +} +~~~ + +7. 在 com.mdd.config 目录下,编写 JdbcConfig.java也就是mysql驱动配置类文件 + +~~~ java +public class JdbcConfig { + // jdbc负责连接mysql,配置驱动,url,用户名,密码 + // spring如何加载第三方的Bean,通过写一个方法,返回这个bea 的类弄。并上这个方法上写一个注解@Bean + @Bean + public DataSource dataSource(){ + // 此时 DataSource 为实现类,需通过 druid 代理 dataSource + DruidDataSource ds = new DruidDataSource(); + // 配置连接四要素:驱动、url、密码、用户名 + ds.setDriverClassName("com.mysql.cj.jdbc.Driver"); + ds.setUrl("jdbc:mysql://localhost:3306/mybatis?useSSl=false"); + ds.setUsername("root"); + ds.setPassword("root"); + return ds; + } +} +~~~ + +8. 在 com.mdd.config 目录下,编写MybatisConfig.java配置类文件 + +~~~ java +public class MybatisConfig { + // 这里做两件事,1.获取SqlSessionFactoryBean 2.获取Mapper代理的包 + //1.获取SqlSessionFactoryBean + @Bean + public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){ + SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean(); + // ssfb 也要做两件事:1.设置实体类的别名 2.设置数据源 + ssfb.setTypeAliasesPackage("com.mdd.domain"); // 实体类所在包的位置 + ssfb.setDataSource(dataSource); + return ssfb; + } + @Bean + //2.获取Mapper代理的包 + public MapperScannerConfigurer mapperScannerConfigurer(){ + MapperScannerConfigurer msc = new MapperScannerConfigurer(); + msc.setBasePackage("com.mdd.mapper"); // 代理类包的位置 + return msc; + } +} +~~~ + +9. 测试代理的功能 + +~~~ java +public class App { + public static void main(String[] args) { + // 1.通过 spring核心配置文件 获取 IOC容器 + ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class); + // 2.获取代理接口的对象 + BrandMapper brandMapper = ctx.getBean(BrandMapper.class); + List all = brandMapper.findAll(); + System.out.println(all); + } +} +~~~ + +10. 遇上复杂的sql,及要使用动态SQL时就要配置对应的XML配置文件在resources下根据代理接口com/mdd/mapper的路径,创建一个**同包同名**的xml文件 com/mdd/mapper/BrandMapper.xml + +~~~ xml + + + + + + + + + + +~~~ + +11. 在Test中测试代理的方法 + +~~~ java +@RunWith(SpringJUnit4ClassRunner.class) // 加载spring为Junit专门提供的运行类 +@ContextConfiguration(classes = SpringConfig.class) // 加载Spring核心配置文件,IOC容器 +public class BrandTest { + //通过自动装配的形式,直接将 bean 注入进来 + @Autowired + private BrandMapper brandMapper; + @Test + public void test01(){ +// List all = brandMapper.findAll(); +// System.out.println(all); + + // 1. 模拟浏览器向服务器发送了查询的数据 + String brandName = "华为"; + String companyName = "华为"; + // 2. 因为是模糊查询,参数要加 % + brandName = "%"+brandName+"%"; + companyName = "%"+companyName+"%"; + // 3. 将数据分装成一个对象 + Brand brand = new Brand(); + brand.setBrandName(brandName); + brand.setCompanyName(companyName); + // 4. 调用代理对象接口中的方法 + List brands = brandMapper.selectByCondition(brand); + System.out.println(brands); + } +} +~~~ + +12. 模拟业务层,先有一个接口,再写一个实现类 + +com.mdd.service.BrandService.java 接口 + +~~~ java +public interface BrandService { + List findAll(); +} +~~~ + +com.mdd.service.impl.BrandServiceImpl.java 实现类 + +~~~ java +@Service +public class BrandServiceImpl implements BrandService { + // 业务层要实现数据的调用,就要借助数据层的对象 + // 将数据层的对象,自动装配进来 + @Autowired + private BrandMapper brandMapper; + @Override + public List findAll() { + System.out.println("业务层的命运齿轮开始运转。。。。"); + // 返回数据层获得的结果 + return brandMapper.findAll(); + } +} +~~~ + +13. 测试类,模拟表现层调用业务层 + +~~~ java +@RunWith(SpringJUnit4ClassRunner.class) // 加载spring为Junit专门提供的运行类 +@ContextConfiguration(classes = SpringConfig.class) // 加载Spring核心配置文件,IOC容器 +public class BrandTest { + //通过自动装配的形式,直接将 bean 注入进来 + @Autowired + private BrandMapper brandMapper; + @Autowired + private BrandService brandService; // 要什么就自动装配什么,装配的是接口,面向接口编程 + @Test + public void test01(){ +// List all = brandMapper.findAll(); +// System.out.println(all); + // 1. 模拟浏览器向服务器发送了查询的数据 + String brandName = "华为"; + String companyName = "华为"; + // 2. 因为是模糊查询,参数要加 % + brandName = "%"+brandName+"%"; + companyName = "%"+companyName+"%"; + // 3. 将数据分装成一个对象 + Brand brand = new Brand(); + brand.setBrandName(brandName); + brand.setCompanyName(companyName); + // 4. 调用代理对象接口中的方法 + List brands = brandMapper.selectByCondition(brand); + System.out.println(brands); + } + + // 模拟表现层调用业务层 + @Test + public void test02(){ + List all = brandService.findAll(); + System.out.println(all); + } +} +~~~ + +14. SptingConfig 类 扫包 + +~~~ java +@Configuration +@Import({JdbcConfig.class, MybatisConfig.class}) +@ComponentScan("com.mdd") +public class SpringConfig { +} +~~~ + +注意:不要漏掉以下操作: + +1. 将实现类用注解@Service,标记为一个Bean + +2. 修改SpringConfig.java,将业务层的包,用 @CompenentScan("com.mdd") ,扫描进来 \ No newline at end of file diff --git "a/03 \350\265\226\345\277\203\345\246\215/20231229 \346\225\264\345\220\210spring.md" "b/03 \350\265\226\345\277\203\345\246\215/20231229 \346\225\264\345\220\210spring.md" new file mode 100644 index 0000000..5d788f7 --- /dev/null +++ "b/03 \350\265\226\345\277\203\345\246\215/20231229 \346\225\264\345\220\210spring.md" @@ -0,0 +1,265 @@ +# 复习 + +### JdbcConfig + +```java +package com.mdd.config; + +import com.alibaba.druid.pool.DruidDataSource; +import org.springframework.context.annotation.Bean; + +import javax.sql.DataSource; + +public class JdbcConfig { + @Bean + public DataSource dataSource(){ + DruidDataSource ds = new DruidDataSource(); + ds.setDriverClassName("com.mysql.cj.jdbc.Driver"); + ds.setUrl("jdbc:mysql:///masql"); + ds.setUsername("root"); + ds.setPassword("123456"); + return ds; + } +} + +``` + +### MybatisConfig + +```java +package com.mdd.config; + +import org.mybatis.spring.SqlSessionFactoryBean; +import org.mybatis.spring.mapper.MapperScannerConfigurer; +import org.springframework.context.annotation.Bean; + +import javax.sql.DataSource; + +public class MybatisConfig { + @Bean + public SqlSessionFactoryBean sessionFactoryBean(DataSource dataSource){ + SqlSessionFactoryBean ssfy = new SqlSessionFactoryBean(); + ssfy.setTypeAliasesPackage("com.mdd.domain"); + ssfy.setDataSource(dataSource); + return ssfy; + } + @Bean + public MapperScannerConfigurer mapperScannerConfigurer(){ + MapperScannerConfigurer mc = new MapperScannerConfigurer(); + mc.setBasePackage("com.mdd.mapper"); + return mc; + } +} + +``` + +### SpringConfig + +```java +package com.mdd.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +@Configuration +@ComponentScan("com.mdd") +@Import({JdbcConfig.class,MybatisConfig.class}) +public class SpringConfig { + +} + +``` + +### User + +```java +package com.mdd.domain; + +public class User { + private Integer id; + private String name; + private String sex; + private Integer age; + + public User() { + } + + public User(Integer id, String name, String sex, Integer age) { + this.id = id; + this.name = name; + this.sex = sex; + this.age = age; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", name='" + name + '\'' + + ", sex='" + sex + '\'' + + ", age=" + age + + '}'; + } +} + +``` + +### UserMapper + +```java +package com.mdd.mapper; + +import com.mdd.domain.User; +import org.apache.ibatis.annotations.Delete; +import org.apache.ibatis.annotations.Insert; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.util.List; + +public interface UserMapper { + @Select("select * from tb_ures") + List findAll(); + + @Select("select * from tb_ures where id=#{id}") + User findByid(int id); + + @Delete("delete from tb_ures where id=#{id}") + void deleteByid(int id); + + @Update("Updata tb_ures set name=#{name},sex=#{sex},age=#{age} where id=#{id}") + void updetaByid(User user); + + @Insert("insert into tb_ures(name,sex,age) values(#{name},#{sex},#{age})") + void insertByid(User user); +} + +``` + +### App 测试类 + +```java +import com.mdd.config.SpringConfig; +import com.mdd.domain.User; +import com.mdd.mapper.UserMapper; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import java.util.List; + +public class App { + public static void main(String[] args) { + ApplicationContext ctx=new AnnotationConfigApplicationContext(SpringConfig.class); + UserMapper bean = ctx.getBean(UserMapper.class); + List all = bean.findAll(); + System.out.println(all); + } +} + +``` + +### 架包 + +```xml + + + 4.0.0 + + com.mdd + spring_10_review + 1.0-SNAPSHOT + + + 8 + 8 + UTF-8 + + + + + org.springframework + spring-context + 5.2.25.RELEASE + + + + org.springframework + spring-jdbc + 5.2.25.RELEASE + + + org.springframework + spring-test + 5.2.25.RELEASE + + + + org.mybatis + mybatis + 3.5.13 + + + + org.mybatis + mybatis-spring + 2.0.5 + + + + com.mysql + mysql-connector-j + 8.1.0 + + + + junit + junit + 4.13.2 + test + + + + com.alibaba + druid + 1.1.23 + + + + + +``` \ No newline at end of file -- Gitee