maven 仓库获取
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.13version>
dependency>
Github 获取源码
中文文档
编写第一个 Mybatis 程序首先需要有一个具体步骤:
搭建环境–> 导入 Mybatis–>编写代码–>测试
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userId` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`userName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名称',
`userAge` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户年龄',
PRIMARY KEY (`userId`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '张三', '12');
INSERT INTO `user` VALUES (2, '李四', '15');
INSERT INTO `user` VALUES (3, '王五', '18');
SET FOREIGN_KEY_CHECKS = 1;
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.13version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.33version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
dependencies>
mybatis-config.xml
的 xml 文件
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<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>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
mappers>
configuration>
property
标签中的 value 值,就是我们在 JDBC 中编写配置文件对应的
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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://localhost:3306/mybatis?TRUE&useUnicode=TRUE&characterEncoding=UTF-8&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
mappers>
configuration>
每个 Mybatis 的应用都是一个以 SqlSessionFactory 的实例为核心的
SqlSessionFactory 可以通过 SqlSessionFactoryBuilder 来获取
**而 SqlSessionFactoryBuilder 可以从 XML 配置文件来构建出 SqlSessionFactory **
从 SqlSessionFactory 可以获取 SqlSession 实例
通过 SqlSession 可以直接执行已经映射的 SQL 语句
在 utils 包下创建一个工具类 MybatisUtils
编写 MybatisUtils 类,获取 SqlSessionFactory 实例
package com.qiaoer.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
//获取资源
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String resource
的值是刚刚编写的 resource 文件夹下的 xml 文件路径
通过已经获取的 SqlSessionFactory 实例,来获取 SqlSession 实例
编写 getSqlSession() 方法,来获取 SqlSession 实例
package com.qiaoer.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;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
//获取资源
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//获取 SqlSession 实例
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
package com.qiaoer.entity;
public class User {
private int userId;
private String userName;
private String userAge;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAge() {
return userAge;
}
public void setUserAge(String userAge) {
this.userAge = userAge;
}
public User() {
}
public User(int userId, String userName, String userAge) {
this.userId = userId;
this.userName = userName;
this.userAge = userAge;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAge='" + userAge + '\'' +
'}';
}
}
package com.qiaoer.dao;
import com.qiaoer.entity.User;
import java.util.List;
public interface UserDao {
//获取所有用户
List<User> getUsers();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qiaoer.dao.UserDao">
<!-- SQL 语句查询-->
<select id="selectBlog" resultType="com.qiaoer.entity.User">
select * from user
</select>
</mapper>
其中
中的 namespace
的值对应的是要实现的接口类
中 id
的值为对应的方法名
resultType
属性表示返回一个结果
resultType
的值为返回值类型的返回类型对应的实体类
编写完 UserMapper.xml 后,需要在 Mybatis 的核心配置文件 mybatis-config.xml
进行 Mapper 注册
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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://localhost:3306/mybatis?TRUE&useUnicode=TRUE&characterEncoding=UTF-8&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/qiaoer/dao/UserMapper.xml"/>
</mappers>
</configuration>
则表现 Mapper 注册resource
属性的值就是对应的 Mapper.xml 文件路径
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
import com.qiaoer.dao.UserDao;
import com.qiaoer.entity.User;
import com.qiaoer.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class Test01 {
public static void main(String[] args) {
//第一步,获取 SqlSession 对象
SqlSession sqlSession= MybatisUtils.getSqlSession();
//方法一:通过 SqlSession 对象获取实现类
System.out.println("=====方法1=====");
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> users = mapper.getUsers();
for (User user:users) {
System.out.println(user);
}
//直接获取结果
List<User> UserLists = sqlSession.selectList("com.qiaoer.dao.UserDao.getUsers");
System.out.println("=====方法2=====");
for (User user:UserLists) {
System.out.println(user);
}
//关闭 SqlSession
sqlSession.close();
}
}
在 Mybatis 中编写dao层的实现类的 Mapper.xml 文件中,对增删改查的标签进行介绍
<select id="对应方法" resultType="方法的返回值类型" parameterType="方法的参数类型">
查询的 SQL 语句
select>
<mapper namespace="com.qiaoer.dao.UserDao">
<!-- SQL 语句查询-->
<select id="selectBlog" resultType="com.qiaoer.entity.User" parameterType="int">
select * from user where userId=#{id}
</select>
</mapper>
<insert id="对应方法" parameterType="方法的参数类型">
增加的 SQL 语句
insert>
<insert id="addUser" parameterType="com.qiaoer.entity.User">
insert into user (userName, userAge) values (#{userName},#{userAge});
</insert>
其中 #{userName},#{userAge}
两个均是 User 对象的属性名
==注意:==当我们执行 SQL 语句的增删改时,都需要开启 SQL 的提交事务,否则并不会实际添加
开启提交事务使用 SqlSession 中的 commit() 方法
代码示例
import com.qiaoer.dao.UserDao;
import com.qiaoer.entity.User;
import com.qiaoer.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class Test01 {
public static void main(String[] args) {
//第一步,获取 SqlSession 对象
SqlSession sqlSession= MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
//执行增加用户
mapper.addUser(new User(-1,"你好","15"));
//查询所有用户
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
//提交事务
sqlSession.commit();
//关闭 SqlSession
sqlSession.close();
}
}
<insert id="对应方法" parameterType="方法的参数类型">
修改的 SQL 语句
insert>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qiaoer.dao.UserDao">
<update id="updateUser" parameterType="com.qiaoer.entity.User">
update user set userName=#{userName} where userId=#{userId};
update>
mapper>
import com.qiaoer.dao.UserDao;
import com.qiaoer.entity.User;
import com.qiaoer.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class Test01 {
public static void main(String[] args) {
//第一步,获取 SqlSession 对象
SqlSession sqlSession= MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
//执行修改 id为1的用户
mapper.updateUser(new User(1,"Qiaoer","15"));
//查询所有用户
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
//提交事务
sqlSession.commit();
//关闭 SqlSession
sqlSession.close();
}
}
<delete id="对应方法" parameterType="方法的参数类型">
删除的 SQL 语句
delete>
package com.qiaoer.dao;
import com.qiaoer.entity.User;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public interface UserDao {
//通过用户年龄,用户姓名,查询用户
List<User> getUserByUserAgeAndUserName(Map<String, Object> map);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qiaoer.dao.UserDao">
<select id="getUserByUserAgeAndUserName" resultType="com.qiaoer.entity.User" parameterType="map">
select * from user where userAge=#{userAge} and userName=#{userName}
select>
mapper>
#{userAge}
和 #{userName}
都属于 map 的 key 值import com.qiaoer.dao.UserDao;
import com.qiaoer.entity.User;
import com.qiaoer.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class Test01 {
public static void main(String[] args) {
//获取 SqlSession 对象
SqlSession sqlSession=MybatisUtils.getSqlSession();
//获取实现类
UserDao userDao=sqlSession.getMapper(UserDao.class);
//创建参数 map
Map<String, Object> map=new HashMap<String, Object>();
map.put("userAge",15);
map.put("userName","Qiaoer");
//调用查询方法
List<User> userByUserAgeAndUserName = userDao.getUserByUserAgeAndUserName(map);
//输出结果
for (User user : userByUserAgeAndUserName) {
System.out.println(user);
}
//提交事务
sqlSession.commit();
//关闭 SqlSession
sqlSession.close();
}
}
mybatis-config.xml
- configuration(配置)
- properties(属性)
- settings(设置)
- typeAliases(类型别名)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- databaseIdProvider(数据库厂商标识)
- mappers(映射器)
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="test">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?TRUE&useUnicode=TRUE&characterEncoding=UTF-8&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?TRUE&useUnicode=TRUE&characterEncoding=UTF-8&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/qiaoer/dao/UserMapper.xml"/>
mappers>
configuration>
在上方的
标签内,
标签代表不同的环境
environment
标签的属性 id,则对应的是自己的环境名称
environments
标签的 属性 default,则表示用户要选择哪个环境,与environment
标签的属性 id 的值对应
例如,上方示例中,我的 environments
标签的属性 default 的值为 test ,则代表我选择了 环境
标签为事务管理器
标签为数据源
标签引入
必须放在
标签内部的最顶部
标签的 resource 属性则代表配置文件的路径
标签中,可以使用配置文件中的键来调用
标签内也可以写入配置信息
标签内的子元素和外部配置文件 之间的顺序存在一个优先级顺序[外链图片转存中…(img-q4RXm37z-1690863007343)]
标签引入
必须放在
标签内部的最顶部[外链图片转存中…(img-h8xqCyEL-1690863007343)]
标签的 resource 属性则代表配置文件的路径
标签中,可以使用配置文件中的键来调用[外链图片转存中…(img-OrgPNL0u-1690863007343)]
标签内也可以写入配置信息[外链图片转存中…(img-hqFB60K9-1690863007343)]
标签内的子元素和外部配置文件 之间的顺序存在一个优先级顺序