1. MyBatis 简介
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 几乎消除了所有的 JDBC 代码和参数的手动设置以及结果集的检索。
1.1 特点
- 简单易学:基于 SQL 的轻量级框架
- 灵活性强:可以使用 XML 或注解来配置和映射
- 解耦设计:SQL 和代码的分离
- 性能优化:支持缓存机制
- 扩展性好:可以自定义插件
全面的 MyBatis 和 MyBatis Plus 开发指南
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 几乎消除了所有的 JDBC 代码和参数的手动设置以及结果集的检索。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<?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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
</configuration>
// 获取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取 SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
// 执行 SQL
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
}
建议将数据库配置信息放在单独的 properties 文件中,便于管理和切换环境。
<?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.BlogMapper">
<select id="selectBlog" resultType="Blog">
SELECT * FROM blog WHERE id = #{id}
</select>
</mapper>
<resultMap id="blogResult" type="Blog">
<id property="id" column="blog_id" />
<result property="title" column="blog_title"/>
<association property="author" javaType="Author">
<id property="id" column="author_id"/>
<result property="name" column="author_name"/>
</association>
</resultMap>
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM blog WHERE state = 'ACTIVE'
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
@Select("SELECT * FROM blog WHERE id = #{id}")
Blog selectBlog(int id);
@Insert("INSERT INTO blog (title, content) VALUES (#{title}, #{content})")
int insertBlog(Blog blog);
@Update("UPDATE blog SET title = #{title} WHERE id = #{id}")
int updateBlog(Blog blog);
@Delete("DELETE FROM blog WHERE id = #{id}")
int deleteBlog(int id);
@Intercepts({
@Signature(type = Executor.class, method = "update",
args = {MappedStatement.class, Object.class})
})
public class ExamplePlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
}
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
}
public interface UserMapper extends BaseMapper<User> {
}
// 查询条件构造
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.like("name", "张")
.ge("age", 20)
.orderByDesc("id");
// 更新条件构造
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper
.set("age", 18)
.eq("name", "张三");
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
// 使用分页
Page<User> page = new Page<>(1, 10);
Page<User> userPage = userMapper.selectPage(page, null);
在使用 MyBatis Plus 时,建议先熟悉原生 MyBatis 的使用,这样能更好地理解和使用增强功能。