以下内容的公开课视频已经录制, 需要的同学可留言
MyBatis 作为一个应用广泛的优秀的持久层 ORM 框架, 已经成了 Javaweb 世界近乎标配的部分, 它支持定制化 SQL, 存储过程以及高级映射. MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集. MyBatis 可以使用简单的 xml 或注解来配置和映射原生类型, 接口和 Java 的 POJO(Plain Old Java Objects, 普通老式 Java 对象) 为数据库中的记录.
1. 下载源码
下载最新的稳定版或者目前项目中使用的 MyBatis 源代码, 本课以 MyBatis 3.5.1 为例进行讲解,(目前最新版本为 3.5.2-SNAPSHOT).
下载地址: https://github.com/mybatis/mybatis-3
注意按照读 tag 进行版本选择.
源码下载. PNG
2. 创建源码项目工程
下载源码后, 在 idea 中导入 pom 工程, 需要按照以下步骤进行修改调整, 项目才能编译成功.
pom 文件中 ognl,javassist 修改为
- <optional>false</optional>
- <dependency>
- <groupId>ognl</groupId>
- <artifactId>ognl</artifactId>
- <version>3.2.10</version>
- <scope>compile</scope>
- <optional>false</optional>
- </dependency>
- <dependency>
- <groupId>org.javassist</groupId>
- <artifactId>javassist</artifactId>
- <version>3.24.1-GA</version>
- <scope>compile</scope>
- <optional>false</optional>
- </dependency>
删除项目目录下的 license.txt
如果不删除的话, 在执行 maven install 时会出错.
手动下载 jar 包到本地
这个视情况而定, 如果本地执行 maven install 时出现如下错误
- [INFO] --- maven-surefire-plugin:2.7.1:test (default-test) @ wms ---
- [WARNING] Error injecting: org.apache.maven.plugin.surefire.SurefirePlugin
- java.lang.NoClassDefFoundError: org/apache/maven/surefire/util/NestedCheckedException
- at java.lang.ClassLoader.defineClass1(Native Method)
则可以考虑手动下载对应 jar 包到本地 maven 仓库中.
下载地址: http://repo1.maven.org/maven2/org/apache/maven/surefire/maven-surefire-common/3.0.0-M3/maven-surefire-common-3.0.0-M3.jar
关闭 maven-PDF-plugin
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pdf-plugin</artifactId>
</plugin>
-->
关闭 test
执行 maven install 时忽略 test.
忽略 test.PNG
执行 maven install
将 MyBatis 编译安装到本地 maven 仓库.
3. 搭建简单 demo
从最简单的 demo 入手, 前期先不要集成 Spring, 只看最简单的最原始的 MyBatis, 熟悉了 MyBatis 源码后再看如何与 Spring 集成;
结合官方文档搭建 demo:http://www.mybatis.org/mybatis-3/zh/getting-started.html
基本使用流程
引入依赖
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.5.1</version>
- </dependency>
- <dependency>
- <groupId>MySQL</groupId>
- <artifactId>MySQL-connector-java</artifactId>
- <version>5.1.46</version>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
创建 xml 配置文件
- mybatis-config.xml
- <?xml version="1.0" encoding="utf-8" ?>
- <!DOCTYPE configuration
- PUBLIC "-//mybatis.org//DTD Cofig 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"></transactionManager>
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql://localhost:3306/test"/>
- <property name="username" value="root"/>
- <property name="password" value="123456"/>
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="EmployeeMapper.xml"></mapper>
- </mappers>
- </configuration>
EmployeeMapper.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="com.boxuegu.javaee.mybatissourcelearn.dao.EmployeeMapper">
- <select id="getEmployeeById" resultType="com.boxuegu.javaee.mybatissourcelearn.dto.Employee">
- select id,last_name lastname,gender, email from bxg_employee where id=#{id}
- </select>
- </mapper>
创建 dto 对象
Employee.java
- package com.boxuegu.javaee.mybatissourcelearn.dto;
- /**
- * @author Jam Fang https://www.jianshu.com/u/0977ede560d4
- * @version 创建时间: 05.24 15:27
- */
- public class Employee {
- private Integer id;
- private String lastName;
- private String email;
- private String gender;
- @Override
- public String toString() {
- return "Employee{" +
- "id=" + id +
- ", lastName='" + lastName + '\'' +
- ", email='" + email + '\'' +
- ", gender='" + gender + '\'' +
- '}';
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getLastName() {
- return lastName;
- }
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getGender() {
- return gender;
- }
- public void setGender(String gender) {
- this.gender = gender;
- }
- }
创建 dao
EmployeeMapper.java
- package com.boxuegu.javaee.mybatissourcelearn.dao;
- import com.boxuegu.javaee.mybatissourcelearn.dto.Employee;
- /**
- * @author Jam Fang https://www.jianshu.com/u/0977ede560d4
- * @version 创建时间: 05.24 17:32
- */
- public interface EmployeeMapper {
- public Employee getEmployeeById(Integer id);
- }
创建数据库测试表
- -- ----------------------------
- -- Table structure for bxg_employee
- -- ----------------------------
- DROP TABLE IF EXISTS `bxg_employee`;
- CREATE TABLE `bxg_employee` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `last_name` varchar(255) DEFAULT NULL,
- `gender` char(1) DEFAULT NULL,
- `email` varchar(255) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of bxg_employee
- -- ----------------------------
- INSERT INTO `bxg_employee` VALUES ('1', 'zhangsan', '1', 'zhangsan@itcast.cn');
创建测试代码
- package com.boxuegu.javaee.mybatissourcelearn;
- import com.boxuegu.javaee.mybatissourcelearn.dao.EmployeeMapper;
- import com.boxuegu.javaee.mybatissourcelearn.dto.Employee;
- 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;
- /**
- * @author Jam Fang https://www.jianshu.com/u/0977ede560d4
- * @version 创建时间: 2019/6/17 13:16
- */
- public class Test {
- public static void main(String[] args) {
- //1. 加载配置文件
- String resource = "mybatis-config.xml";
- InputStream inputStream = null;
- try {
- inputStream = Resources.getResourceAsStream(resource);
- } catch (IOException e) {
- e.printStackTrace();
- }
- //2. 获取 sqlSessionFactory
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- //3. 获取 sqlSession
- SqlSession sqlSession = sqlSessionFactory.openSession();
- try {
- //4. 获取 mapper 接口实现
- EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
- System.out.println("mapper::::" + mapper.getClass());
- //5. 执行 sql 语句
- Employee employee = mapper.getEmployeeById(1);
- System.out.println(employee);
- } finally {
- sqlSession.close();
- }
- }
- }
来源: http://www.jianshu.com/p/9ff9a495aeb6