●创建一张测试表。
●创建对应的 JavaBean 。
●创建 Mybatis 配置文件和 SQL 映射文件。
●测试。
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL,
`last_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`gender` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `employee` VALUES (1, 'tom', '男', 'tom@qq.com');
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
package com.xuguoguo.domain;
public class Employee {
private Integer id;
private String lastName;
private String email;
private String 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;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
package com.xuguoguo.mapper;
import com.xuguoguo.domain.Employee;
public interface EmployeeMapper {
Employee findById(Integer id);
}
<?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.xuguoguo.mapper.EmployeeMapper">
<select id="findById" resultType="com.xuguoguo.domain.Employee">
SELECT id,last_name as lastName,email,gender
FROM employee
WHERE id = #{id,jdbcType=INTEGER}
</select>
</mapper>
<?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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.134.100:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 将写好的SQL映射文件注册到全局配置文件中 -->
<mapper resource="com/xuguoguo/mapper/EmployeeMapper.xml"/>
</mappers>
</configuration>
package com.xuguoguo;
import com.xuguoguo.domain.Employee;
import com.xuguoguo.mapper.EmployeeMapper;
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;
/**
* ①接口式编程
* ②SqlSession代表和数据库的一次会话,用完必须关闭。
* ③SqlSession和Connection一样,都是线程不安全的。每次使用都应该去获取新的对象。
* ④Mapper接口没有实现类,但是Mybatis会为这个接口生成一个代理对象。
* EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
* ⑤两个重要的配置文件:
* Mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等系统运行环境
* Mybatis的SQL映射文件:保存每一个SQL语句的映射信息。
*
*/
public class EmployeeTest {
/**
* ①根据XML配置文件(全局配置文件)创建一个SqlSessionFactory对象(有数据源等一些运行的环境信息)
* ②sql映射文件:配置了每一个SQL,以及SQL的封装规则等。
* ③将sql映射文件注册在全局配置文件中
* ④写代码:
* - 根据全局配置文件获取SqlSessionFactory对象。
* - 使用SqlSessionFactory工厂,获取sqlSession对象,使用其来进行CRUD。
* - 一个sqlSession对象代表一次数据库的会话,用完关闭。
* - 使用sql的唯一标识来告诉Mybatis执行哪个SQL
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = employeeMapper.findById(1);
System.out.println("employee = " + employee);
sqlSession.close();
}
}
提示:本章节主要讲解的是Mybatis框架入门的基本的步骤流程和核心的细节处理完善!!!