MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
https://mybatis.org/mybatis-3/zh/index.html
最好的官方文档之一,一篇文档读懂,根本不用看其他任何教程
window10
IntelliJ Idea(2020.2)
JDK 8
MySql server
项目名(name)随意,GroupId一般是域名的倒写,一般和你的包结构一致
其实随便填就行
图片仅供参考,我是在项目中创建了子Module,不必模仿,用你们新建的项目就够了
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL COMMENT '用户名称',,
`pwd` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '王五',‘123’);
INSERT INTO `user` VALUES ('10', '张三', '123');
INSERT INTO `user` VALUES ('16', '张小明', ‘123’);
INSERT INTO `user` VALUES ('22', '陈小明', ‘123’);
INSERT INTO `user` VALUES ('24', '张三丰', ‘123’);
INSERT INTO `user` VALUES ('25', '陈小明', ‘123’);
INSERT INTO `user` VALUES ('26', '王五', ‘123’);
新建package名叫model
新建class User
package com.term.model;
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
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 String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
新建package名叫dao
新建interface名叫UserDao
package com.term.dao;
import com.term.model.User;
import java.util.List;
import java.util.Map;
public interface UserDao {
List<User> getAllUsers();
int updateUser(User user);
int addUser(User user);
int deleteUser(int id);
User getOneUser(Map<String, Object> map);
List<User> getUsersByNameLike(String name);
}
以上内容和普通的JDBC一致
接下来引入Mybatis
打开项目的pom文件,导入Mybatis依赖
<?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.term</groupId>
<artifactId>MybatisStudy</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
如上所示,我导入了mybatis 3.5.2 jar包,和mybatis所依赖的Junit、mysql
中的内容时配置文件扫描,以免编译器不加载配置文件
在项目的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>
<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/mybatis?useUnicode=true&characterEncoding=utf8&autoReconnect=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/term/dao/UserMapper.xml"/>
</mappers>
</configuration>
简单解释一下,这是mybatis最简单的配置,
environments便签是环境配置,如上主要是dataSource连接数据库的参数,以及transactionManager决定数据库事务处理方式
mappers标签用来指定mapper.xml,如上
意思就是我待会会在com/term/dao中创建一个Mapper.xml实现数据库具体操作
如果不配置这各标签,那么mapper将不生效
就这些
写一个全局的工具类,静态返回初始化好的SqlSession对象:
package com.term.utils;
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;
/**
* 初始化sqlSessionFactory,并返回sqlSession
*/
public class MybatisUtils {
//SqlSessionFactory 对象最好是全局的单例变量
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//每个请求初始化一个SqlSession,调用这个方法
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
//得到支持自动提交的SqlSession对象
public static SqlSession getAutoCommitSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
刚才我们写了一个UserDao接口,并定义了一些数据库操作方法,mybatis要求我们使用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">
<!-- namespace指定你要实现的mapper接口全名 -->
<mapper namespace="com.term.dao.UserDao">
<!--标签名是操作方式,id与接口中方法名一致 resultType指定返回值类型的全名-->
<select id="getAllUsers" resultType="com.term.model.User">
<!--标签内写sql语句-->
select * from user
</select>
<update id="updateUser" parameterType="com.term.model.User">
<!--用#{}传入参数,实体类的属性可以直接用属性名调用,方法参数可以直接用参数名-->
update user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
<insert id="addUser" parameterType="com.term.model.User">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
<select id="getOneUser" parameterType="map" resultType="com.term.model.User">
select * from user where id=#{id}
</select>
<select id="getUsersByNameLike" parameterType="String" resultType="com.term.model.User">
select * from user where name like #{name}
</select>
</mapper>
好了,写完了
package com.term.dao;
import com.term.model.User;
import com.term.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Mybatis 增删改查Junit
*/
public class UserDaoTest {
@Test
public void testGetAllUser() {
final SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> users = userDao.getAllUsers();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void testAddUser() {
final SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao.addUser(new User(1, "li", "zhang3"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void testUpdateUser() {
final SqlSession sqlSession = MybatisUtils.getSqlSession();
final UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao.updateUser(new User(2, "lisi", "lisq"));
//增删改需要提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void testDelUser(){
final SqlSession sqlSession = MybatisUtils.getSqlSession();
final UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao.deleteUser(1);
//增删改需要提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void testGetOneUser(){
final SqlSession sqlSession = MybatisUtils.getSqlSession();
final UserDao userDao = sqlSession.getMapper(UserDao.class);
Map<String, Object> map = new HashMap<>();
map.put("id", 2);
System.out.println(userDao.getOneUser(map));
sqlSession.close();
}
@Test
public void testGetUsersByNameLike(){
final SqlSession sqlSession = MybatisUtils.getSqlSession();
final UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> users = userDao.getUsersByNameLike("%l%");
for (User user : users)
System.out.println(user);
sqlSession.close();
}
}
感谢大家收看