MyBatis-入门基础
1.创建测试数据库
CREATE DATABASE `mybatis`; -- 使用此数据库 USE `mybatis`; -- 创建 user 表 CREATE TABLE user( `id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(30) NOT NULL, `pwd` VARCHAR(30) NOT NULL )ENGINE=INNODB CHARSET UTF8; -- 添加3条测试数据 INSERT INTO user(`name`, `pwd`) VALUES ('张三', '864531'), ('李四', '1564513'), ('刘鹏飞', '9846513')
2.搭建项目
使用IDEA创建一个空的maven项目
然后删除其中的src项目,将此工程作为一个父工程
3.添加maven依赖
org.mybatis mybatis 3.5.5
4.添加第一个Module测试项目
5.创建pojo实体类
使用@Data注解可以省去大量get/set方法
@Data public class User implements Serializable { private Integer id; private String name; private String pwd; }
6.配置Mybatis核心文件mybatis-config.xml
default="development"> "development"> "JDBC"/> "POOLED"> "driver" value="com.mysql.jdbc.Driver"/> "url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/> "username" value="root"/> "password" value="123456"/>
7.创建一个工具类用于获取SqlSession
public class MyBatisUtil { private static SqlSessionFactory sqlSessionFactory; static { try { // 初始化构建 SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } /** * 通过 SqlSessionFactory 创建一个 SqlSession 对象 * * @return SqlSession 对象 */ public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } }
8.添加UserMapper接口
public interface UserMapper { /** * 查询所有用户信息 * * @return 用户信息 */ public ListgetUserList(); }
9.添加UserMapper.xml配置文件编写sql语句
mapper namespace="com.bai.dao.UserMapper"> <select id="getUserList" resultType="com.bai.pojo.User"> select * from mybatis.user; select>
10.添加测试类测试
public class UserMapperTest { @Test public void test01() { SqlSession sqlSession = null; try { // 1.获取到 SqlSession 对象那个 sqlSession = MyBatisUtil.getSqlSession(); // 2.通过 getMapper 方法加载对应的 UserMapper 接口 UserMapper mapper = sqlSession.getMapper(UserMapper.class); // 3.执行接口方法 ListuserList = mapper.getUserList(); for (User user : userList) { System.out.println(user); } } catch (Exception e) { e.printStackTrace(); } finally { // 4.关闭 sqlSession 对象 if (sqlSession != null) { sqlSession.close(); } } } }
然后通过运行我们发现一个被遗忘的问题, UserMapper文件并没有被注册到 MapperRegistry 中
Type interface com.bai.dao.UserMapper is not known to the MapperRegistry.
我们要解决这个问题,需要在 mybatis-config.xml 文件中注册此 Mapper 文件
然后我们还有遇到一个初始化异常错误
Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/bai/dao/UserMapper.xml
发生这个错误是因为在 java 源码中并不能加载 xml 类型的文件,要解决这个问题,需要修改一个 pom.xml 文件,添加一些配置
src/main/resources **/*.properties **/*.xml true src/main/java **/*.properties **/*.xml true
最终测试结果: