SSM-6-Mybatis
- 什么是Mybatis
- Mybatis工作原理
- Mybatis入门
Mybatis是orm框架
Mybatis工作原理
从图 6-4 可以看出, MyBati 框架在操作数据库时,大体经过了 个步骤 下面就对图 6-4 中的每一步流程进行详细讲解,具体如下
( 1 )读取 MyBatis 配置文件 mybatis-config .xml mybatis-config.xml 作为 MyBatis 的全局配 置文件,配置了 MyBatis 的运行环境等信息,其中主要内容是获取数据库连接。
(2 )加载映射文件 Mapper.xml Mapper.xml 文件即 SQL 映射文件,该文件中配置了操作 数据库的 SOL 语句,需要在 mybatis-config .xml 中加载才能执行mybatis-config.xml 可以加 载多个配置文件,每个配置文件对应数据库中的一张表
(3 )构建会话 通过 MyBatis 的环境等配置信息构建会话工厂 SqlSessionFactory
(4 )创 SqlSession 对象 由会话工厂创建 SqlSession 对象,该对象中包含了执行 SOL 的所有方法
(5) MyBatis 底层定义了一个 Executor 接口来操作数据库,它会根据 SqlSession 传递的参 数动态地生成需要执行的 SOL 语句,同时负责查询缓存的维护。
(6 )在 Executor 接口的执行方法中,包含一个 MappedStatement 类型的参数,该参数是对映射信息的封装 用于存储要映射的 SQL 语句的 id 、参数等 Mapper.xml 文件中一个 SOL 对应一个 MappedStatement 对象 SQL id 即是 MappedStatement id
( 7 )输入参数映射 在执行方法时, MappedStatement 对象会对用户执行 SQL 语句的输入 参数进行定义(可以定义为 Map 、Li st 类型、基本类型和 POJO 类型 Executor 执行器会通过 MappedStatement 对象在执行 SOL 前,将输入的 Java 对象映射到 SOL 语句中 这里对输入参 数的映射过程就类似于 JDBC 编程中对 preparedStatement 对象设置参数的过程
( 8 )输出结果映射 在数据库中执行完 SOL 语句后, MappedStatement 对象会对 SOL 行输出的结果进行定义(可以定义为 Map 和List 类型、基本类型、 POJO 类型 Executor 执行 器会通过 MappedStatement 对象在执行 SOL 语句后,将输出结果映射至 Java 对象中 这种将 输出结果映射到 Java 对象的过程就类似于 JDBC 编程中对结果的解析处理过程
Mybatis基本操作
Mybatis配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <?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="mysql"> <environment id="mysql"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://192.168.134.128:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/itheima/mapper/MyCustomerMapper.xml" /> </mappers> </configuration>
|
加载映射文件CustomerMapper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| <?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.CustomerMapper"> <select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer"> select * from t_customer where id = #{id} </select> <select id="findCustomerByName" parameterType="String" resultType="com.itheima.po.Customer"> select * from t_customer where username like concat('%',#{value},'%') </select> <insert id="addCustomer" parameterType="com.itheima.po.Customer"> insert into t_customer(username,jobs,phone) values(#{username},#{jobs},#{phone}) </insert> <update id="updateCustomer" parameterType="com.itheima.po.Customer"> update t_customer set username=#{username},jobs=#{jobs},phone=#{phone} where id=#{id} </update> <delete id="deleteCustomer" parameterType="Integer"> delete from t_customer where id=#{id} </delete> </mapper>
|
Customer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package com.itheima.po;
public class Customer { private Integer id; private String username; private String jobs; 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 getJobs() { return jobs; }
public void setJobs(String jobs) { this.jobs = jobs; }
public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }
@Override public String toString() { return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]"; } }
|
配置Debug
1 2 3 4 5 6 7 8
| log4j.rootLogger=ERROR, stdout
log4j.logger.com.itheima=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
|
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
| package com.itheima.test;
import java.io.InputStream; import java.util.List;
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 com.itheima.po.Customer;
public class MybatisTest {
@Test public void findCustomerByIdTest() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); Customer customer = sqlSession.selectOne("com.itheima.mapper" + ".CustomerMapper.findCustomerById", 1); System.out.println(customer.toString()); sqlSession.close(); }
@Test public void findCustomerByNameTest() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); List<Customer> customers = sqlSession.selectList("com.itheima.mapper" + ".CustomerMapper.findCustomerByName", "j"); for (Customer customer : customers) { System.out.println(customer); } sqlSession.close(); }
@Test public void addCustomerTest() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); Customer customer = new Customer(); customer.setUsername("rose"); customer.setJobs("student"); customer.setPhone("13333533092"); int rows = sqlSession.insert("com.itheima.mapper" + ".CustomerMapper.addCustomer", customer); if (rows > 0) { System.out.println("您成功插入了" + rows + "条数据!"); } else { System.out.println("执行插入操作失败!!!"); } sqlSession.commit(); sqlSession.close(); }
@Test public void updateCustomerTest() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); Customer customer = new Customer(); customer.setId(1); customer.setUsername("john"); customer.setJobs("programmer"); customer.setPhone("6666666666"); int rows = sqlSession.update("com.itheima.mapper" + ".CustomerMapper.updateCustomer", customer); if (rows > 0) { System.out.println("您成功修改了" + rows + "条数据!"); } else { System.out.println("执行修改操作失败!!!"); } sqlSession.commit(); sqlSession.close(); }
@Test public void deleteCustomerTest() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); int rows = sqlSession.delete("com.itheima.mapper" + ".CustomerMapper.deleteCustomer", 4); if (rows > 0) { System.out.println("您成功删除了" + rows + "条数据!"); } else { System.out.println("执行删除操作失败!!!"); } sqlSession.commit(); sqlSession.close(); }
}
|
这里注意从工厂获取Session是重复操作,我们可以将其封装
MyBatis核心对象
- SqlSessionFactory
- SqlSession
使用工具类创建SqlSessionFactory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| package com.itheima.utils;
import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory = null; static { try { Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); } }
public static SqlSession getSession() { return sqlSessionFactory.openSession(); } }
|
MyBatis配置
本文作者:NoOne
本文地址: https://noonegroup.xyz/posts/94b94ba/
版权声明:转载请注明出处!