Here are several ways to implement a save method for a Repository class using pure Java 8 (without Spring Data JPA or other frameworks):
1. In-Memory Repository (Simple HashMap)
public class InMemoryUserRepository implements UserRepository {
private final Map<Long, User> users = new ConcurrentHashMap<>();
private final AtomicLong idGenerator = new AtomicLong(1);
@Override
public User save(User user) {
if (user.getId() == null) {
// Create new user
Long newId = idGenerator.getAndIncrement();
User newUser = new User(newId, user.getName(), user.getEmail());
users.put(newId, newUser);
return newUser;
} else {
// Update existing user
users.put(user.getId(), user);
return user;
}
}
@Override
public Optional<User> findById(Long id) {
return Optional.ofNullable(users.get(id));
}
@Override
public List<User> findAll() {
return new ArrayList<>(users.values());
}
}
2. File-Based Repository (JSON)
public class FileUserRepository implements UserRepository {
private final String filePath;
private final ObjectMapper objectMapper;
private final AtomicLong idGenerator = new AtomicLong(1);
public FileUserRepository(String filePath) {
this.filePath = filePath;
this.objectMapper = new ObjectMapper();
initializeIdGenerator();
}
@Override
public User save(User user) {
List<User> users = loadAllUsers();
if (user.getId() == null) {
// Create new user
Long newId = idGenerator.getAndIncrement();
User newUser = new User(newId, user.getName(), user.getEmail());
users.add(newUser);
saveAllUsers(users);
return newUser;
} else {
// Update existing user
users = users.stream()
.map(u -> u.getId().equals(user.getId()) ? user : u)
.collect(Collectors.toList());
saveAllUsers(users);
return user;
}
}
private List<User> loadAllUsers() {
try {
File file = new File(filePath);
if (!file.exists()) {
return new ArrayList<>();
}
return objectMapper.readValue(file,
objectMapper.getTypeFactory()
.constructCollectionType(List.class, User.class));
} catch (IOException e) {
throw new RuntimeException("Failed to load users", e);
}
}
private void saveAllUsers(List<User> users) {
try {
objectMapper.writeValue(new File(filePath), users);
} catch (IOException e) {
throw new RuntimeException("Failed to save users", e);
}
}
private void initializeIdGenerator() {
List<User> users = loadAllUsers();
long maxId = users.stream()
.mapToLong(User::getId)
.max()
.orElse(0L);
idGenerator.set(maxId + 1);
}
}
3. JDBC Repository (Raw SQL)
public class JdbcUserRepository implements UserRepository {
private final DataSource dataSource;
public JdbcUserRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public User save(User user) {
if (user.getId() == null) {
return insert(user);
} else {
return update(user);
}
}
private User insert(User user) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, user.getName());
stmt.setString(2, user.getEmail());
int affectedRows = stmt.executeUpdate();
if (affectedRows == 0) {
throw new RuntimeException("Creating user failed, no rows affected.");
}
try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
if (generatedKeys.next()) {
Long id = generatedKeys.getLong(1);
return new User(id, user.getName(), user.getEmail());
} else {
throw new RuntimeException("Creating user failed, no ID obtained.");
}
}
} catch (SQLException e) {
throw new RuntimeException("Failed to insert user", e);
}
}
private User update(User user) {
String sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, user.getName());
stmt.setString(2, user.getEmail());
stmt.setLong(3, user.getId());
int affectedRows = stmt.executeUpdate();
if (affectedRows == 0) {
throw new RuntimeException("User not found with id: " + user.getId());
}
return user;
} catch (SQLException e) {
throw new RuntimeException("Failed to update user", e);
}
}
@Override
public Optional<User> findById(Long id) {
String sql = "SELECT id, name, email FROM users WHERE id = ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setLong(1, id);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return Optional.of(new User(
rs.getLong("id"),
rs.getString("name"),
rs.getString("email")
));
}
return Optional.empty();
}
} catch (SQLException e) {
throw new RuntimeException("Failed to find user", e);
}
}
}
4. Generic Repository Pattern
public abstract class AbstractRepository<T, ID> {
protected final Map<ID, T> storage = new ConcurrentHashMap<>();
public T save(T entity) {
ID id = getId(entity);
if (id == null) {
id = generateId();
entity = setId(entity, id);
}
storage.put(id, entity);
return entity;
}
public Optional<T> findById(ID id) {
return Optional.ofNullable(storage.get(id));
}
public List<T> findAll() {
return new ArrayList<>(storage.values());
}
public void deleteById(ID id) {
storage.remove(id);
}
// Abstract methods to be implemented by concrete repositories
protected abstract ID getId(T entity);
protected abstract T setId(T entity, ID id);
protected abstract ID generateId();
}
// Concrete implementation
public class UserRepository extends AbstractRepository<User, Long> {
private final AtomicLong idGenerator = new AtomicLong(1);
@Override
protected Long getId(User user) {
return user.getId();
}
@Override
protected User setId(User user, Long id) {
return new User(id, user.getName(), user.getEmail());
}
@Override
protected Long generateId() {
return idGenerator.getAndIncrement();
}
}
5. Repository with Result Pattern (No Exceptions)
public class SafeUserRepository implements UserRepository {
private final Map<Long, User> users = new ConcurrentHashMap<>();
private final AtomicLong idGenerator = new AtomicLong(1);
public Result<User> save(User user) {
try {
if (user.getId() == null) {
Long newId = idGenerator.getAndIncrement();
User newUser = new User(newId, user.getName(), user.getEmail());
users.put(newId, newUser);
return Result.success(newUser);
} else {
users.put(user.getId(), user);
return Result.success(user);
}
} catch (Exception e) {
return Result.failure(Error.SAVE_FAILED);
}
}
public Result<User> findById(Long id) {
User user = users.get(id);
return user != null
? Result.success(user)
: Result.failure(Error.USER_NOT_FOUND);
}
}
Usage Example
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User createUser(String name, String email) {
User user = new User(null, name, email);
return userRepository.save(user);
}
public User updateUser(Long id, String name, String email) {
User user = new User(id, name, email);
return userRepository.save(user);
}
}
User Entity Example
public class User {
private final Long id;
private final String name;
private final String email;
public User(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// Getters
public Long getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
// equals, hashCode, toString methods
}
Choose based on your needs:
- In-Memory: Testing, prototyping
- File-Based: Small applications, simple persistence
- JDBC: Production applications with database
- Generic: When you have multiple entities
- Result Pattern: When avoiding exceptions
The JDBC approach is most common for production Java 8 applications without frameworks.