随着springboot的出现,绝大多数开源框架和中间件都可以通过springboot来整合,并且使用起来非常简单,但是,今天要介绍的是mybatis原生的使用方法。并且分享一下在结合官网学习过程中遇到的问题。
目录
准备工作
数据库版本说明
创建数据库表
快速开始
引入maven依赖
创建数据库实体类
创建持久层接口
创建mapper.xml
创建mybatis配置文件
构建SqlSessionFactory的方式
从XML中构建SqlSessionFactory
运行报错问题解决
不使用XML构建SqlSessionFactory
调用mapper接口方法的方式
绑定sql语句的方式
通过mapper.xml绑定
通过注解绑定
准备工作
数据库版本说明
在开始本篇文章之前,需要提前创建好相关的数据库和表。文章使用的mysql版本为MariaDB 10.6,对应mysql版本为8.0,所以mybatis-config.xml中驱动不一样。
mysql 8.0之前的数据库驱动类为
com.mysql.jdbc.Driver
mysql 8.0之后的数据库驱动类为
com.mysql.cj.jdbc.Driver
创建数据库表
创建一个数据库mybatis,并在数据库下创建user表,执行以下SQL脚本即可。
/*Navicat Premium Data TransferSource Server : MariaDBSource Server Type : MariaDBSource Server Version : 100605 (10.6.5-MariaDB)Source Host : 127.0.0.1:3306Source Schema : mybatisTarget Server Type : MariaDBTarget Server Version : 100605 (10.6.5-MariaDB)File Encoding : 65001Date: 24/10/2023 23:57:18
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户名',`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '12345' COMMENT '密码',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'mumu', '12345');
INSERT INTO `user` VALUES (2, 'system', '12345');SET FOREIGN_KEY_CHECKS = 1;
快速开始
首先,需要找到mybatis的官网
https://mybatis.org/mybatis-3/zh/getting-started.htmlhttps://mybatis.org/mybatis-3/zh/getting-started.html如图,根据官网的步骤开始使用mybatis
引入maven依赖
在IntelliJ IDEA中创建一个maven项目mybatis,在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>org.example</groupId><artifactId>mybatis</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.13</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
本篇文章使用的mybatis是最新的版本,更多版本可以通过maven仓库搜索
https://central.sonatype.com/artifact/org.mybatis/mybatis/versionshttps://central.sonatype.com/artifact/org.mybatis/mybatis/versions
创建数据库实体类
在项目src/main/java包下创建多级包org.example.pojo包,在pojo包下创建一个User.java
package org.example.pojo;import lombok.Data;/*** @author heyunlin* @version 1.0*/
@Data
public class User {private String id;private String username;private String password;
}
创建持久层接口
在src/main/java/org/example包下创建mapper包,在mapper包下创建一个UserMapper.java
package org.example.mapper;import org.example.pojo.User;import java.util.List;/*** @author heyunlin* @version 1.0*/
public interface UserMapper {List<User> selectAll();
}
创建mapper.xml
紧接着,在src/main/resources目录下也创建多级目录org.example.mapper,目录结构和UserMapper.java接口的路径保持一致。
<?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="org.example.mapper.UserMapper"><select id="selectAll" resultType="org.example.pojo.User">select id, username, password from user</select></mapper>
创建mybatis配置文件
根据官网在resources目录下创建一个mybatis的配置文件,文件名可以任意命名,在这里就命名为mybatis-config.xml
mybatis-config.xml的内容,用户名、密码以及数据库名根据自己实际情况修改
<?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="username" value="root" /><property name="password" value="root" /><property name="driver" value="com.mysql.cj.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis" /></dataSource></environment></environments><mappers><mapper class="org/example/mapper/UserMapper.xml" /></mappers>
</configuration>
构建SqlSessionFactory的方式
从XML中构建SqlSessionFactory
在org.example包下面创建一个MybatisExample类来测试一下,然后运行main方法
package org.example;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.example.pojo.User;import java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** @author heyunlin* @version 1.0*/
public class MybatisExample {public static void main(String[] args) throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> list = sqlSession.selectList("org.example.mapper.UserMapper.selectAll");System.out.println(list);}}
运行报错问题解决
运行出错了,说是找不到类org/example/mapper/UserMapper.xml
很显然这不是类,所以改成org/example/mapper/UserMapper再试试
然后再次运行main方法,居然又报错了,说是找不到org/example/mapper/UserMapper类,但是其实这个类是有的。
如下图,已经编译到相关目录下
这也是官网坑的地方之一,这里的/要改成.
于是再次修改mybatis-config.xml
<?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="username" value="root" /><property name="password" value="root" /><property name="driver" value="com.mysql.cj.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis" /></dataSource></environment></environments><mappers><mapper class="org.example.mapper.UserMapper" /></mappers>
</configuration>
这次运行成功查询到了数据库user表的所有数据
不使用XML构建SqlSessionFactory
为了方便动态修改获取SqlSessionFactory的方式,对原来的代码进行重构,抽离获取SqlSessionFactory的方法。
package org.example;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.example.pojo.User;import java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** @author heyunlin* @version 1.0*/
public class MybatisExample {private static SqlSessionFactory getSqlSessionFactory() throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);return new SqlSessionFactoryBuilder().build(inputStream);}public static void main(String[] args) throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();SqlSession sqlSession = sqlSessionFactory.openSession();List<User> list = sqlSession.selectList("org.example.mapper.UserMapper.selectAll");System.out.println(list);}}
如下图所示,官网提供的代码中,第一行代码获取数据源的工厂类很显然是自己写的,我们要用其他方式获取数据源对象。
修改getSqlSessionFactory()方法的代码,查看Datasource有那些子类,博主看这个PooledDataSource比较顺眼,就用了它。
于是再次修改MybatisExample的代码
package org.example;import com.mysql.cj.jdbc.MysqlDataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
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.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.example.mapper.UserMapper;
import org.example.pojo.User;import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** @author heyunlin* @version 1.0*/
public class MybatisExample {private static SqlSessionFactory getSqlSessionFactory(int method) throws IOException {// 从XML中构建 SqlSessionFactoryif (method == 1) {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);return new SqlSessionFactoryBuilder().build(inputStream);} else if (method == 2) { // 不使用XML构建SqlSessionFactoryDataSource dataSource = new PooledDataSource("com.mysql.cj.jdbc.Driver","jdbc:mysql://localhost:3306/mybatis", "root", "root");TransactionFactory transactionFactory = new JdbcTransactionFactory();Environment environment = new Environment("development", transactionFactory, dataSource);Configuration configuration = new Configuration(environment);configuration.addMapper(UserMapper.class);return new SqlSessionFactoryBuilder().build(configuration);}return null;}public static void main(String[] args) throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(2);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> list = sqlSession.selectList("org.example.mapper.UserMapper.selectAll");System.out.println(list);}}
调用mapper接口方法的方式
上面已经提供了一种方法:通过SqlSession的selectXxx()方法
public static void main(String[] args) throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(2);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> list = sqlSession.selectList("org.example.mapper.UserMapper.selectAll");System.out.println(list);}
接下来再介绍一种
public static void main(String[] args) throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(2);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> users = userMapper.selectAll();System.out.println(users);}
绑定sql语句的方式
注意,两种方式不能一起使用,否则会报错。
所以用了注解就要注释掉UserMapper.xml里对应的的statement
通过mapper.xml绑定
上面用的方式就是通过mapper.xml绑定。
通过注解绑定
package org.example.mapper;import org.apache.ibatis.annotations.Select;
import org.example.pojo.User;import java.util.List;/*** @author heyunlin* @version 1.0*/
public interface UserMapper {@Select("select id, username, password from user")List<User> selectAll();
}
<?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="org.example.mapper.UserMapper"><!-- <select id="selectAll" resultType="org.example.pojo.User">-->
<!-- select id, username, password from user-->
<!-- </select>--></mapper>
好了,文章就分享到这里了,代码已开源,可按需获取~
https://gitee.com/he-yunlin/mybatis.githttps://gitee.com/he-yunlin/mybatis.git