2026-03-07 05:43:15 +00:00
|
|
|
package com.example.demo.service;
|
|
|
|
|
|
2026-03-08 14:40:30 +00:00
|
|
|
import com.example.demo.exception.ResourceNotFoundException;
|
2026-03-07 05:43:15 +00:00
|
|
|
import com.example.demo.model.User;
|
|
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
|
|
|
|
import java.util.ArrayList;
|
|
|
|
|
import java.util.List;
|
|
|
|
|
import java.util.concurrent.atomic.AtomicLong;
|
|
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
|
|
|
|
@Service
|
|
|
|
|
public class UserService {
|
|
|
|
|
|
|
|
|
|
private final List<User> users = new ArrayList<>();
|
|
|
|
|
private final AtomicLong idGenerator = new AtomicLong(1);
|
|
|
|
|
|
|
|
|
|
public UserService() {
|
|
|
|
|
users.add(new User(idGenerator.getAndIncrement(), "张三", "zhangsan@example.com", 25));
|
|
|
|
|
users.add(new User(idGenerator.getAndIncrement(), "李四", "lisi@example.com", 30));
|
|
|
|
|
users.add(new User(idGenerator.getAndIncrement(), "王五", "wangwu@example.com", 28));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public List<User> findAll() {
|
|
|
|
|
return new ArrayList<>(users);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public User findById(Long id) {
|
|
|
|
|
return users.stream()
|
|
|
|
|
.filter(u -> u.getId().equals(id))
|
|
|
|
|
.findFirst()
|
2026-03-08 14:40:30 +00:00
|
|
|
.orElseThrow(() -> new ResourceNotFoundException("用户不存在: id=" + id));
|
2026-03-07 05:43:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public List<User> findByName(String name) {
|
|
|
|
|
return users.stream()
|
|
|
|
|
.filter(u -> u.getName().contains(name))
|
|
|
|
|
.collect(Collectors.toList());
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-08 14:40:30 +00:00
|
|
|
public User create(User user) {
|
|
|
|
|
user.setId(idGenerator.getAndIncrement());
|
|
|
|
|
users.add(user);
|
|
|
|
|
return user;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public User update(Long id, User user) {
|
|
|
|
|
findById(id);
|
|
|
|
|
user.setId(id);
|
|
|
|
|
for (int i = 0; i < users.size(); i++) {
|
|
|
|
|
if (users.get(i).getId().equals(id)) {
|
|
|
|
|
users.set(i, user);
|
|
|
|
|
return user;
|
2026-03-07 05:43:15 +00:00
|
|
|
}
|
|
|
|
|
}
|
2026-03-08 14:40:30 +00:00
|
|
|
throw new ResourceNotFoundException("用户不存在: id=" + id);
|
2026-03-07 05:43:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void delete(Long id) {
|
2026-03-08 14:40:30 +00:00
|
|
|
boolean removed = users.removeIf(u -> u.getId().equals(id));
|
|
|
|
|
if (!removed) {
|
|
|
|
|
throw new ResourceNotFoundException("用户不存在: id=" + id);
|
|
|
|
|
}
|
2026-03-07 05:43:15 +00:00
|
|
|
}
|
2026-03-08 14:40:30 +00:00
|
|
|
}
|