一、创建数据库与表
1、创建数据库
- 在Navicat里创建MySQL数据库 - testdb,采用utf8mb4字符集
2、创建用户表
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
3、添加表记录
INSERT INTO `t_user` VALUES ('1', '李洪刚', '20', '江阳区嘉裕花园3栋四楼15#');
INSERT INTO `t_user` VALUES ('2', '王云华', '30', '纳溪区大渡镇红鱼村三大队');
INSERT INTO `t_user` VALUES ('3', '郑小翠', '21', '江阳区老窖花园2栋五楼15号');
二、基于配置文件方式使用MyBatis
(一)创建Maven项目
(二)添加相关依赖
- 在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>net.huawei.mybatis</groupId>
<artifactId>MyBatisDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
- Maven本地仓库位置
(三)创建用户实体类
package net.huawei.mybatis.bean;
public class User {
private int id;
private String name;
private int age;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int 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 + '\'' +
'}';
}
}
(四)创建用户映射器配置文件
- 在resources目录里创建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="net.huawei.mybatis.mapper.UserMapper">
<!--按编号查询用户记录-->
<select id="findById" parameterType="int" resultType="User">
SELECT * FROM t_user WHERE id = #{id};
</select>
<!--查询全部用户记录-->
<select id="findAll" resultType="User">
SELECT * FROM t_user;
</select>
</mapper>
(五)创建MyBatis配置文件
- 在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>
<!--配置实体类别名-->
<typeAliases>
<typeAlias type="net.huawei.mybatis.bean.User" alias="User"/>
</typeAliases>
<!--配置数据库环境-->
<environments default="development">
<environment id="development">
<!--配置事务管理器-->
<transactionManager type="JDBC"/>
<!--配置数据源-->
<dataSource type="POOLED"> <!--数据库连接池-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/testdb"/>
<property name="username" value="root"/>
<property name="password" value="903213"/> <!--改成自己的密码-->
</dataSource>
</environment>
</environments>
<!--配置实体关系映射器文件-->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
(六)创建日志属性文件
- 在resources目录里创建log4j.properties文件
log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/mybatis.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
(七)测试用户操作
1、创建用户操作测试类
- 在test/java目录里创建net.huawei.mybatis.bean包,然后在包里创建测试类 - TestUserOperation
package net.huawei.mybatis.bean;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
public class TestUserOperation {
private SqlSession sqlSession;
@Before
public void init() {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
sqlSession = factory.openSession();
System.out.println("SQL会话创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testFindById() {
int id = 1;
User user = sqlSession.selectOne("net.huawei.mybatis.mapper.UserMapper.findById", id);
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到~");
}
}
@Test
public void testFindAll() {
List<User> users = sqlSession.selectList("net.huawei.mybatis.mapper.UserMapper.findAll");
users.forEach(user -> System.out.println(user));
}
@After
public void destroy() {
sqlSession.close();
System.out.println("SQL会话已经关闭~");
}
}
2、测试按编号查询用户记录
-
运行测试方法 - testFindById(),查看结果
-
想要去掉警告信息,就得修改MyBatis配置文件
-
再运行测试方法 - testFindById(),查看结果
-
修改testFindById()代码,再运行查看结果
3、测试查询全部用户记录
- 运行测试方法 - testFindAll(),查看结果
三、采用接口方式使用MyBatis
(一)创建用户映射器接口
- 创建net.huawei.mybatis.mapper包,然后在包里创建用户映射器接口 - UserMapper
package net.huawei.mybatis.mapper;
import net.huawei.mybatis.bean.User;
import java.util.List;
public interface UserMapper {
User findById(int id);
List<User> findAll();
}
(二)测试用户映射器接口
1、创建用户映射器接口测试类
- 在test/java里创建net.huawei.mybatis.mapper包,然后在包里创建测试类 - TestUserMapper
package net.huawei.mybatis.mapper;
import net.huawei.mybatis.bean.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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
public class TestUserMapper {
private SqlSession sqlSession;
private UserMapper userMapper;
@Before
public void init() {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
sqlSession = factory.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println("SQL会话创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testFindById() {
int id = 1;
User user = userMapper.findById(id);
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到~");
}
}
@Test
public void testFindAll() {
List<User> users = userMapper.findAll();
users.forEach(user -> System.out.println(user));
}
@After
public void destroy() {
sqlSession.close();
System.out.println("SQL会话已经关闭~");
}
}
2、测试按编号查询用户记录
3、测试查询全部用户记录
四、利用配置类与注解方式使用MyBatis
(一)创建MyBatis配置类
- 在net.huawei.mybatis包里创建config子包,然后在子包里创建MyBatisConfig类
package net.huawei.mybatis.config;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import javax.sql.DataSource;
public class MyBatisConfig {
public static Configuration getConfiguration() {
Configuration configuration = null;
TransactionFactory transactionFactory = new JdbcTransactionFactory();
DataSource dataSource = new PooledDataSource(
"com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/testdb?useSSL=false",
"root",
"903213"
);
Environment environment = new Environment("development", transactionFactory, dataSource);
configuration = new Configuration(environment);
return configuration;
}
}
(二)创建新的用户映射器接口测试类
- 在test/java的net.huawei.mybatis.mapper包里创建TestUserMapperNew类
package net.huawei.mybatis.mapper;
import net.huawei.mybatis.bean.User;
import net.huawei.mybatis.config.MyBatisConfig;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
public class TestUserMapperNew {
private SqlSession sqlSession;
private UserMapper userMapper;
@Before
public void init() {
Configuration configuration = MyBatisConfig.getConfiguration();
configuration.addMapper(UserMapper.class);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(configuration);
sqlSession = factory.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println("SQL会话创建成功~");
}
@Test
public void testFindById() {
int id = 1;
User user = userMapper.findById(id);
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到~");
}
}
@Test
public void testFindAll() {
List<User> users = userMapper.findAll();
users.forEach(user -> System.out.println(user));
}
@After
public void destroy() {
sqlSession.close();
System.out.println("SQL会话已经关闭~");
}
}
(三)修改用户映射器接口
package net.huawei.mybatis.mapper;
import net.huawei.mybatis.bean.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
@Select("SELECT * FROM t_user WHERE id = #{id}")
User findById(int id);
@Select("SELECT * FROM t_user")
List<User> findAll();
}
(四)运行新的用户映射器接口测试类