Mybatis 入门与配置
TIP
MyBatis 是一款优秀的持久层框架,支持自定义 SQL、存储过程和高级映射。它避免了几乎所有的 JDBC 代码和手动设置参数。
核心组件
| 组件 | 说明 |
|---|---|
| SqlSessionFactory | 创建 SqlSession 的工厂 |
| SqlSession | 数据库会话,执行 SQL |
| Mapper | 映射接口,定义数据库操作 |
| XML 映射文件 | SQL 定义和结果映射 |
配置 MyBatis
xml
<!-- 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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<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/demo"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>快速开始
java
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
// 获取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取 SqlSession
try (SqlSession session = sqlSessionFactory.openSession(true)) {
User user = session.selectOne("com.example.mapper.UserMapper.selectById", 1L);
System.out.println(user);
}
}
}使用 Mapper 接口
java
// Mapper 接口
public interface UserMapper {
User selectById(Long id);
List<User> selectAll();
int insert(User user);
int update(User user);
int deleteById(Long id);
}
// 使用 Mapper(推荐)
try (SqlSession session = sqlSessionFactory.openSession(true)) {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectById(1L);
}