demo 地址:https://github.com/DKAngel/MyBatisDemo
如何上传项目到 github
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。可以通过XML
或注解
的方式来配置和映射原始类型、接口和 POJO为数据库中的记录。详见 MyBatis官方文档
各ORM框架对比 MyBatis、Hibernate、JPA
net start mysql
mysql -u root -p[pwd]
create database test
CREATE TABLE `t_user` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`sex` enum('MALE','FEMALE') DEFAULT 'MALE',
`age` smallint NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=100 DEFAULT CHARSET=utf8;
通过 IDEA 创建SpringBoot项目,勾选依赖:Mybatis Framework
、MySQL Driver
依赖下载缓慢,修改maven setting.xml
mysql.properties
Driver=com.mysql.cj.jdbc.Driver
Url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=true
Username=root
Password=123
mybatis-config.xml
<configuration>
<properties resource="mysql.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${Driver}"/>
<property name="url" value="${Url}"/>
<property name="username" value="${Username}"/>
<property name="password" value="${Password}"/>
dataSource>
environment>
environments>
configuration>
User.java
package com.example.demo.entity;
public class User {
private Integer id;
private String name;
private Enum sex;
private Integer age;
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 Enum getSex() {
return sex;
}
public void setSex(Enum sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
SexEnum.java
package com.example.demo.common;
public enum SexEnum {
MALE,
FEMALE,
}
UserMapper.java
package com.example.demo.mapper;
import com.example.demo.entity.User;
import java.util.List;
public interface UserMapper {
int insertUser(User user);
List<User> selectAllUser();
User selectUserById(Integer id);
}
UserMapper.xml
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="userMap" type="com.example.demo.entity.User">
<id property="id" column="id" javaType="java.lang.Integer"/>
<result property="name" column="name" javaType="java.lang.String"/>
<result property="sex" column="sex" javaType="com.example.demo.common.SexEnum"/>
<result property="age" column="age" javaType="java.lang.Integer"/>
resultMap>
<insert id="insertUser">
insert into t_user (name, sex, age)
values (#{name}, #{sex}, #{age});
insert>
<select id="selectAllUser" resultMap="userMap">
select *
from t_user;
select>
<select id="selectUserById" resultMap="userMap">
select *
from t_user
where id = #{id};
select>
mapper>
mybatis-config.xml
...
<typeAliases>
<package name="com.example.demo.entity"/>
typeAliases>
...
<mappers>
<mapper resource="com/example/demo/mapper/UserMapper.xml"/>
mappers>
强迫症,没有配置Database的话,UserMapper.xml里的sql语句会报红
Server returns invalid timezone. Go to 'Advanced' tab and set 'serverTimezone' property manually
set global time_zone='+8:00';
Connection to test@localhost failed. [08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.
?serverTimezone=GMT
,参考这里package com.example.demo.tool;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisTool {
private static SqlSessionFactory sqlSessionFactory;
static {
Reader reader = null;
try {
reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
在 UserMapper.java 中使用快捷键 Alt + Insert 创建测试类
package com.example.demo.mapper;
import com.example.demo.entity.SexEnum;
import com.example.demo.entity.User;
import com.example.demo.tool.MyBatisTool;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
class UserMapperTest {
@Test
void insertUser() {
User user = new User();
user.setName("dkangel");
user.setSex(SexEnum.MALE);
user.setAge(24);
SqlSession sqlSession = MyBatisTool.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int len;
try {
len = userMapper.insertUser(user);
sqlSession.commit(true);
} finally {
sqlSession.close();
}
Assert.assertEquals(1, len);
}
@Test
void selectAllUser() {
SqlSession sqlSession = MyBatisTool.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users;
try {
users = userMapper.selectAllUser();
sqlSession.commit();
} finally {
sqlSession.close();
}
Assert.assertEquals(1, users.size());
}
@Test
void selectUserById() {
SqlSession sqlSession = MyBatisTool.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user;
try {
user = userMapper.selectUserById(101);
sqlSession.commit();
} finally {
sqlSession.close();
}
Assert.assertEquals("dkangel", user.getName());
}
}