diff --git "a/44 \344\273\243\347\221\236/0102MVC.md" "b/44 \344\273\243\347\221\236/0102MVC.md" new file mode 100644 index 0000000000000000000000000000000000000000..22aefe6e99f39b1e0f925e2a6a9d4e8ea56af176 --- /dev/null +++ "b/44 \344\273\243\347\221\236/0102MVC.md" @@ -0,0 +1,182 @@ +## 笔记 + +名称:@ComponentScan + +类型:类注解 + +属性 + +excludeFilters:排除扫描路径中加载的bean,需要指定类别(type)与具体项(classes) + +includeFilters:加载指定的bean,需要指定类别(type)与具体项(classes) + +名称:@RequestParam + +类型:形参注解 + +位置:SpringMVC控制器方法形参定义前面 + +作用:绑定请求参数与处理器方法形参间的关系 + +参数: + +required:是否为必传参数 + +defaultValue:参数默认值 + +名称:@EnableWebMvc + +类型:配置类注解 + +位置:SpringMVC配置类定义上方 + +作用:开启SpringMVC多项辅助功能 + +## 作业 + +步骤; + +1.pom.xml,将没有的东西复原,如java,test。。。 + +```xml + + 4.0.0 + com.xlu + ssmvc + war + 1.0-SNAPSHOT + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + org.springframework + spring-webmvc + 5.2.25.RELEASE + + + + + + + + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + 88 + / + + + + + + + +``` + +2.创建com.xlu.config.SpringMvcConfig + +```java +package com.xlu.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.xlu") +public class SpringMvcConfig { +} +``` + +3.com.xlu.config.WeblnitConfig + +```java +package com.xlu.config; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public class WeblnitConfig extends AbstractAnnotationConfigDispatcherServletInitializer { + + + protected Class[] getRootConfigClasses() { + return new Class[0];//加载spring的核心配置文件 + } + + protected Class[] getServletConfigClasses() { + //加载springmvc的核心配置文件 + return new Class[]{SpringMvcConfig.class}; + } + + protected String[] getServletMappings() { + //设置从/开始的路径,都归tomcat管理 + return new String[]{"/"}; + } +} +``` + +4.com.xlu.controller.UserController + +```java +package com.xlu.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.xml.ws.RequestWrapper; +import java.security.PublicKey; + +@Controller +public class UserController { + + + @RequestMapping("/save") + @ResponseBody + public String userSave(){ + + return "ok";//http://localhost:88/save网址,查看是否出现OK + + } + + @RequestMapping("/book") + @ResponseBody + public String book(){ + return "book is ok!";//http://localhost:88/book网址,查看是否有东西 + } + + + @RequestMapping("/hello") + @ResponseBody + public String hello(){ + + System.out.println(666); + return "666";//http://localhost:88/hello网址,查看是否有东西 + + } + +// @RequestMapping("/shouYe") +// public String shouYe(){ +// +// return "index.jsp";//http://localhost:88/shouYe网址,跳转网页出现 helloword +// } + + @RequestMapping("/shouYe") + @ResponseBody + public String shouYe(){ + + return "index.jsp";//http://localhost:88/shouYe网址,出现index.jsp + } + + +} +``` \ No newline at end of file diff --git "a/44 \344\273\243\347\221\236/12 29 \345\244\215\344\271\240.md" "b/44 \344\273\243\347\221\236/12 29 \345\244\215\344\271\240.md" new file mode 100644 index 0000000000000000000000000000000000000000..5d788f7b8b7a115defb8a056cfdf968413586873 --- /dev/null +++ "b/44 \344\273\243\347\221\236/12 29 \345\244\215\344\271\240.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 diff --git "a/44 \344\273\243\347\221\236/1220MyBatis\347\254\224\350\256\260.md" "b/44 \344\273\243\347\221\236/1220MyBatis\347\254\224\350\256\260.md" new file mode 100644 index 0000000000000000000000000000000000000000..8e72f4a2058ccf1f18e2015bf71f9e290601378e --- /dev/null +++ "b/44 \344\273\243\347\221\236/1220MyBatis\347\254\224\350\256\260.md" @@ -0,0 +1,213 @@ +## 笔记 + +### Mybatis 概念 + +- MyBatis 是一款优秀的==持久层框架==,用于简化 JDBC 开发 +- MyBatis 本是 Apache 的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github +- 官网:[https://mybatis.org/mybatis-3/zh/index.html](https://gitee.com/link?target=https%3A%2F%2Fmybatis.org%2Fmybatis-3%2Fzh%2Findex.html) + +**持久层:** + +- 负责将数据到保存到数据库的那一层代码。以后开发我们会将操作数据库的Java代码作为持久层。而Mybatis就是对jdbc代码进行了封装。 +- JavaEE三层架构:表现层、业务层、持久层 + +三层架构在后期会给大家进行讲解,今天先简单的了解下即可。 + +**框架:** + +- 框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型 +- 在框架的基础之上构建软件编写更加高效、规范、通用、可扩展 + +### **JDBC** 缺点 + +- 硬编码,耦合度高(注册驱动、获取连接、SQL语句,不方便后期维护) +- 操作繁琐(手动设置参数,手动封装结果集,没有什么技术含量,而且特别耗费时间的) + +### Mybatis 优化 + +- 硬编码可以配置到==配置文件== +- 操作繁琐的地方mybatis都==自动完成== + +### 几个概念: + +1. 文档官网:[https://mybatis.org/mybatis-3/zh_CN/index.html](https://gitee.com/link?target=https%3A%2F%2Fmybatis.org%2Fmybatis-3%2Fzh_CN%2Findex.html) 或 [http://mybatis.net.cn](https://gitee.com/link?target=http%3A%2F%2Fmybatis.net.cn) +2. 核心配置文件:mybatis-config.xml +3. SQL 映射文件:xxMapper.xml --> 统一管理sql语句,解决硬编码问题 + +## 作业 + +#### 导入坐标 + +``` + + + + com.mysql + mysql-connector-j + 8.1.0 + + + + org.mybatis + mybatis + 3.5.13 + + + + junit + junit + 4.13.2 + test + + + +``` + +#### 编写 MyBatis 核心配置文件 -- > 替换连接信息 + +``` + + + + + + + + + + + + + + + + + + + + +``` + +#### 编写 SQL 映射文件 --> 统一管理sql语句 + +``` + + + + + + + + insert into db_user(name,age,gender) value(#{name},#{age},#{gender}) + + + + delete from db_user where id = #{id} + + + + update db_user set name = #{name},age = #{age},gender = #{gender} where id = #{id} + + +``` + +#### 编写测试类 + +```java +package com.mdd; + +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 { + // 获取 sqlSessionFactory 对象 + SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); + // 获取执行 sql 的对象 + SqlSession sqlSession = sqlSessionFactory.openSession(true); + List list = sqlSession.selectList("test.selectAll"); + + System.out.println(list); + // 释放资源 + sqlSession.close(); + + } + + // 增 + @Test + public void testInsert() throws IOException { + // 获取 sqlSessionFactory 对象 + SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); + // 获取执行 sql 的对象 + SqlSession sqlSession = sqlSessionFactory.openSession(true); + // 创建一个对象 + User user = new User(); + user.setName("老八"); + user.setAge(18); + user.setGender("男"); + + sqlSession.insert("test.insert",user); + System.out.println("添加成功!"); + // 释放资源 + sqlSession.close(); + + } + + // 删 + @Test + public void testDelete() throws IOException { + // 获取 sqlSessionFactory 对象 + SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); + // 获取执行 sql 的对象 + SqlSession sqlSession = sqlSessionFactory.openSession(true); + + sqlSession.delete("test.delete",5); + System.out.println("删除成功!"); + // 释放资源 + sqlSession.close(); + } + + // 改 + @Test + public void testUpdate() throws IOException { + // 获取 sqlSessionFactory 对象 + SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); + // 获取执行 sql 的对象 + SqlSession sqlSession = sqlSessionFactory.openSession(true); + + // 创建一个对象 + User user = new User(); + user.setId(6); + user.setName("小七"); + user.setAge(20); + user.setGender("女"); + + sqlSession.delete("test.update",user); + System.out.println("修改成功!"); + // 释放资源 + sqlSession.close(); + } +} +``` \ No newline at end of file diff --git "a/44 \344\273\243\347\221\236/1221 MyBatis(mapper\344\273\243\347\220\206).md" "b/44 \344\273\243\347\221\236/1221 MyBatis(mapper\344\273\243\347\220\206).md" new file mode 100644 index 0000000000000000000000000000000000000000..445fa04e5a2dc6e5bc67fab306db047d21f4cabd --- /dev/null +++ "b/44 \344\273\243\347\221\236/1221 MyBatis(mapper\344\273\243\347\220\206).md" @@ -0,0 +1,314 @@ +## Mybatis 第2版(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 表,添加数据** + +``` +-- 删除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类 + +``` +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 配置文件中添加依赖的坐标 + +``` + + + 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 ,内容如下: + +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +**5. 编写 SQL 映射文件 —> 统一管理 sql 语句,在resources下创建与代理商文件路径相同** + +将sql映射文件(改成与mapper接口同名)移动到该目录,并将namespace属性为Mapper接口完整路径(引用) + +``` + + + + + + + + + + + + + + + + +``` + +**6.定义与 SQL 映射文件同名的 Mapper 接口** + +``` +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/44 \344\273\243\347\221\236/1222 \345\242\236\345\210\240\346\224\271\346\237\245.md" "b/44 \344\273\243\347\221\236/1222 \345\242\236\345\210\240\346\224\271\346\237\245.md" new file mode 100644 index 0000000000000000000000000000000000000000..d6d789041293c14e5bcf28f949d387f85ecf6b25 --- /dev/null +++ "b/44 \344\273\243\347\221\236/1222 \345\242\236\345\210\240\346\224\271\346\237\245.md" @@ -0,0 +1,490 @@ +# 笔记 + +1.导入maven环境 2.创建dao接口,里面定了你需要对数据库执行什么操作 3.编写mapper文件,sql映射文件,写上你的sql语句 4.创建mybatis主配置文件,读取配置文件中的内容,连接到数据库 5.使用mybatis对象执行sql语句:sqlSession对象 6.关闭连接:sqlSession.close(); + +# 作业 + +数据库表 + +``` +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'); +``` + +创建实体类 + +``` +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 + '\'' + + '}'; + } + +} +``` + +xxxxxxxxxx   4.0.0​  com.mdd  spring_01_quickstart  1.0-SNAPSHOT​            junit      junit      4.13.2      test              org.springframework      spring-context      5.2.25.RELEASE​      src/main/resources/ApplicationContext.xmlApplicationContext.xml​文件名:BookDaoImpl.java​package com.mdd.dao.impl;​import com.mdd.dao.BookDao;​public class BookDaoImpl implements BookDao {    public void save() {        System.out.println("book dao save ...");   }}文件名: BookServiceImpl.java​package com.mdd.service.impl;import com.mdd.dao.BookDao;import com.mdd.dao.impl.BookDaoImpl;import com.mdd.service.BookService;​public class BookServiceImpl implements BookService {​    private BookDao bookDao;​    public void setBookDao(BookDao bookDao) {        this.bookDao = bookDao;   }​    public void save() {        System.out.println("book service save ...");        bookDao.save();   }​}文件名:BookDao.javapackage com.mdd.dao;public interface BookDao {    public void save();}文件名:App.javapackage com.mdd;import com.mdd.service.BookService;import com.mdd.service.impl.BookServiceImpl;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;​public class App {    public static void main(String[] args) {//       BookService bookService = new BookServiceImpl();//       bookService.save();        //1.通过配置文件获取IOC容器        ApplicationContext ctx=new ClassPathXmlApplicationContext("ApplicationContext.xml");        //2.通过IOC容器的getBean 方法,获取对象       BookServiceImpl bookService = (BookServiceImpl) ctx.getBean("bookService");       bookService.save();​   }}文件名:BookService.javapackage com.mdd.service;​public interface BookService {    public void save();}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的主配置文件 + +``` + + + + + + + +--> + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +编写mybatis工具类 + +``` +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; + } +} +``` + +定义接口 + +``` +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文件 + +``` + + + + + + + + + + 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 + +``` +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/44 \344\273\243\347\221\236/1226 IOC\344\270\216DI.md" "b/44 \344\273\243\347\221\236/1226 IOC\344\270\216DI.md" new file mode 100644 index 0000000000000000000000000000000000000000..815fa4dd5f571b5af9fb4c8c83beb954fa2169c7 --- /dev/null +++ "b/44 \344\273\243\347\221\236/1226 IOC\344\270\216DI.md" @@ -0,0 +1,142 @@ +## Ioc和DI + +``` +IoC(Inversion of Control)控制反转 +使用对象时,由主动new产生对象转换为由外部提供对象,此过程中对象创建控制权由程序转移到外部,此思想称为控制反转 +Spring技术对IoC思想进行了实现 +Spring提供了一个容器,称为IoC容器,用来充当IoC思想中的“外部” +IoC容器负责对象的创建、初始化等一系列工作,被创建或被管理的对象在IoC容器中统称为Bean +DI(Dependency Injection)依赖注入 +在容器中建立bean与bean之间的依赖关系的整个过程,称为依赖注入 +``` + +bean生命周期: + +``` +初始化容器 +创建对象(内存分配) +执行构造方法 +执行属性注入(set操作) +执行bean初始化方法 +使用bean +执行业务操作 +关闭/销毁容器 +执行bean销毁方法 +``` + +bean销毁时机 + +``` +容器关闭前触发bean的销毁 +关闭容器方式: +手工关闭容器 +ConfigurableApplicationContext接口close()操作 +注册关闭钩子,在虚拟机退出前先关闭容器再退出虚拟机 + ConfigurableApplicationContext接口registerShutdownHook()操作 + +public class AppForLifeCycle { public static void main( String[] args ) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ctx.close(); }} +``` + +pom.xml + +```java + + + + 4.0.0 + + com.mdd + spring_01_quickstart + 1.0-SNAPSHOT + + + + junit + junit + 4.13.2 + test + + + org.springframework + spring-context + 5.2.25.RELEASE + + + + + +src/main/resources/ApplicationContext.xml +ApplicationContext.xml + + + + + + + +文件名:BookDaoImpl.java + +package com.mdd.dao.impl; + +import com.mdd.dao.BookDao; + +public class BookDaoImpl implements BookDao { + public void save() { + System.out.println("book dao save ..."); + } +} +文件名: BookServiceImpl.java + +package com.mdd.service.impl; +import com.mdd.dao.BookDao; +import com.mdd.dao.impl.BookDaoImpl; +import com.mdd.service.BookService; + +public class BookServiceImpl implements BookService { + + private BookDao bookDao; + + public void setBookDao(BookDao bookDao) { + this.bookDao = bookDao; + } + + public void save() { + System.out.println("book service save ..."); + bookDao.save(); + } + +} +文件名:BookDao.java +package com.mdd.dao; +public interface BookDao { + public void save(); +} +文件名:App.java +package com.mdd; +import com.mdd.service.BookService; +import com.mdd.service.impl.BookServiceImpl; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class App { + public static void main(String[] args) { +// BookService bookService = new BookServiceImpl(); +// bookService.save(); + //1.通过配置文件获取IOC容器 + ApplicationContext ctx=new ClassPathXmlApplicationContext("ApplicationContext.xml"); + //2.通过IOC容器的getBean 方法,获取对象 + BookServiceImpl bookService = (BookServiceImpl) ctx.getBean("bookService"); + bookService.save(); + + } +} +文件名:BookService.java +package com.mdd.service; + +public interface BookService { + public void save(); +} +``` \ No newline at end of file diff --git "a/44 \344\273\243\347\221\236/1227 \345\210\233\345\273\272\345\256\271\345\231\250.md" "b/44 \344\273\243\347\221\236/1227 \345\210\233\345\273\272\345\256\271\345\231\250.md" new file mode 100644 index 0000000000000000000000000000000000000000..4957725d74e0b1c1df4770c2dc57dc3b199a7ab4 --- /dev/null +++ "b/44 \344\273\243\347\221\236/1227 \345\210\233\345\273\272\345\256\271\345\231\250.md" @@ -0,0 +1,44 @@ +创建容器 + +加载多个配置文件 + +``` +ApplicationContext ctx = new ClassPathXmlApplicationContext("bean1.xml", "bean2.xml"); +``` + +Spring提供@Component注解的三个衍生注解 + +@Controller:用于表现层bean定义 + +@Service:用于业务层bean定义 + +@Repository:用于数据层bean定义 + +``` +@Repository("bookDao")public class BookDaoImpl implements BookDao {} +@Servicepublic class BookServiceImpl implements BookService {} +``` + +Spring3.0开启了纯注解开发模式,使用Java类替代配置文件,开启了Spring快速开发赛道Java类代替Spring核心配置文件, + +@Configuration注解用于设定当前类为配置类@ComponentScan注解用于设定扫描路径,此注解只能添加一次,多个数据请用数组格式 + +``` +@ComponentScan({com.mdd.service","com.mdd.dao"}) +//加载配置文件初始化容器 +ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); +//加载配置类初始化容器 +ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class); +``` + +依赖注入 + +使用@Autowired注解开启自动装配模式(按类型) + +``` +@Servicepublic class BookServiceImpl implements BookService { @Autowired private BookDao bookDao; public void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } public void save() { System.out.println("book service save ..."); bookDao.save(); }} +``` + +注意:自动装配基于反射设计创建对象并暴力反射对应属性为私有属性初始化数据,因此无需提供setter方法 + +注意:自动装配建议使用无参构造方法创建对象(默认),如果不提供对应构造方法,请提供唯一的构造方法 \ No newline at end of file diff --git "a/44 \344\273\243\347\221\236/1228MyBatis\346\225\264\345\220\210.md" "b/44 \344\273\243\347\221\236/1228MyBatis\346\225\264\345\220\210.md" new file mode 100644 index 0000000000000000000000000000000000000000..c9b0192d35b4082329ad82713aed813de3de7c33 --- /dev/null +++ "b/44 \344\273\243\347\221\236/1228MyBatis\346\225\264\345\220\210.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