🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### 数据库 ```mysql CREATE DATABASE `mybatis` CHARACTER SET 'utf8' COLLATE 'utf8_bin'; USE `mybatis`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255), `age` int(11), `address` varchar(255), PRIMARY KEY (`id`) USING BTREE ); INSERT INTO `user` VALUES (1, 'Apollo', 26, 'ShangHai'); ``` ### 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>com.gosuncn</groupId> <artifactId>mybatis</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project> ``` ### 实体类 ```java package com.gosuncn.entity; import java.io.Serializable; public class User implements Serializable { private Integer id; private String name; private Integer age; private String address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; } } ``` ### 持久层接口 ```java package com.gosuncn.dao; import com.gosuncn.entity.User; import java.util.List; public interface UserDao { List<User> findAll(); } ``` ### 全局配置文件 > resources/SqlMapConfig.xml ```xml <?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="dev"> <environment id="dev"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/gosuncn/dao/UserDaoMapper.xml"/> </mappers> </configuration> ``` ### 映射配置文件 > resources/com/gosuncn/dao/UserDaoMapper.xml ```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.gosuncn.dao.UserDao"> <select id="findAll" resultType="com.gosuncn.entity.User"> SELECT `id`, `name`, `age`, `address` FROM `user` </select> </mapper> ``` ### 测试类 ```java package com.gosuncn; import com.gosuncn.dao.UserDao; import com.gosuncn.entity.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.InputStream; import java.util.List; public class MainTest { public static void main(String[] args) throws Exception { InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sessionFactory.openSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> users = userDao.findAll(); for (User user : users) { System.out.println(user); } sqlSession.close(); inputStream.close(); } } ``` ### MyBatis是如何做到的? MyBatis框架读取到`SqlMapConfig.xml`配置。配置中有数据源信息,因此它知道该去哪里操作数据库。配置中有映射文件信息,在映射文件中定义了`namespace`和`id`属性,在它心中就有了SQL的唯一标识。通过`sqlSession.getMapper(UserDao.class)`代码,MyBatis就懂了,哦,我要获取到以`UserDao`接口的全路径为`namespace`下的所有SQL定义信息。由于`id`和方法名也是一一对应的,所以MyBatis就可以为`UserDao`接口实例化一个代理对象来真正的执行数据库操作了。智慧啊!