JavaWeb--Mybatis--2022年9月25日
第一节 Mybatis概述
1.Mybatis概念
tips:
持久层是什么:
负责将数据保存到数据库的那一层代码,以后开发我们会将操作数据库的Java代码作为持久层,而Mybatis就是对jdbc代码进行了封装
JavaEE三层框架:表现层,业务层,持久层
框架:
框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型
在框架的基础之上构建软件编写更加高效、规范、通用、可扩展
2.JDBC缺点
分析:
3.Mybatis优化
硬编码可以配置到配置文件
操作繁琐的地方mybatis都自动完成
第二节 Mybatis快速入门--查询user表中所有的数据
1.创建user表,添加数据
create database mybatis; use mybatis; drop table if exists tb_user; create table tb_user( id int primary key auto_increment, username varchar(20), password varchar(20), gender char(1), addr varchar(30) ); INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京'); INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津'); INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');
2.创建模块,导入坐标:在创建好的模块中的pom.xml配置文件中添加依赖的坐标
<dependencies>
<!--mybatis 依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--junit 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- 添加slf4j日志api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<!-- 添加logback-classic依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- 添加logback-core依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
注意:需要在项目的resources目录下创建logback的配置文件
3.编写MyBatis核心配置文件-->替换连接信息,解决硬编码问题,在模块下的resources目录下创建mybatis的配置文件mybatis-config.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> <typeAliases> <package name="com.itmao.pojo"/> </typeAliases> <!-- environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的 environment --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <!--数据库连接信息--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> <environment id="test"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <!--数据库连接信息--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <!--加载sql映射文件--> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
4.编写SQL映射文件,统一管理sql语句,解决硬编码问题,在模块的resources目录下创建映射配置文件UserMapper.xml,内容如下:
<?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"> <mapper namespace="test"> <select id="selectAll" resultType="com.itheima.pojo.User"> select * from tb_user; </select> </mapper>
5.编码
在com.itmao.pojo包下创建User类
public class User { private int id; private String username; private String password; private String gender; private String addr; }
在com.itmao包下编写MybatisDemo测试类
public class MyBatisDemo { public static void main(String[] args) throws Exception { //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象,用它来执行sql SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 执行sql List<User> users = sqlSession.selectList("test.selectAll"); //参数是一个字符串,该字符串必须是映射配置文件的namespace.id System.out.println(users); //4. 释放资源 sqlSession.close(); } }
6.解决SQL映射文件的警告提示:在入门案例映射文件中中存在报红的情况。问题如下:
产生的原因:Idea和数据库没有建立连接,不识别表信息,但是大家一定要记住,它并不影响程序的执行。
解决方式:在Idea中配置MySQL数据库连接。步骤如下
点击IDEA有边框的Database,在展开的界面点解+,选择DataSource,再选择MySQL
在弹出的界面进行基本信息的填写
点击完成后就能看到如下界面
而此界面就和navicat工具一样可以进行数据库的操作,也可以编写SQL语句
第三节 Mapper代理开发
1.Mapper代理方式的目的
解决原生方式中的硬编码
简化后期执行SQL
2.使用Mapper代理必须满足以下要求
定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下(编译后在同一个文件夹就行)如下图:
设置SQL映射文件的namespace属性为Mapper接口全限定名
在Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致
案例代码实现
在com.itmao.mapper包下创建UserMapper接口,代码如下:
public interface UserMapper { List<User> selectAll(); }
在resources下创建com/itmao/mapper目录,并在该目录下创建UserMapper.xml映射配置文件
namespace:空间名称,必须对应接口的全限定名
<mapper namespace="com.itmao.mapper.UserMapper"> <select id="selectAll" resultType="com.itmao.pojo.User"> select * from tb_user; </select> </mapper>
创建测试类
/** * Mybatis 代理开发 */ public class MyBatisDemo2 { public static void main(String[] args) throws IOException { //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象,用它来执行sql SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 执行sql //3.1 获取UserMapper接口的代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> users = userMapper.selectAll(); System.out.println(users); //4. 释放资源 sqlSession.close(); } }
第四节 核心配置文件
1.核心配置文件的具体内容及书写规范,可以通过官网查看 XML配置
2.多环境配置
3.类型别名
第五节 mybatis练习--配置文件实现CRUD
1.环境准备
A.数据库表(tb_brand)及数据准备
-- 删除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);
B.实体类brand准备,在com.itmao.pojo包下创建
public class Brand { // id 主键 private Integer id; // 品牌名称 private String brandName; // 企业名称 private String companyName; // 排序字段 private Integer ordered; // 描述信息 private String description; // 状态:0:禁用 1:启用 private Integer status; //省略 setter and getter。自己写时要补全这部分代码 }
C.编写测试用例,在test/java目录下创建包及测试用例,项目结构如下
D.安装MyBatisX插件
MyBatisX是一款基于IDEA的快速开发插件,为效率而生。
主要功能
XML映射配置文件和接口方法间相互跳转
根据接口方法生成statement
安装方式:File--》Seetings--》plugins--》搜索MyBatisX--》点击安装--》重启IDEA
2.查询所有数据
第一步:在mybatis-config.xml里加载sql映射文件
<mappers> <!--加载sql映射文件--> <mapper resource="com\itmao\mapper\UserMapper.xml"/> <mapper resource="com\itmao\mapper\BrandMapper.xml"/> </mappers>
第二步:编写接口方法
public interface BrandMapper { /** * 查询所有 */ List<Brand> selectAll(); }
第三步:编写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"> <mapper namespace="com.itheima.mapper.BrandMapper"> <select id="selectAll" resultType="brand"> select * from tb_brand; </select> </mapper>
第四步:编写测试代码
@Test public void testSelectAll() throws IOException { //1. 获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法 List<Brand> brands = brandMapper.selectAll(); System.out.println(brands); //5. 释放资源 sqlSession.close(); }
注意:如果实体类属性名称和数据库的列名不一致,会导致数据封装不成功,也就是会导致实体类有些属性值是null,有以下两种解决方法:
a、给字段起别名:sql语句可以这么写
<select id="selectAll" resultType="brand">
select
id, brand_name as brandName, company_name as companyName, ordered, description, status
from tb_brand;
</select>
或者使用sql片段
b、使用resultMap定义字段和属性的映射关系
3.查询详情
A、编写接口方法
/** * 查看详情:根据Id查询 */ Brand selectById(int id);
B、编写映射文件
<select id="selectById" resultMap="brandResultMap"> select * from tb_brand where id = #{id}; </select>
C、编写测试代码
@Test public void testSelectById() throws IOException { //接收参数,该id以后需要传递过来 int id = 1; //1. 获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法 Brand brand = brandMapper.selectById(id); System.out.println(brand); //5. 释放资源 sqlSession.close(); }
E、参数占位符
注意:以后开发使用#{}占位符
F、parameterType使用
G、SQL语句中特殊字段处理
4.多条件查询
A、编写接口方法:共三种方法
//@Param("找映射文件里面的占位符")
List<Brand> selectByCondition(@Param("status") int status, @Param("companyName") String companyName,@Param("brandName") String brandName);
//映射文件里的占位符会自动去找get占位符方法,所以映射文件里占位符最好写实体类里的属性名称
List<Brand> selectByCondition(Brand brand);
//映射文件里的占位符会找Map对应键的值
List<Brand> selectByCondition(Map map);
B、编写SQL语句
<select id="selectByCondition" resultMap="brandResultMap"> select * from tb_brand where status = #{status} and company_name like #{companyName} and brand_name like #{brandName} </select>
C、编写测试用例
@Test public void testSelectByCondition() throws IOException { //接收参数 int status = 1; String companyName = "华为"; String brandName = "华为"; // 处理参数 companyName = "%" + companyName + "%"; brandName = "%" + brandName + "%"; //1. 获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法 //方式一 :接口方法参数使用 @Param 方式调用的方法 //List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName); //方式二 :接口方法参数是 实体类对象 方式调用的方法 //封装对象 /* Brand brand = new Brand(); brand.setStatus(status); brand.setCompanyName(companyName); brand.setBrandName(brandName);*/ //List<Brand> brands = brandMapper.selectByCondition(brand); //方式三 :接口方法参数是 map集合对象 方式调用的方法 Map map = new HashMap(); map.put("status" , status); map.put("companyName", companyName); map.put("brandName" , brandName); List<Brand> brands = brandMapper.selectByCondition(map); System.out.println(brands); //5. 释放资源 sqlSession.close(); }
5.单个条件(动态SQL)
A、动态SQL的实现
B、实现多条件动态SQL需要使用if标签和where标签
if标签:条件判断
test属性:逻辑表达式
<select id="selectByCondition" resultMap="brandResultMap"> select * from tb_brand where <if test="status != null"> and status = #{status} </if> <if test="companyName != null and companyName != '' "> and company_name like #{companyName} </if> <if test="brandName != null and brandName != '' "> and brand_name like #{brandName} </if> </select>
where标签
作用:替换where关键字;会动态的去掉第一个条件前的and;如果所有的参数没有值则不加where关键字
<select id="selectByCondition" resultMap="brandResultMap"> select * from tb_brand <where> <if test="status != null"> and status = #{status} </if> <if test="companyName != null and companyName != '' "> and company_name like #{companyName} </if> <if test="brandName != null and brandName != '' "> and brand_name like #{brandName} </if> </where> </select>
//注意,需要给每个条件前都加上and
C、单条件动态SQL实现:页面端选择什么筛选条件就用什么条件去筛选
编写SQL方法
** * 单条件动态查询 * @param brand * @return */ List<Brand> selectByConditionSingle(Brand brand);
编写SQL语句
<select id="selectByConditionSingle" resultMap="brandResultMap"> select * from tb_brand <where> <choose><!--相当于switch--> <when test="status != null"><!--相当于case--> status = #{status} </when> <when test="companyName != null and companyName != '' "><!--相当于case--> company_name like #{companyName} </when> <when test="brandName != null and brandName != ''"><!--相当于case--> brand_name like #{brandName} </when> </choose> </where> </select>
编写测试代码
@Test public void testSelectByConditionSingle() throws IOException { //接收参数 int status = 1; String companyName = "华为"; String brandName = "华为"; // 处理参数 companyName = "%" + companyName + "%"; brandName = "%" + brandName + "%"; //封装对象 Brand brand = new Brand(); //brand.setStatus(status); brand.setCompanyName(companyName); //brand.setBrandName(brandName); //1. 获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法 List<Brand> brands = brandMapper.selectByConditionSingle(brand); System.out.println(brands); //5. 释放资源 sqlSession.close(); }
6.添加数据
编写mapper接口
/** * 添加 */ void add(Brand brand);
编写映射文件
<insert id="add">
insert into tb_brand (brand_name, company_name, ordered, description, status)
values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>
编写测试代码
@Test public void testAdd() throws IOException { //接收参数 int status = 1; String companyName = "波导手机"; String brandName = "波导"; String description = "手机中的战斗机"; int ordered = 100; //封装对象 Brand brand = new Brand(); brand.setStatus(status); brand.setCompanyName(companyName); brand.setBrandName(brandName); brand.setDescription(description); brand.setOrdered(ordered); //1. 获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //SqlSession sqlSession = sqlSessionFactory.openSession(true); //设置自动提交事务,这种情况不需 要手动提交事务了 //3. 获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法 brandMapper.add(brand); //提交事务 sqlSession.commit(); //5. 释放资源 sqlSession.close(); }
添加后返回主键:只需要在映射文件里面修改,增加两个属性
<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:指定将获取到的主键值封装到实体类的哪个属性里
7.修改
编写mapper接口
/** * 修改 */ void update(Brand brand);
编写映射sql文件
<update id="update"> update tb_brand <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"> ordered = #{ordered}, </if> <if test="description != null and description != ''"> description = #{description}, </if> <if test="status != null"> status = #{status} </if> </set> where id = #{id}; </update>
编写测试代码
@Test public void testUpdate() throws IOException { //接收参数 int status = 0; String companyName = "波导手机"; String brandName = "波导"; String description = "波导手机,手机中的战斗机"; int ordered = 200; int id = 6; //封装对象 Brand brand = new Brand(); brand.setStatus(status); // brand.setCompanyName(companyName); // brand.setBrandName(brandName); // brand.setDescription(description); // brand.setOrdered(ordered); brand.setId(id); //1. 获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //SqlSession sqlSession = sqlSessionFactory.openSession(true); //3. 获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法 int count = brandMapper.update(brand); System.out.println(count); //提交事务 sqlSession.commit(); //5. 释放资源 sqlSession.close(); }
8.删除一行数据
编写mapper接口
/**
* 根据id删除
*/
void deleteById(int id);
编写映射sql文件
<delete id="deleteById">
delete from tb_brand where id = #{id};
</delete>
编写测试代码
@Test
public void testDeleteById() throws IOException {
//接收参数
int id = 6;
//1. 获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2. 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3. 获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4. 执行方法
brandMapper.deleteById(id);
//提交事务
sqlSession.commit();
//5. 释放资源
sqlSession.close();
}
9.批量删除
编写mapper接口
/**
* 批量删除
*/
void deleteByIds(int[] ids);
编写映射sql文件
<delete id="deleteByIds">
delete from tb_brand where id
in
<foreach collection="array" item="id" separator="," open="(" close=")">
#{id}
</foreach>
;
</delete>
编写测试代码
@Test
public void testDeleteByIds() throws IOException {
//接收参数
int[] ids = {5,7,8};
//1. 获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2. 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3. 获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4. 执行方法
brandMapper.deleteByIds(ids);
//提交事务
sqlSession.commit();
//5. 释放资源
sqlSession.close();
}
10.MyBatis参数传递
第六节 mybatis练习--注解实现CRUD
*******************************************************************************************************************************************************************************************************************************
*******************************************************************************************************
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!