了解MyBatis+Mapper+Maven开发
一、什么是MyBatis?
MyBatis是一款优秀的 持久层 框架,用于简化JDBC开发。
三层架构:表现层(显示)、业务层(逻辑)、持久层(操作数据库)。
简化JDBC开发:
- 硬编码:注册驱动,获取连接、SQL语句 => 写到配置文件去
- 操作繁琐:手动设置参数、手动封装结果集 => 自动完成
二、MyBatis快速入门
1. 查询user表中所有数据案例,步骤:
1.1 准备user表
1.2 创建模块,导入jar包信息
1.3 编写MyBatis核心配置文件 —> 替换连接信息,解决硬编码问题
1.4 编写SQL映射文件 —> 统一管理SQL语句,解决硬编码问题
1.5 编码
1.5.1 定义POJO类,即实体类
1.5.2 加载核心配置文件,获取SqlSessionFactory对象
1.5.3 获取SqlSession对象,执行SQL
1.5.4 释放资源
2. Maven+Mybatis实操:
(1)Maven依赖管理文件pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>maven-demo</artifactId> <version>1.0-SNAPSHOT</version> <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> </project>
(2)logback.xml日志配置文件
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- CONSOLE:表示当前的日志信息是可以输出到控制台的。 --> <appender name="Console" class="ch.gos.logback.core.ConsleAppender"> <encoder> <pattern>[%level] %blue(%d{HH:mm:ss.SSS})%cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern> </encoder> </appender> <logger name="com.hung" level="DEBUG" additivity="false"> <appender-ref ref="Console"/> </logger> </configuration>
(3)user实体类
package com.hung.pojo; public class User { private int id; private String username; private String password; private String gender; private String addr; public int getId() { return id; } public void setId(int 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 getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", gender='" + gender + '\'' + ", addr='" + addr + '\'' + '}'; } }
(4)mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <!-- 数据库连接信息 --> <property name="driver" value="com.mysql.jdbc.Driver"/> <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>
(5)UserMapper映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace:命名空间 id:该sql语句的唯一标识 resultType:返回结果类型 --> <!-- tb_user 报红,可在右侧点击database配置当前项目连接的数据库解决 --> <mapper namespace="test"> <select id="selectAll" resultType="com.hung.pojo.User"> select * from tb_user; </select> </mapper>
(6)MybatisDemo测试类
package com.hung; import com.hung.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对象 SqlSession sqlSession = sqlSessionFactory.openSession(); // 3.执行sql List<User> users = sqlSession.selectList("test.selectAll"); System.out.println(users); // 4.释放资源 sqlSession.close(); } }
三、Mapper代理开发
1. 步骤
- 定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
- 设置SQL映射文件的namespace属性为Mapper接口全限定名
- 在Mapper接口中定义方法,方法名就是SQL映射文件中sq语句的id,并保持参数类型和返回值类型一致
- 编码
1. 通过SqlSession的getMapper方法获取Mapper接口的代理对象
2. 调用对应方法完成sql的执行
2. Maven+Mybatis+Mapper实操(续二实操)
(1)移动了UserMapper.xml文件,需相应修改mybatis-config.xml配置文件的加载sql映射的配置
<mappers> <!-- 加载sql映射文件 --> <!-- <mapper resource="com/hung/mapper/UserMapper.xml"/> --> <!-- 当接口文件和配置文件符合“同名”同“目录”时,用包扫描方式更方便 --> </mappers>
(2)修改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"> <!-- namespace:命名空间 id:该sql语句的唯一标识 resultType:返回结果类型 --> <mapper namespace="com.hung.mapper.UserMapper"> <select id="selectAll" resultType="com.hung.pojo.User"> select * from tb_user; </select> </mapper>
(3)UserMapper接口文件
package com.hung.mapper; import com.hung.pojo.User; import java.util.List; public interface UserMapper { // 返回值跟 UserMapper.xml 中定义的相同,这里返回装了多个User的List集合 List<User> selectAll(); }
(3)MybatisDemo2测试类
package com.hung; import com.hung.mapper.UserMapper; import com.hung.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 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对象 SqlSession sqlSession = sqlSessionFactory.openSession(); // 3.获取UserMapper接口的代理对象对象(变化处) // List<User> users = sqlSession.selectList("test.selectAll"); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> users = userMapper.selectAll(); System.out.println(users); // 4.释放资源 sqlSession.close(); } }
四、MyBatis核心配置文件
参考官网即可
五、案例
1. 使用配置文件开发方式
使用配置进行增删改查、使用注解进行增删改查、动态SQL:已上传gitee
环境准备好之后,主要步骤就是:
- 1. 编写Mapper接口文件中的接口
参数:
结果: - 2. 编写Mapper映射文件中的sql语句
- 3. 编写Java文件中的执行方法
(1)Brand.java 实体类
查看代码
package com.hung.pojo; public class Brand { private Integer id; private String brandName; private String companyName; private Integer ordered; private String description; 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 + '}'; } }
(2)BrandMapper.java 接口文件
查看代码
package com.hung.mapper; import com.hung.pojo.Brand; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; public interface BrandMapper { /** * 查询所有 * @return List<Brand> */ List<Brand> selectAll(); /** * 查询详情:根据ID * @param id * @return Brand */ Brand selectById(int id); /** * 多条件动态条件查询 * * 接收参数方式: * 1.散装参数 * 2.对象参数 * 3.map集合参数 * @param status * @param companyName * @param brandName * @return List<Brand> */ List<Brand> selectByCondition(@Param("status")int status,@Param("companyName")String companyName,@Param("brandName")String brandName); // List<Brand> selectByCondition(Brand brand); // List<Brand> selectByCondition(Map map); /** * 单条件动态条件查询 * @param brand * @return */ List<Brand> selectByConditionSingle(Brand brand); /** * 添加信息 * @param brand */ void add(Brand brand); /** * 更新信息 * @param brand * @return */ int update(Brand brand); /** * 批量删除 * @param ids */ void deleteByIds(@Param("ids")int[] ids); }
(3)BrandMapper.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"> <!-- namespace:命名空间 id:该sql语句的唯一标识 resultType:返回结果类型 --> <!-- 更改命名空间 --> <!-- 数据库字段和实体类字段名称不一致,不能自动封装 解决: 1.在sql语句给字段起别名,但麻烦 2.设置sql片段,也不方便 3.resultMap 牛 --> <mapper namespace="com.hung.mapper.BrandMapper"> <!-- =========================定义返回类型映射============================== --> <!-- 定义 brandResultMap --> <!-- <id></id>: 主键映射 <resultMap></<resultMap>: 一般字段映射 --> <resultMap id="brandResultMap" type="com.hung.pojo.Brand"> <result column="brand_name" property="brandName"/> <result column="company_name" property="companyName"/> </resultMap> <!-- ===========================查询所有信息============================ --> <!-- 设置resultMap="brandResultMap" --> <select id="selectAll" resultMap="brandResultMap"> select * from tb_brand; </select> <!-- ============================根据ID查询=========================== --> <!-- #{id}}: ?占位参数,防止sql注入,因此常用于传递参数的时候,如下id: ${}: 拼接sql,会sql注入,可用于动态查询的字段的占位,如下面的*位置字段 特殊条件字符处理: = 可正常使用,但 < 会被认为时标签起始符号,需转义 —> 转义字符法 或 CDATA区法 查资料了解 --> <select id="selectById" resultMap="brandResultMap"> select * from tb_brand where id = #{id}; </select> <!-- ============================条件查询=========================== --> <select id="selectByCondition" resultMap="brandResultMap"> <!-- 1.固定条件sql select * from tb_brand where status = #{status} and company_name like #{companyName} and brand_name like #{brandName} --> <!-- 2.多条件动态sql--> select * from tb_brand <where> <if test="status != null"> and status = #{status} </if> <if test="companyName != null and companyName != ''"> and companyName like #{companyName} </if> <if test="brandName != null and brandName != ''"> and brandName like #{brandName} </if> </where> </select> <!-- =========================单条件动态查询============================== --> <select id="selectByConditionSingle" resultMap="brandResultMap"> select * from tb_brand <where> <choose> <!-- 类似switch --> <when test="status != null"> <!-- 类似case,条件成立即跳出choose --> status = #{status} </when> <when test="companyName != null and companyName != ''"> companyName like #{companyName} </when> <when test="brandName != null and brandName != ''"> brandName like #{brandName} </when> </choose> </where> </select> <!-- =========================添加信息,获取返回主键============================== --> <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> <!-- =========================更新信息,获取返回影响行数============================== --> <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 = #{brandName}, </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> <delete id="deleteByIds"> delete from tb_brand where id in <foreach collection="ids" item="id" separator="," open="(" close=")"> #{id} </foreach> <!-- 或括号在 (<foreach collection="ids" item="id" separator=","> #{id} </foreach>) --> </delete> </mapper>
(4)MyBatisTest.java 测试类
查看代码
package com.hung.test; import com.hung.mapper.BrandMapper; import com.hung.pojo.Brand; import com.hung.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.HashMap; import java.util.List; import java.util.Map; public class MyBatisTest { // 演示查询所有,主要讲解整个查询流程 @Test public void testSelectAll() throws IOException { // 1.加载myBatis核心配置文件,获取SqlSessionFactory (固定代码,参照官网即可!) String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2.获取SqlSession对象(固定代码) SqlSession sqlSession = sqlSessionFactory.openSession(); // 3.获取BrandMapper接口的代理对象对象(变化处) BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4.执行查询方法,接收返回结果,并处理(变化处) List<Brand> brands = brandMapper.selectAll(); System.out.println(brands); // 5.释放资源 sqlSession.close(); } // 演示根据ID查询,注意查询返回结果类型 @Test public void testSelectById() throws IOException { // 模拟接收前端参数 int id = 1; // 1.加载myBatis核心配置文件,获取SqlSessionFactory (固定代码,参照官网即可!) String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2.获取SqlSession对象(固定代码) SqlSession sqlSession = sqlSessionFactory.openSession(); // 3.获取BrandMapper接口的代理对象对象(变化处) BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4.执行查询方法,接收返回结果,并处理(变化处) Brand brand = brandMapper.selectById(id); System.out.println(brand); // 5.释放资源 sqlSession.close(); } // 演示多条件动态参数处理,主要讲解参数处理 @Test public void testSelectByCondition() throws IOException { // 模拟接收前端参数 int status = 1; String companyName = "华为"; String brandName = "华为"; // 处理参数 // 1.散装参数传递方法 companyName = "%" + companyName + "%"; brandName = "%" + brandName + "%"; /* 2.对象参数传递方法 companyName = "%" + companyName + "%"; brandName = "%" + brandName + "%"; Brand brand = new Brand(); brand.setStatus(status); brand.setCompanyName(companyName); brand.setBrandName(BrandName); */ /* 3.map对象传递参数方法 companyName = "%" + companyName + "%"; brandName = "%" + brandName + "%"; Map map = new HashMap(); map.put("status",status); map.put("companyName",companyName); map.put("brandName",brandName); */ // 1.加载myBatis核心配置文件,获取SqlSessionFactory (固定代码,参照官网即可!) String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2.获取SqlSession对象(固定代码) SqlSession sqlSession = sqlSessionFactory.openSession(); // 3.获取BrandMapper接口的代理对象对象(变化处) BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4.执行查询方法,接收返回结果,并处理(变化处) // 4.1散装参数传递 List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName); /* 4.2对象参数传递 List<Brand> brands = brandMapper.selectByCondition(brand); */ /* 4.3map参数传递 List<Brand> brands = brandMapper.selectByCondition(map); */ System.out.println(brands); // 5.释放资源 sqlSession.close(); } // 演示单条件动态查询,重心在sql语句 @Test public void testSelectByConditionSingle() throws IOException { // 模拟接收前端参数:单一参数 String brandName = "华为"; // 处理参数 brandName = "%" + brandName + "%"; Brand brand = new Brand(); brand.setBrandName(brandName); // 1.加载myBatis核心配置文件,获取SqlSessionFactory (固定代码,参照官网即可!) String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2.获取SqlSession对象(固定代码) SqlSession sqlSession = sqlSessionFactory.openSession(); // 3.获取BrandMapper接口的代理对象对象(变化处) BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4.执行查询方法,接收返回结果,并处理(变化处) List<Brand> brands = brandMapper.selectByConditionSingle(brand); System.out.println(brands); // 5.释放资源 sqlSession.close(); } // 演示添加信息,主要讲解事务的提交、接收主键返回 @Test public void testAdd() throws IOException { // 模拟接收前端参数 String brandName = "荣耀"; String companyName = "荣耀集团有限公司"; int ordered = 4; String description = "荣耀手机是好手机"; int status = 1; // 处理参数 Brand brand = new Brand(); brand.setBrandName(brandName); brand.setCompanyName(companyName); brand.setOrdered(ordered); brand.setDescription(description); brand.setStatus(status); // 1.加载myBatis核心配置文件,获取SqlSessionFactory (固定代码,参照官网即可!) String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2.获取SqlSession对象(固定代码) SqlSession sqlSession = sqlSessionFactory.openSession(true);// true:自动提交事务 // 3.获取BrandMapper接口的代理对象对象(变化处) BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4.执行查询方法 brandMapper.add(brand); // 4.1手动提交事务 // sqlSession.commit(); // 4.2接收主键返回 int mainId = brand.getId(); System.out.println(mainId); // 5.释放资源 sqlSession.close(); } // 演示修改信息,主要看sql语句,接收主键影响行数 @Test public void testUpdate() throws IOException { // 模拟接收前端参数 int id = 4; String brandName = "honor"; // String companyName = "荣耀集团有限公司"; int ordered = 5; String description = "honor手机是好手机"; int status = 0; // 处理参数 Brand brand = new Brand(); brand.setBrandName(brandName); // brand.setCompanyName(companyName); brand.setOrdered(ordered); brand.setDescription(description); brand.setStatus(status); // 1.加载myBatis核心配置文件,获取SqlSessionFactory (固定代码,参照官网即可!) String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2.获取SqlSession对象(固定代码) SqlSession sqlSession = sqlSessionFactory.openSession(true);// true:自动提交事务 // 3.获取BrandMapper接口的代理对象对象(变化处) BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4.执行查询方法 int row = brandMapper.update(brand); System.out.println(row); // 5.释放资源 sqlSession.close(); } // 演示批量删除,主要看sql语句 @Test public void testDeleteByIds() throws IOException { // 模拟接收前端参数 int[] ids = {1,3,4}; // 1.加载myBatis核心配置文件,获取SqlSessionFactory (固定代码,参照官网即可!) String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2.获取SqlSession对象(固定代码) SqlSession sqlSession = sqlSessionFactory.openSession(true);// true:自动提交事务 // 3.获取BrandMapper接口的代理对象对象(变化处) BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); // 4.执行查询方法 brandMapper.deleteByIds(ids); // 5.释放资源 sqlSession.close(); } }
2. 使用注解开发方式
- 查询 @Select
- 添加 @Insert
- 修改 @Update
- 删除 @Delete
注解开发不需要写xml映射文件,只需要在接口文件的方法上写上注解:
@Select("select * from tb_brand where id = #{}") Brand selectById(int id);
本文来自博客园,作者:RHCHIK,转载请注明原文链接:https://www.cnblogs.com/suihung/p/16595884.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)