本文目录导读:

在Java中编写Mapper接口通常是在使用MyBatis或MyBatis-Plus框架时进行的,以下是不同场景下的编写方法:
MyBatis 标准 Mapper 接口
基础结构
import org.apache.ibatis.annotations.*;
public interface UserMapper {
// 查询所有用户
@Select("SELECT * FROM user")
List<User> findAll();
// 根据ID查询
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(@Param("id") Long id);
// 插入用户
@Insert("INSERT INTO user(name, age, email) VALUES(#{name}, #{age}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(User user);
// 更新用户
@Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")
int update(User user);
// 删除用户
@Delete("DELETE FROM user WHERE id = #{id}")
int deleteById(@Param("id") Long id);
}
XML 映射方式
public interface UserMapper {
// 方法定义,SQL写在XML文件中
List<User> findAll();
User findById(@Param("id") Long id);
int insert(User user);
int update(User user);
int deleteById(@Param("id") Long id);
}
对应的 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 * FROM user
</select>
<select id="findById" resultType="com.example.entity.User">
SELECT * FROM user WHERE id = #{id}
</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 name = #{name}, age = #{age}
WHERE id = #{id}
</update>
<delete id="deleteById">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
MyBatis-Plus Mapper 接口
基础使用
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 继承BaseMapper后,自动拥有CRUD方法
// 无需编写基础增删改查
}
自定义方法
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 自定义查询
@Select("SELECT * FROM user WHERE age > #{age}")
List<User> selectByAge(@Param("age") Integer age);
// 使用MyBatis-Plus的Wrapper
default List<User> findActiveUsers() {
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(User::getStatus, 1);
return this.selectList(wrapper);
}
// 分页查询
IPage<User> selectPageVo(IPage<?> page, @Param("age") Integer age);
}
Spring Boot 集成配置
添加依赖(pom.xml)
<!-- MyBatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
<!-- 或者使用纯MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
配置扫描
# application.yml mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.entity # 或 MyBatis-Plus mybatis-plus: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.entity
主类扫描
@SpringBootApplication
@MapperScan("com.example.mapper") // 扫描Mapper接口
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
实战案例
实体类
public class User {
private Long id;
private String name;
private Integer age;
private String email;
private Integer status;
// getter/setter 省略
}
Service 层调用
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
// 使用继承的方法
public List<User> getAll() {
return userMapper.selectList(null);
}
// 使用自定义方法
public List<User> getByAge(Integer age) {
return userMapper.selectByAge(age);
}
// 复杂条件查询
public List<User> searchUsers(String name, Integer minAge) {
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.like(StringUtils.isNotBlank(name), User::getName, name)
.ge(minAge != null, User::getAge, minAge);
return userMapper.selectList(wrapper);
}
}
注意事项
- 命名规范:Mapper接口通常以实体类名+Mapper命名,如
UserMapper - 返回值类型:注意SQL查询结果与Java类型的映射
- 参数传递:
- 单个参数:直接使用
- 多个参数:使用
@Param注解
- 事务管理:在Service层使用
@Transactional - 动态SQL:可以使用MyBatis的
<if>、<where>等标签
最佳实践
// 推荐使用MyBatis-Plus,减少样板代码
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 复杂查询使用自定义XML
List<UserVO> selectUserWithOrders(@Param("userId") Long userId);
// 批量操作
int batchInsert(@Param("list") List<User> list);
// 统计查询
Long countByCondition(@Param("condition") UserQueryCondition condition);
}
选择哪种方式取决于你的项目需求:
- 简单CRUD:推荐MyBatis-Plus
- 复杂查询:可混用注解和XML
- 性能要求高:使用XML编写优化SQL