MyBatis简单入门使用

时间:2021-12-12 16:47:02
环境准备: 
1. IDE(推荐使用ItelliJ IDEA)
2. JDK1.7以上
3. Maven构建工具

4. MySQL数据库(目前最新版本为5.7)


1. 新建一个Maven工程项目

使用IDE新建maven工程很简单,这里就不多介绍了,新建后项目结构如下:

MyBatis简单入门使用

2. 添加插件依赖

修改pom.xml文件,添加对如下插件的依赖:
1. maven编译插件
2. mybatis
3. log4j
4. JUnit
5. MySQL连接驱动

修改后的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>cn.linjk</groupId>
<artifactId>mybatis-test</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.outputEncoding>UTF-8</project.build.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>

</project>

3. 准备数据库

这里仅仅测试流程,因此,新建一个测试数据库来弄,按如下步骤准备:

1. 创建数据库

2. 创建一个测试表

3. 往测试表插入部分测试数据

结果如下所示:

MyBatis简单入门使用

4. 配置mybatis

在src/main/resources路径下新建文件mybatis-config.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>
<settings>
<!-- 使用sl4j输出日志 -->
<setting name="logImpl" value="LOG4J"/>
</settings>

<typeAliases>
<package name="cn.linjk.mybatistest.domain"/>
</typeAliases>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>

<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://**.**.**.**:***/mytest"/>
<property name="username" value="***"/>
<property name="password" value="******"/>
</dataSource>
</environment>
</environments>

<mappers>
<mapper resource="cn/linjk/mybatistest/mapper/UserMapper.xml"/>
</mappers>
</configuration>

5. 创建实体类

目前数据库只有一个user表,因此,创建一个User.java文件,内容如下(属性名必须和数据库的字段名一一对应):

package cn.linjk.mybatistest.domain;

public class User {
private Long iduser
;
private String name;
private String passwd;

public Long getUserId() {
return iduser;
}

public void setUserId(Long userId) {
this.iduser = userId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPasswd() {
return passwd;
}

public void setPasswd(String passwd) {
this.passwd = passwd;
}
}

6. 创建映射文件

src/main/resources/cn.linjk.mybatistest.mapper/UserMapper.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="cn.linjk.mybatistest.mapper.UserMapper">
<select id="selectUsers" resultMap="User">
SELECT iduser, name, passwd FROM user
</select>
</mapper>

7. 配置Log4j,让程序执行可以输出详细过程, 这里主要想看数据库连接过程

新建文件src/main/resources/log4j.properties:

# 全局配置
log4j.rootLogger=ERROR, stdout

# MyBatis日志配置
log4j.logger.cn.linjk.mybatistest.mapper=TRACE

# 控制台输出配置
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

8. 测试代码:

package cn.linjk.mybatistest;

import cn.linjk.mybatistest.domain.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 org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class UserMapperTest {
private static SqlSessionFactory sqlSessionFactory;

@BeforeClass
public static void init() {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}

@Test
public void tesrSelectUsers() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
List<User> userList = sqlSession.selectList("selectUsers");
for (User user : userList) {
System.out.printf("%-4d%4s%4s\n",
user.getUserId(), user.getName(), user.getPasswd());
}
}
finally {
sqlSession.close();
}
}
}
运行结果如下:

MyBatis简单入门使用

MyBatis的简单使用流程就这样,这样很麻烦,容易出错,后面会有介绍工具生成这个映射文件的。