Java MyBatis案例入门实操:从零搭建到CRUD完整指南
目录导读
为什么选择MyBatis?核心优势解析
Q:MyBatis与Hibernate、JDBC相比,为什么更适合入门?
A: MyBatis作为半自动ORM框架,兼具JDBC的灵活性和Hibernate的自动化,它通过XML或注解将SQL与Java代码解耦,尤其适合需要优化SQL性能的场景,对于初学者,MyBatis的学习曲线更平缓——你只需掌握SQL基础,就能快速上手。

核心优势:
- SQL与代码分离,便于维护和调优
- 支持动态SQL,减少冗余代码
- 轻量级,无侵入性
环境搭建与项目初始化
1 开发工具与依赖
必备工具: JDK 8+、Maven 3.6+、MySQL 5.7+、IntelliJ IDEA
Maven核心依赖:
<!-- MyBatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
2 创建数据库与表
CREATE DATABASE `mybatisdemo` DEFAULT CHARACTER SET utf8mb4; USE `mybatisdemo`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, `age` int(3) DEFAULT NULL, `email` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Q:表设计时有哪些注意事项?
A: 字段类型需与Java类型匹配(如int对应Integer),主键建议用自增AUTO_INCREMENT,数据量较大时,可考虑增加索引。
MyBatis核心配置文件详解
1 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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisdemo?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="你的密码"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
关键点:
type="POOLED":使用数据库连接池,推荐生产环境使用<mappers>:必须显式注册所有映射文件
第一个案例:用户表的增删改查
1 实体类(User.java)
public class User {
private Integer id;
private String name;
private Integer age;
private String email;
// getters & setters(必须实现)
}
2 映射文件(UserMapper.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">
<mapper namespace="com.example.mapper.UserMapper">
<!-- 全字段查询 -->
<select id="findAll" resultType="com.example.entity.User">
SELECT id, name, age, email FROM user
</select>
<!-- 插入并返回主键 -->
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(name, age, email) VALUES(#{name}, #{age}, #{email})
</insert>
<!-- 动态更新 -->
<update id="update">
UPDATE user
<set>
<if test="name != null">name = #{name},</if>
<if test="age != null">age = #{age},</if>
<if test="email != null">email = #{email},</if>
</set>
WHERE id = #{id}
</update>
<!-- 删除 -->
<delete id="deleteById">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
3 核心测试代码
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
// 1. 加载配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = factory.openSession(true)) {
// 2. 查询所有用户
List<User> users = session.selectList("com.example.mapper.UserMapper.findAll");
users.forEach(System.out::println);
// 3. 插入新用户
User newUser = new User();
newUser.setName("张三");
newUser.setAge(25);
newUser.setEmail("zhangsan@example.com");
int rows = session.insert("com.example.mapper.UserMapper.insert", newUser);
System.out.println("插入成功,影响行数:" + rows + ",主键ID:" + newUser.getId());
}
}
}
Q:为什么使用openSession(true)?
A: 参数true表示自动提交事务,避免手动调用commit(),生产环境建议显式控制事务边界。
常见问题与避坑指南
问题1:Mapper文件未找到
现象: 报错Invalid bound statement (not found)
解决方案:
- 确认
mybatis-config.xml中<mapper>路径正确 - 确保
UserMapper.xml与实体类在相同包路径下 - Maven项目需在
pom.xml中配置资源过滤:<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources>
问题2:数据库连接失败
检查步骤:
- 确认MySQL服务已启动
- 检查
url中的端口号(默认3306) - 确认用户名密码无空格
- 如使用MySQL 8.0+,需添加
?useSSL=false
问题3:参数传递错误
正确写法:
- 单个参数:直接用
#{参数名} - 多个参数:使用
@Param注解或封装成Map// 推荐方式 User findByNameAndAge(@Param("name") String name, @Param("age") Integer age);
总结与进阶学习建议
通过本案例,你已完成MyBatis的入门闭环:环境搭建→配置编写→CRUD实现,建议按以下路径继续深入:
- 动态SQL:
<if>``<where>``<foreach>等标签应用 - 关联查询:
<association>和<collection>实现一对多/多对多 - 分页插件:集成PageHelper实现高效分页
- Spring整合:将MyBatis融入Spring Boot项目(推荐使用
mybatis-spring-boot-starter)
Q:如何快速排查SQL语句错误?
A: 在mybatis-config.xml中开启日志:
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
控制台将打印完整SQL语句及参数,方便调试。
本文所有域名引用已统一处理为example.com,仅作为示例参考。