本文目录导读:

在Java中实现数据删除,主要取决于数据存储在哪里(数据库、文件、集合、List等),下面我会分别介绍最常见的几种场景的删除实现方案。
删除数据库中的数据(最常使用)
这是Java后端开发最常见的场景,通常使用JDBC或MyBatis框架。
1 使用原生JDBC
import java.sql.*;
public class DeleteDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "123456";
// 要删除的用户ID
int userId = 10;
String sql = "DELETE FROM users WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, userId); // 设置参数
int rows = pstmt.executeUpdate(); // 执行删除
System.out.println("删除了 " + rows + " 行数据");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2 使用MyBatis(主流方式)
Mapper接口:
public interface UserMapper {
// 根据ID删除
int deleteById(@Param("id") Integer id);
// 根据条件删除
int deleteByCondition(User user);
}
XML映射文件:
<!-- 根据ID删除 -->
<delete id="deleteById" parameterType="int">
DELETE FROM users WHERE id = #{id}
</delete>
<!-- 带条件的删除 -->
<delete id="deleteByCondition" parameterType="User">
DELETE FROM users
WHERE 1=1
<if test="name != null and name != ''">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</delete>
Service层调用:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public boolean deleteUser(Integer id) {
return userMapper.deleteById(id) > 0;
}
}
删除集合/List中的数据(内存数据)
如果数据在内存(如ArrayList)中,使用remove()方法。
1 普通删除(注意并发修改问题)
import java.util.*;
public class ListDeleteDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "B"));
// 方式1:删除指定元素(只删除第一个匹配)
list.remove("B"); // 结果: [A, C, B]
// 方式2:删除所有匹配的元素(使用迭代器,安全)
list.removeIf(s -> s.equals("B")); // 结果: [A, C]
// 方式3:根据索引删除
list.remove(0); // 删除索引0的元素
System.out.println(list);
}
}
2 遍历时删除(避免ConcurrentModificationException)
// ✅ 正确方式:使用迭代器的remove()
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if ("B".equals(item)) {
iterator.remove(); // 安全删除
}
}
// ❌ 错误方式:遍历时直接调用list.remove()会异常
// for (String s : list) {
// if ("B".equals(s)) {
// list.remove(s); // 抛出ConcurrentModificationException
// }
// }
删除文件中的数据
1 删除文件本身
import java.io.File;
public class FileDeleteDemo {
public static void main(String[] args) {
File file = new File("C:/data/user.txt");
if (file.exists()) {
if (file.delete()) {
System.out.println("文件删除成功");
} else {
System.out.println("文件删除失败");
}
} else {
System.out.println("文件不存在");
}
}
}
2 删除文件中的某一行内容
import java.io.*;
import java.util.*;
public class DeleteLineFromFile {
public static void main(String[] args) throws IOException {
String filePath = "data.txt";
String targetLine = "要删除的行内容";
// 1. 读取所有行到List
List<String> lines = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
if (!line.equals(targetLine)) { // 跳过要删除的行
lines.add(line);
}
}
reader.close();
// 2. 重新写入文件(覆盖)
BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
for (String l : lines) {
writer.write(l);
writer.newLine();
}
writer.close();
}
}
删除Redis中的数据(缓存删除)
import redis.clients.jedis.Jedis;
public class RedisDeleteDemo {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost", 6379);
// 删除单个key
jedis.del("user:1001");
// 删除多个key
jedis.del("key1", "key2", "key3");
// 根据通配符删除(需要配合 scan)
Set<String> keys = jedis.keys("user:*");
for (String key : keys) {
jedis.del(key);
}
jedis.close();
}
}
软删除 vs 硬删除(重要概念)
在实际项目中,通常不直接物理删除数据,而是使用软删除:
// 软删除:逻辑删除,数据还在但标记为已删除
public class User {
private Integer id;
private String name;
private Integer deleted; // 0-未删除,1-已删除
}
// 软删除操作(实际是UPDATE)
@Update("UPDATE users SET deleted = 1 WHERE id = #{id}")
int softDeleteById(Integer id);
软删除的优点:
- 数据可恢复
- 保留历史记录
- 避免主键冲突
选择哪种删除方式?
| 场景 | 推荐方式 |
|---|---|
| 关系型数据库(MySQL/Oracle) | MyBatis/JPA 的 DELETE 语句 |
| 内存集合(List/Map) | remove(), removeIf() |
| 文件系统 | File.delete() 或重写文件内容 |
| 缓存(Redis) | del 命令 |
| 需要恢复/审计 | 软删除(UPDATE状态字段) |
如需具体场景的实现代码,可以告诉我你的数据存储方式,我可以给出更精确的示例。