MyBatis 详细教程

网友投稿 753 2022-11-19

MyBatis 详细教程

MyBatis 详细教程

​​MyBatis​​​​Mapper 代理​​​​案例 - 配置文件完成增删改查​​

​​准备工作​​​​查询​​

​​1. 查询所有数据​​​​2. 根据Id查询​​​​3. 多条件查询​​​​4. 多条件查询 - 动态条件查询​​​​5. 单条件查询 - 动态条件查询​​

​​添加​​​​修改​​

​​1. 修改全部字段​​​​2. 修改动态字段​​

​​删除​​

​​1. 删除一个​​​​2. 批量删除​​

​​MyBatis 参数传递​​​​注解完成增删改查​​

MyBatis

​​tb_user.sql​​

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', '男', '西安');INSERT INTO tb_user VALUES (4, '赵六', '111', '女', '上海');

​​pom.xml​​

java 5.1.46 junit junit 4.13 test org.slf4j slf4j-api 1.7.20 ch.qos.logback logback-classic 1.2.3 ch.qos.logback logback-core 1.2.3 org.slf4j slf4j-nop 1.7.5

​​logback.xml​​

[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n

​​mybatis.config.xml​​

​​UserMapper.xml​​

​​MyBatisDemo.java​​

package com.ruochen;import com.ruochen.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;/** * MyBatis 快速入门代码 */public class MyBatisDemo { public static void main(String[] args) throws IOException { // 1. 加载 MyBatis 的核心配置文件,获取 SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2. 获取 SqlSession 对象,用它来执行 sql SqlSession sqlSession = sqlSessionFactory.openSession(); // 3. 执行 sql 语句 List users = sqlSession.selectList("test.selectAll"); System.out.println(users); // 4. 释放资源 sqlSession.close(); }}

[User{id=1, username='zhangsan', password='123', gender='男', addr='北京'}, User{id=2, username='李四', password='234', gender='女', addr='天津'}, User{id=3, username='王五', password='11', gender='男', addr='西安'}, User{id=4, username='赵六', password='111', gender='女', addr='上海'}]

Mapper 代理

package com.ruochen.mapper;import com.ruochen.pojo.User;import java.util.List;public interface UserMapper { List selectAll();}

编码测试

package com.ruochen;import com.ruochen.mapper.UserMapper;import com.ruochen.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;/** * Mapper 代理开发 */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 语句 // List users = sqlSession.selectList("test.selectAll"); // 3.1 获取 UserMapper 接口的代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List users = userMapper.selectAll(); System.out.println(users); // 4. 释放资源 sqlSession.close(); }}

[User{id=1, username='zhangsan', password='123', gender='男', addr='北京'}, User{id=2, username='李四', password='234', gender='女', addr='天津'}, User{id=3, username='王五', password='11', gender='男', addr='西安'}, User{id=4, username='赵六', password='111', gender='女', addr='上海'}]

案例 - 配置文件完成增删改查

准备工作

数据库表:​​tb_brand.sql​​

-- 删除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);SELECT * FROM tb_brand;

实体类:​​Brand.java​​

package com.ruochen.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 + '}'; }}

测试用例:​​test​​​ 中新建​​com.ruochen.test.MyBatisTest.java​​安装 MyBatisX 插件

查询

1. 查询所有数据

编写接口方法:Mapper接口

参数:无结果:List

package com.ruochen.mapper;import com.ruochen.pojo.Brand;import java.util.List;public interface BrandMapper { /** * 查询所有 */ public List selectAll();}

编写 SQL 语句:SQL映射文件

执行方法,测试

@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 brands = brandMapper.selectAll(); System.out.println(brands); // 5. 释放资源 sqlSession.close(); }

2. 根据Id查询

编写接口方法:Mapper接口

参数:id结果:Brand

/** * 查看详情:根据Id查询 */ Brand selectById(int id);

编写 SQL 语句:SQL映射文件

执行方法,测试

@Test public void TestSelectById() throws IOException { // 接收参数 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(); }

3. 多条件查询

编写接口方法:Mapper接口

参数:所有查询条件结果:List

/** * 条件查询 * * 参数接收 * 1. 散装参数:如果方法中有多个参数,需要使用 @Param("SQL参数占位符名称") * 2. 对象参数:对象的属性的名称要和参数占位符名称一致 * 3. map集合参数 * * @param status * @param companyName * @param brandName * @return */// List selectByCondition(@Param("status") int status, @Param("companyName") String companyName, @Param("brandName") String brandName);// List selectByCondition(Brand brand); List selectByCondition(Map map);

编写 SQL 语句:SQL 映射文件

执行方法,测试

/** * 多条件查询 * @throws IOException */ @Test public void TestSelectByCondition() 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); Map map = new HashMap(); map.put("status", status); map.put("companyName", companyName); map.put("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. 执行方法// List brands = brandMapper.selectByCondition(status, companyName, brandName);// List brands = brandMapper.selectByCondition(brand); List brands = brandMapper.selectByCondition(map); System.out.println(brands); // 5. 释放资源 sqlSession.close(); }

中文查询不到结果可将 jdbc 修改为如下​​​​​

4. 多条件查询 - 动态条件查询

修改 SQL 语句即可

5. 单条件查询 - 动态条件查询

Mapper 接口

/** * 单条件动态查询 * @param brand * @return */ List selectByConditionSingle(Brand brand);

SQL 映射文件

可不使用 ,使用 标签

执行方法,测试

/** * 单条件查询 * * @throws IOException */ @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 brands = brandMapper.selectByConditionSingle(brand); System.out.println(brands); // 5. 释放资源 sqlSession.close(); }

添加

编写接口方法:Mapper 接口

参数:除了 id 之外的所有数据结果:void

/** * 添加 * @param brand */ void add(Brand brand);

编写 SQL 语句:SQL 映射文件

insert into tb_brand (brand_name, company_name, ordered, description, status) values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});

执行方法,测试

/** * 添加 * * @throws IOException */ @Test public void TestAdd() throws IOException { // 接收参数 int status = 1; String companyName = "波导手机"; String brandName = "波导"; String description = "手机中的战斗机"; int ordered = 100; // 处理参数 companyName = "%" + companyName + "%"; brandName = "%" + brandName + "%"; // 封装对象 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(); // 3. 获取 Mapper 接口代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4. 执行方法 brandMapper.add(brand); // 5. 释放资源 sqlSession.close(); }

运行后发现并没有添加到数据库中,这就要说到MyBatis的事务添加​​sqlSession.commit();​​ 即可或者​​SqlSession sqlSession = sqlSessionFactory.openSession(true);​​ 设置为自动提交事务(关闭事务)添加 - 主键返回在数据添加成功后,需要获取插入数据库数据的主键的值SQL 映射文件:​​​​测试文件中直接获取即可:​​Integer id = brand.getId();​​

修改

1. 修改全部字段

编写接口方法:Mapper 接口

参数:所有数据结果:void

/** * 修改 * @param brand * @return */ int update(Brand brand);

编写 SQL 语句:SQL 映射文件

update tb_brand set brand_name = #{brandName}, company_name= #{companyName}, ordered = #{ordered}, description = #{description}, status = #{status} where id = #{id};

执行方法,测试

/** * 修改 * * @throws IOException */ @Test public void TestUpdate() throws IOException { // 接收参数 int status = 1; 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(); // 3. 获取 Mapper 接口代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4. 执行方法 int count = brandMapper.update(brand); System.out.println(count); // 提交事务 sqlSession.commit(); // 5. 释放资源 sqlSession.close(); }

2. 修改动态字段

编写 SQL 语句:SQL 映射文件

update tb_brand brand_name = #{brandName}, company_name= #{companyName}, ordered = #{ordered}, description = #{description}, status = #{status} where id = #{id};

删除

1. 删除一个

编写接口方法:Mapper 接口

参数:id结果:void

/** * 根据Id 删除 * @param id */ void deleteById(int id);

编写 SQL 语句:SQL 映射文件

delete from tb_brand where id = #{id};

执行方法,测试

/** * 根据Id 删除 * * @throws IOException */ @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(); // 3. 获取 Mapper 接口代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4. 执行方法 brandMapper.deleteById(id); // 提交事务 sqlSession.commit(); // 5. 释放资源 sqlSession.close(); }

2. 批量删除

编写接口方法:Mapper 接口

参数:id数组结果:void

/** * 批量删除 * @param ids */ void deleteByIds(@Param("ids") int[] ids);

编写 SQL 语句:SQL 映射文件

delete from tb_brand where id in ${id}

执行方法,测试

/** * 批量删除 * * @throws IOException */ @Test public void TestDeleteByIds() throws IOException { // 接收参数 int[] ids = {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(); // 3. 获取 Mapper 接口代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4. 执行方法 brandMapper.deleteByIds(ids); // 提交事务 sqlSession.commit(); // 5. 释放资源 sqlSession.close(); }

MyBatis 参数传递

MyBatis 提供了 ParamNameResolver 类来进行参数封装单个参数

POJO类型:直接使用,属性名 和 参数占位符名称 一致Map集合:直接使用,键名 和 参数占位符名称 一致Collection:封装为 Map 集合,可以使用@Param注解,替换Map集合中默认的arg键名

map.put("arg0", collection集合)map.put("collection", collection集合)

List:封装为 Map 集合,可以使用@Param注解,替换Map集合中默认的arg键名

map.put("arg0", list集合)map.put("collection", list集合)map.put("list", list集合)

Array:封装为 Map 集合,可以使用@Param注解,替换Map集合中默认的arg键名

map.put("array", 数组)map.put("arg0", 数组)

其他类型:直接使用

多个参数:封装为 Map 集合,可以使用@Param注解,替换Map集合中默认的arg键名

map.put("arg0", 参数值1)map.put("param1", 参数值1)map.put("arg1", 参数值2)map.put("param2", 参数值2)---------------@Param("username")map.put("username", 参数值1)map.put("param1", 参数值1)map.put("arg1", 参数值2)map.put("param2", 参数值2)

注解完成增删改查

查询:​​@Select​​添加:​​@Insert​​修改:​​@Update​​删除:​​@Delete​​

@Select("select * from tb_user where id = #{id}")public User selectById(int id);

【注】使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。 换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和 XML 的语句映射方式间自由移植和切换。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Echarts Map 值域为小数的原因
下一篇:jpa 使用@Column来定义字段类型
相关文章

 发表评论

暂时没有评论,来抢沙发吧~