本文目录导读:

我来详细介绍Java MyBatis删除操作的实操案例,从基础到进阶。
环境准备
1 数据库表结构
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
email VARCHAR(100),
age INT,
status INT DEFAULT 1,
create_time DATETIME
);
INSERT INTO user (name, email, age, status, create_time) VALUES
('张三', 'zhangsan@example.com', 25, 1, NOW()),
('李四', 'lisi@example.com', 30, 1, NOW()),
('王五', 'wangwu@example.com', 28, 0, NOW());
2 实体类
public class User {
private Integer id;
private String name;
private String email;
private Integer age;
private Integer status;
private Date createTime;
// getter和setter方法(省略)
}
基本删除操作
1 Mapper接口
import org.apache.ibatis.annotations.*;
public interface UserMapper {
// 根据ID删除
@Delete("DELETE FROM user WHERE id = #{id}")
int deleteById(Integer id);
// 根据条件删除
int deleteByCondition(User user);
// 批量删除
int batchDelete(@Param("ids") List<Integer> ids);
// 删除所有
@Delete("DELETE FROM user")
int deleteAll();
}
2 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">
<!-- 根据条件删除 -->
<delete id="deleteByCondition" parameterType="com.example.model.User">
DELETE FROM user
WHERE 1=1
<if test="id != null">
AND id = #{id}
</if>
<if test="name != null and name != ''">
AND name = #{name}
</if>
<if test="email != null and email != ''">
AND email = #{email}
</if>
<if test="status != null">
AND status = #{status}
</if>
</delete>
<!-- 批量删除 -->
<delete id="batchDelete" parameterType="java.util.List">
DELETE FROM user
WHERE id IN
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
</mapper>
高级删除操作
1 逻辑删除
// 逻辑删除接口
@Update("UPDATE user SET status = 0 WHERE id = #{id}")
int logicDeleteById(Integer id);
// 恢复逻辑删除
@Update("UPDATE user SET status = 1 WHERE id = #{id}")
int restoreById(Integer id);
2 级联删除
// 同时删除用户和相关订单
@Delete({
"DELETE FROM user WHERE id = #{userId}",
"DELETE FROM orders WHERE user_id = #{userId}"
})
void cascadeDelete(@Param("userId") Integer userId);
服务层实现
1 Service接口
public interface UserService {
// 根据ID删除
void deleteById(Integer id) throws Exception;
// 批量删除
void batchDelete(List<Integer> ids) throws Exception;
// 条件删除
void deleteByCondition(User user) throws Exception;
}
2 Service实现
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteById(Integer id) throws Exception {
// 检查用户是否存在
User user = userMapper.selectById(id);
if (user == null) {
throw new Exception("用户不存在");
}
// 执行删除
int result = userMapper.deleteById(id);
if (result <= 0) {
throw new Exception("删除失败");
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void batchDelete(List<Integer> ids) throws Exception {
if (ids == null || ids.isEmpty()) {
throw new Exception("删除ID列表不能为空");
}
int result = userMapper.batchDelete(ids);
if (result != ids.size()) {
throw new Exception("部分删除失败,期望删除" + ids.size() + "条,实际删除" + result + "条");
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteByCondition(User user) throws Exception {
int result = userMapper.deleteByCondition(user);
System.out.println("删除了 " + result + " 条记录");
}
}
控制器层实现
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
// 根据ID删除
@DeleteMapping("/{id}")
public Result deleteById(@PathVariable Integer id) {
try {
userService.deleteById(id);
return Result.success("删除成功");
} catch (Exception e) {
return Result.error(e.getMessage());
}
}
// 批量删除
@PostMapping("/batchDelete")
public Result batchDelete(@RequestBody List<Integer> ids) {
try {
userService.batchDelete(ids);
return Result.success("批量删除成功");
} catch (Exception e) {
return Result.error(e.getMessage());
}
}
// 条件删除
@PostMapping("/deleteByCondition")
public Result deleteByCondition(@RequestBody User user) {
try {
userService.deleteByCondition(user);
return Result.success("条件删除成功");
} catch (Exception e) {
return Result.error(e.getMessage());
}
}
}
测试代码
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Arrays;
@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;
@Test
void testDeleteById() {
try {
userService.deleteById(1);
System.out.println("删除成功");
} catch (Exception e) {
System.out.println("删除失败: " + e.getMessage());
}
}
@Test
void testBatchDelete() {
try {
userService.batchDelete(Arrays.asList(1, 2, 3));
System.out.println("批量删除成功");
} catch (Exception e) {
System.out.println("批量删除失败: " + e.getMessage());
}
}
@Test
void testDeleteByCondition() {
try {
User user = new User();
user.setStatus(0); // 删除状态为0的用户
userService.deleteByCondition(user);
} catch (Exception e) {
System.out.println("条件删除失败: " + e.getMessage());
}
}
}
注意事项
1 事务管理
@Configuration
@EnableTransactionManagement
public class MyBatisConfig {
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
2 防止误删
// 添加删除限制
@Delete("DELETE FROM user WHERE id = #{id} AND status = 1")
int deleteActiveUserById(Integer id);
// 批量删除限制
@Delete({
"<script>",
"DELETE FROM user",
"WHERE id IN",
"<foreach collection='ids' item='id' open='(' close=')' separator=','>",
"#{id}",
"</foreach>",
"AND status = 1",
"</script>"
})
int batchDeleteActiveUser(@Param("ids") List<Integer> ids);
3 日志记录
@Aspect
@Component
public class DeleteLogAspect {
@Before("@annotation(org.springframework.web.bind.annotation.DeleteMapping)")
public void logBeforeDelete(JoinPoint joinPoint) {
System.out.println("执行删除操作: " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning("@annotation(org.springframework.web.bind.annotation.DeleteMapping)")
public void logAfterDelete() {
System.out.println("删除操作完成");
}
}
常见问题解决
1 删除失败处理
try {
userService.deleteById(id);
} catch (DataAccessException e) {
// 数据库异常
logger.error("数据库删除异常", e);
return Result.error("数据库异常");
} catch (Exception e) {
// 其他异常
logger.error("删除异常", e);
return Result.error("操作失败");
}
2 性能优化
// 使用批量删除
@Delete("DELETE FROM user WHERE id IN (${ids})")
int batchDeleteByString(@Param("ids") String ids);
// 分页删除
@Delete("DELETE FROM user WHERE id > #{startId} LIMIT #{limit}")
int deleteInBatch(@Param("startId") int startId, @Param("limit") int limit);
是MyBatis删除操作的完整实操案例,涵盖了基本操作、进阶用法和最佳实践,你可以根据实际需求选择合适的方式来实现删除功能。