MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

1.创建一个普通的maven项目
2.在pom.xml中导入依赖
| |
| <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> |
注意在pom.xml配置如下,防止资源导入不成功问题
| |
| <build> |
| <resources> |
| <resource> |
| <directory>src/main/resources</directory> |
| <includes> |
| <include>**/*.properties</include> |
| <include>**/*.xml</include> |
| </includes> |
| <filtering>true</filtering> |
| </resource> |
| <resource> |
| <directory>src/main/java</directory> |
| <includes> |
| <include>**/*.properties</include> |
| <include>**/*.xml</include> |
| </includes> |
| <filtering>true</filtering> |
| </resource> |
| </resources> |
| </build> |
在resources目录下编写MyBatis核心配置文件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="driver" value="com.mysql.jdbc.Driver"/> |
| <property name="url" value="jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8"/> |
| <property name="username" value="root"/> |
| <property name="password" value="root"/> |
| </dataSource> |
| </environment> |
| </environments> |
| |
| <mappers> |
| <mapper resource="com/mao/dao/UserDaoMapper.xml" /> |
| </mappers> |
| </configuration> |
3.测试数据库建立表结构
| CREATE DATABASE `mybatis`; |
| USE `mybatis`; |
| DROP TABLE IF EXISTS `user`; |
| CREATE TABLE `user` ( |
| `id` int(20) NOT NULL, |
| `name` varchar(30) DEFAULT NULL, |
| `password` varchar(30) DEFAULT NULL, |
| PRIMARY KEY (`id`) |
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
| insert into `user`(`id`,`name`,`password`) values (1,'王二','123456'),(2,'张三','abcdef'),(3,'李四','987654'); |
4.创建如下的包结构

5.编写工具类utils下MybatisUtils
| public class MybatisUtils { |
| |
| 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(); |
| } |
| } |
| |
| |
| public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession();} |
| } |
6.在pojo包下创建User实体类
| package com.mao.pojo; |
| |
| |
| |
| public class User { |
| private int id; |
| private String name; |
| private String password; |
| |
| public User() { |
| } |
| |
| public User(int id, String name, String password) { |
| this.id = id; |
| this.name = name; |
| this.password = password; |
| } |
| |
| 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 getPassword() { |
| return password; |
| } |
| |
| public void setPassword(String password) { |
| this.password = password; |
| } |
| |
| @Override |
| public String toString() { |
| return "User{" + |
| "id=" + id + |
| ", name='" + name + '\'' + |
| ", password='" + password + '\'' + |
| '}'; |
| } |
| } |
| |
7.在dao包下创建编写Mapper接口类UserDao.java,并创建Mapper.xml(可以理解为像UserDao接口的实现类的配置)
| public interface UserDao { |
| List<User> getUserList(); |
| } |
| <?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="com.mao.dao.UserDao"> |
| |
| <select id="getUserList" resultType="com.mao.pojo.User"> |
| select * from test.user |
| </select> |
| </mapper> |
然后记得在MyBatis核心配置文件mybatis-config.xml中注册Mapper
| |
| <mappers> |
| <mapper resource="com/mao/dao/UserDaoMapper.xml" /> |
| </mappers> |
8.测试
| public class UserDaoTest { |
| @Test |
| public void test(){ |
| |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| try{ |
| |
| UserDao mapper = sqlSession.getMapper(UserDao.class); |
| List<User> list = mapper.getUserList(); |
| for (User u:list){ |
| System.out.println(u); |
| } |
| |
| |
| |
| |
| |
| }finally { |
| |
| sqlSession.close(); |
| } |
| } |
| } |
其他操作(增删改查)
| public interface UserDao { |
| List<User> getUserList(); |
| |
| |
| |
| User getUserById(int id); |
| |
| |
| int addUser(User user); |
| |
| int updateUser(User user); |
| |
| int deleteUserById(int id); |
| } |
- 在实现mapper中添加相应的配置和实现的具体sql语句
| <mapper namespace="com.mao.dao.UserDao"> |
| |
| <select id="getUserList" resultType="com.mao.pojo.User"> |
| select * from test.user |
| </select> |
| |
| <select id="getUserById" resultType="com.mao.pojo.User" parameterType="int"> |
| select * from test.user where id = #{id} |
| </select> |
| |
| <insert id="addUser" parameterType="com.mao.pojo.User" > |
| insert into test.user (id,name,password) values (#{id},#{name},#{password}) |
| </insert> |
| |
| <update id="updateUser" parameterType="com.mao.pojo.User"> |
| update test.user set name=#{name}, password=#{password} where id = #{id} |
| </update> |
| |
| <delete id="deleteUserById" parameterType="int"> |
| delete from test.user where id = #{id} |
| </delete> |
| </mapper> |
| public class UserDaoTest { |
| @Test |
| public void test(){ |
| |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| |
| UserDao mapper = sqlSession.getMapper(UserDao.class); |
| List<User> list = mapper.getUserList(); |
| for (User u:list){ |
| System.out.println(u); |
| } |
| sqlSession.close(); |
| } |
| @Test |
| public void testGetUserById(){ |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| UserDao mapper = sqlSession.getMapper(UserDao.class); |
| User u = mapper.getUserById(1); |
| System.out.println(u.toString()); |
| sqlSession.close(); |
| |
| } |
| @Test |
| public void testAddUser(){ |
| |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| |
| UserDao mapper = sqlSession.getMapper(UserDao.class); |
| int i = mapper.addUser(new User(5, "Jim", "12321312")); |
| System.out.println(i); |
| |
| sqlSession.commit(); |
| sqlSession.close(); |
| } |
| @Test |
| public void testUpdateUser(){ |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| UserDao mapper = sqlSession.getMapper(UserDao.class); |
| int i = mapper.updateUser(new User(1, "admin", "111111")); |
| sqlSession.commit(); |
| sqlSession.close(); |
| } |
| @Test |
| public void testDeleteUserById(){ |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| UserDao mapper = sqlSession.getMapper(UserDao.class); |
| int i = mapper.deleteUserById(1); |
| sqlSession.commit(); |
| sqlSession.close(); |
| } |
| } |
注意!!
- 增删改一定要提交事务: sqlSession.commit();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理