引言
MyBatis 是一个优秀的持久层框架,它消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
本文将详细介绍 MyBatis 的实战指南和进阶技巧,帮助读者从入门到精通。
第一章:MyBatis 基础入门
1.1 MyBatis 简介
MyBatis 是一个半自动化的持久层框架,它使用 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs 映射成数据库中的记录。
1.2 环境搭建
- 添加依赖:在 Maven 项目中添加 MyBatis 依赖。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
- 配置文件:创建
mybatis-config.xml文件,配置数据源、事务管理器等。
<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=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
- Mapper 文件:创建
UserMapper.xml文件,定义 SQL 映射。
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectById" resultType="com.example.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
- 接口定义:创建
UserMapper接口。
public interface UserMapper {
User selectById(Integer id);
}
1.3 运行测试
使用以下代码运行测试:
public class MyBatisTest {
public static void main(String[] args) throws IOException {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(new FileInputStream("src/main/resources/mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectById(1);
System.out.println(user);
} finally {
sqlSession.close();
}
}
}
第二章:MyBatis 进阶技巧
2.1 动态 SQL
MyBatis 支持动态 SQL,可以使用 <if>、<choose>、<when>、<otherwise> 等标签实现条件判断。
<select id="selectUsers" resultType="User">
SELECT * FROM users
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
2.2 关联查询
MyBatis 支持关联查询,可以使用 <resultMap> 定义关联关系。
<resultMap id="userResultMap" type="User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="age" column="age"/>
<association property="address" column="address_id" select="selectAddress"/>
</resultMap>
<select id="selectUser" resultMap="userResultMap">
SELECT * FROM users WHERE id = #{id}
</select>
<select id="selectAddress" resultType="Address">
SELECT * FROM addresses WHERE id = #{id}
</select>
2.3 批量操作
MyBatis 支持批量操作,可以使用 <foreach> 标签实现。
<insert id="insertUsers">
INSERT INTO users (username, age) VALUES
<foreach collection="users" item="user" separator=",">
(#{user.username}, #{user.age})
</foreach>
</insert>
2.4 缓存机制
MyBatis 支持一级缓存和二级缓存,可以有效地提高查询效率。
一级缓存:在同一个 SqlSession 中,相同的查询会被缓存起来,后续查询可以直接从缓存中获取结果。
二级缓存:在同一个 namespace 中,相同的查询会被缓存起来,不同的 namespace 之间不会共享缓存。
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
第三章:MyBatis 实战案例
3.1 用户管理系统
本节将介绍如何使用 MyBatis 实现一个简单的用户管理系统,包括用户注册、登录、查询等功能。
- 实体类:定义
User和Address实体类。
public class User {
private Integer id;
private String username;
private Integer age;
private Address address;
// 省略 getter 和 setter
}
public class Address {
private Integer id;
private String street;
private String city;
// 省略 getter 和 setter
}
- Mapper 接口:定义
UserMapper和AddressMapper接口。
public interface UserMapper {
User selectById(Integer id);
List<User> selectAll();
int insert(User user);
int update(User user);
int delete(Integer id);
}
public interface AddressMapper {
Address selectById(Integer id);
List<Address> selectAll();
int insert(Address address);
int update(Address address);
int delete(Integer id);
}
- Mapper XML:创建
UserMapper.xml和AddressMapper.xml文件,定义 SQL 映射。
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<!-- ... -->
</mapper>
<!-- AddressMapper.xml -->
<mapper namespace="com.example.mapper.AddressMapper">
<!-- ... -->
</mapper>
- Service 层:定义
UserService和AddressService接口及其实现类。
public interface UserService {
User selectById(Integer id);
List<User> selectAll();
int insert(User user);
int update(User user);
int delete(Integer id);
}
public interface AddressService {
Address selectById(Integer id);
List<Address> selectAll();
int insert(Address address);
int update(Address address);
int delete(Integer id);
}
- Controller 层:定义
UserController和AddressController控制器。
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User getUser(@PathVariable Integer id) {
return userService.selectById(id);
}
// ... 其他方法
}
@Controller
public class AddressController {
@Autowired
private AddressService addressService;
@GetMapping("/address/{id}")
public Address getAddress(@PathVariable Integer id) {
return addressService.selectById(id);
}
// ... 其他方法
}
3.2 商品管理系统
本节将介绍如何使用 MyBatis 实现一个简单的商品管理系统,包括商品添加、查询、修改、删除等功能。
- 实体类:定义
Product实体类。
public class Product {
private Integer id;
private String name;
private Double price;
// 省略 getter 和 setter
}
- Mapper 接口:定义
ProductMapper接口。
public interface ProductMapper {
Product selectById(Integer id);
List<Product> selectAll();
int insert(Product product);
int update(Product product);
int delete(Integer id);
}
- Mapper XML:创建
ProductMapper.xml文件,定义 SQL 映射。
<!-- ProductMapper.xml -->
<mapper namespace="com.example.mapper.ProductMapper">
<!-- ... -->
</mapper>
- Service 层:定义
ProductService接口及其实现类。
public interface ProductService {
Product selectById(Integer id);
List<Product> selectAll();
int insert(Product product);
int update(Product product);
int delete(Integer id);
}
- Controller 层:定义
ProductController控制器。
@Controller
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/product/{id}")
public Product getProduct(@PathVariable Integer id) {
return productService.selectById(id);
}
// ... 其他方法
}
总结
本文详细介绍了 MyBatis 的实战指南和进阶技巧,包括基础入门、动态 SQL、关联查询、批量操作、缓存机制等。同时,还提供了用户管理系统和商品管理系统的实战案例,帮助读者更好地理解和应用 MyBatis。
希望本文能对您学习 MyBatis 帮助很大!
