【简介】
1.MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github。
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)。
当前,最新版本是MyBatis 3.5.13,其发布时间是2023年03月11日。
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。(注:来源百度百科)
【MyBatis特点】
1.简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件。易于学习,易于使用。通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
2.灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
3.解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
4.提供映射标签,支持对象与数据库的ORM字段关系映射。
5.提供对象关系映射标签,支持对象关系组建维护。
6.提供xml标签,支持编写动态sql。(注:来源百度百科)
【开发过程】
1、导入相关的包(11个jar包)
2、在src目录下编写编写配置文件(mybatis-cfg.xml)
3、编写实体类(User.java)
4、编写映射文件(UserMapper.xml)
5、编写测试文件
6、调用JUnit 5进行调试
【MyBatis常用的三个查询方法】
1.selectList
用于查询多条数据,返回值是一个List集合。若没有查到任何数据返回一个空集合,不是null。
2.selectOne
用于查询单条数据,返回值是一个对象。如果没有查到任何数据,返回null。
3.selectMap
用于查询多条数据,返回值是一个Map集合。若没有查到任何数据返回一个空集合,不是null。
----------------------------------------------------------------
大体结构
Test 代码
----------------------------------------
package TestResult; import jiazhong.pojo.Emp; 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; import java.util.Set; public class Test1 { @Test public void findAll() throws IOException { //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 List<Emp> emps = sqlSession.selectList("EmpMapper.findAll"); for (Emp obj : emps) { System.out.println("obj = " + obj); } } @Test public void insert() throws IOException { //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 int i = sqlSession.update("EmpMapper.insert"); sqlSession.commit();//提交事务 System.out.println("i = " + i); } @Test public void update() throws IOException { //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 int i = sqlSession.update("EmpMapper.update"); sqlSession.commit();//提交事务 System.out.println("i = " + i); } @Test public void delete() throws IOException { //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 int i = sqlSession.update("EmpMapper.delete"); sqlSession.commit();//提交事务 System.out.println("i = " + i); } //根据参数来查询 @Test public void findone() throws IOException { //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 Object o = sqlSession.selectOne("EmpMapper.findone", 5); System.out.println("o = " + o); } //根据参数来增加 @Test public void insert1() throws IOException { HashMap hashMap = new HashMap(); hashMap.put("name", "22"); hashMap.put("tel", "123456"); hashMap.put("dress", "444"); hashMap.put("money", 55); hashMap.put("sta", "0"); //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 int i = sqlSession.update("EmpMapper.insert1", hashMap); sqlSession.commit();//提交事务 System.out.println("i = " + i); } //根据参数来修改 @Test public void update1() throws IOException { HashMap hashMap = new HashMap(); hashMap.put("name", "22"); hashMap.put("tel", "123456"); hashMap.put("dress", "444"); hashMap.put("money", 55); hashMap.put("sta", "0"); hashMap.put("empId", 12); //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 int i = sqlSession.update("EmpMapper.update1", hashMap); sqlSession.commit();//提交事务 System.out.println("i = " + i); } //根据参数来删除 @Test public void delete1() throws IOException { //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 int i = sqlSession.update("EmpMapper.delete1", 12); sqlSession.commit();//提交事务 System.out.println("i = " + i); } //字段查询 @Test public void findoneZIduan() throws IOException { HashMap hashMap = new HashMap(); hashMap.put("cols", "name,tel"); //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 List<Emp> emps = sqlSession.selectList("EmpMapper.findoneziduan", hashMap); for (Emp obj : emps) { System.out.println("obj = " + obj); } } //模糊查询 @Test public void findone2() throws IOException { HashMap hashMap = new HashMap(); hashMap.put("name", "1"); //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 List<Emp> emps = sqlSession.selectList("EmpMapper.findone2", hashMap); for (Emp obj : emps) { System.out.println("obj = " + obj); } } //限制查询 @Test public void findone3() throws IOException { HashMap<String, Object> stringObjectHashMap = new HashMap<>(); stringObjectHashMap.put("minmoney", 1); stringObjectHashMap.put("maxmoney", 60); //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 List<Emp> emps = sqlSession.selectList("EmpMapper.findone3", stringObjectHashMap); for (Emp obj : emps) { System.out.println("obj = " + obj); } } //批量来删除 @Test public void delete2() throws IOException { Integer[] ids = {4}; //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 int i = sqlSession.delete("EmpMapper.delete2", ids); sqlSession.commit();//提交事务 System.out.println("i = " + i); } //批量更新 @Test public void update2() throws IOException { HashMap<String, Object> stringObjectHashMap = new HashMap<>(); Integer money = 100; Integer[] ids = {3, 5, 7}; stringObjectHashMap.put("arrIds", ids); stringObjectHashMap.put("money", money); //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 int i = sqlSession.update("EmpMapper.update2", stringObjectHashMap); sqlSession.commit();//提交事务 System.out.println("i = " + i); } //返回map查询 @Test public void findAll1() throws IOException { //1.读取加载核心配置文件 InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml"); //2.构造会话工厂 SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in); //3.创建对象会话 SqlSession sqlSession = fac.openSession(); //4.执行器 Map<Integer, Object> map = sqlSession.selectMap("EmpMapper.getresult", "empId"); Set<Integer> integers = map.keySet(); for (Integer obj : integers) { System.out.println("obj = " + obj); System.out.println("map.get(obj) = " + map.get(obj)); } } }
---------------------------------------------------
注:test 是EmpMapper的测试所以一一对应
EmpMapper 代码
----------------------------------------------------
<?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="EmpMapper"> <!-- 查询--> <select id="findAll" resultType="jiazhong.pojo.Emp"> select * from emp1 </select> <!-- 增加--> <update id="insert"> insert into emp1 values (null, "13", "567", "465", 500, "1") </update> <!-- 修改--> <update id="update"> update emp1 set name="55", tel="500" where empId = 5 </update> <!-- 删除--> <update id="delete"> delete from emp1 where empId = 6 </update> <!-- 根据参数 查询--> <select id="findone" resultType="jiazhong.pojo.Emp"> select * from emp1 where empId = #{empId} </select> <!-- 根据参数 增加--> <update id="insert1"> insert into emp1 values (null, #{name}, #{tel}, #{dress}, #{money}, ${sta}) </update> <!-- 根据参数 修改--> <update id="update1"> update emp1 set name=#{name}, tel=#{tel}, dress=#{dress}, money=#{money}, sta=#{sta} where empId = #{empId} </update> <!-- 删除--> <update id="delete1" parameterType="int"> delete from emp1 where empId = #{empId} </update> <!-- 列段 查询--> <select id="findoneziduan" resultType="jiazhong.pojo.Emp"> select ${cols} from emp1 </select> <!-- 模糊 查询--> <select id="findone2" resultType="jiazhong.pojo.Emp"> select * from emp1 where name like '%${name}%' </select> <!-- 限制查询--> <select id="findone3" resultType="jiazhong.pojo.Emp"> select * from emp1 where 1=1 <if test="minmoney != null"> and money>#{minmoney} </if> <!-- <![CDATA[]]>--> <if test="maxmoney != null"> and money<![CDATA[<]]>#{maxmoney} </if> </select> <!-- 批量删除--> <!-- where id in ()--> <update id="delete2"> delete from emp1 where empId in <foreach collection="array" open="(" item="empId" separator="," close=")"> #{empId} </foreach> </update> <!-- 批量更新--> <update id="update2"> update emp1 set money = money+ #{money} where empId in <foreach collection="arrIds" open="(" item="empId" separator="," close=")"> #{empId} </foreach> </update> <!-- 以map查询--> <select id="getresult" resultType="jiazhong.pojo.Emp"> select * from emp1 </select> </mapper>
--------------------------------------------------
mybatis-config.xml 代码
----------------------------------------
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 引入链接--> <properties resource="config/JDBC.properties"></properties> <environments default="develop"> <environment id="develop"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!-- 导入配置的语句--> <mappers> <mapper resource="mapper/EmpMapper.xml"/> </mappers> </configuration>
-----------------------------------------
依赖
-------------------------------------
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> </dependency> </dependencies>
----------------------------------------------