Here are several ways to implement a save method for a Repository class using pure Java 8 (no frameworks):
1. Simple In-Memory Repository with HashMap
public class UserRepository {
private final Map<Long, User> storage = new ConcurrentHashMap<>();
private final AtomicLong idGenerator = new AtomicLong(1);
public User save(User user) {
if (user.getId() == null) {
// New entity - generate ID
user.setId(idGenerator.getAndIncrement());
}
storage.put(user.getId(), user);
return user;
}
public Optional<User> findById(Long id) {
return Optional.ofNullable(storage.get(id));
}
public List<User> findAll() {
return new ArrayList<>(storage.values());
}
}
2. Immutable Entity Approach
If your entities are immutable, you need to return a new instance:
public class User {
private final Long id;
private final String name;
private final String email;
// Constructor, getters only (no setters)
public User withId(Long id) {
return new User(id, this.name, this.email);
}
}
public class UserRepository {
private final Map<Long, User> storage = new ConcurrentHashMap<>();
private final AtomicLong idGenerator = new AtomicLong(1);
public User save(User user) {
User toSave = user.getId() == null
? user.withId(idGenerator.getAndIncrement())
: user;
storage.put(toSave.getId(), toSave);
return toSave;
}
}
3. Generic Repository with Type Safety
public interface Entity<ID> {
ID getId();
void setId(ID id);
}
public class User implements Entity<Long> {
private Long id;
private String name;
// getters and setters
}
public class InMemoryRepository<T extends Entity<ID>, ID> {
private final Map<ID, T> storage = new ConcurrentHashMap<>();
private final Function<T, ID> idGenerator;
public InMemoryRepository(Function<T, ID> idGenerator) {
this.idGenerator = idGenerator;
}
public T save(T entity) {
if (entity.getId() == null) {
entity.setId(idGenerator.apply(entity));
}
storage.put(entity.getId(), entity);
return entity;
}
public Optional<T> findById(ID id) {
return Optional.ofNullable(storage.get(id));
}
}
// Usage
InMemoryRepository<User, Long> userRepo =
new InMemoryRepository<>(user -> System.currentTimeMillis());
4. File-Based Persistence (Simple JSON)
public class FileBasedUserRepository {
private final Path filePath;
private final ObjectMapper mapper = new ObjectMapper();
private final Map<Long, User> cache = new ConcurrentHashMap<>();
private final AtomicLong idGenerator;
public FileBasedUserRepository(String fileName) {
this.filePath = Paths.get(fileName);
loadFromFile();
this.idGenerator = new AtomicLong(
cache.keySet().stream()
.mapToLong(Long::longValue)
.max()
.orElse(0) + 1
);
}
public synchronized User save(User user) {
if (user.getId() == null) {
user.setId(idGenerator.getAndIncrement());
}
cache.put(user.getId(), user);
persistToFile();
return user;
}
private void persistToFile() {
try {
List<User> users = new ArrayList<>(cache.values());
String json = mapper.writeValueAsString(users);
Files.write(filePath, json.getBytes(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
throw new RuntimeException("Failed to save to file", e);
}
}
private void loadFromFile() {
if (Files.exists(filePath)) {
try {
String json = new String(Files.readAllBytes(filePath));
List<User> users = mapper.readValue(json,
new TypeReference<List<User>>() {});
users.forEach(user -> cache.put(user.getId(), user));
} catch (IOException e) {
// Log error, start with empty cache
}
}
}
}
5. Event Sourcing Style
public class EventSourcedRepository<T extends Entity<Long>> {
private final List<Event<T>> events = new CopyOnWriteArrayList<>();
private final AtomicLong idGenerator = new AtomicLong(1);
public T save(T entity) {
if (entity.getId() == null) {
entity.setId(idGenerator.getAndIncrement());
events.add(new CreatedEvent<>(entity, Instant.now()));
} else {
events.add(new UpdatedEvent<>(entity, Instant.now()));
}
return entity;
}
public Optional<T> findById(Long id) {
return events.stream()
.filter(e -> e.getEntity().getId().equals(id))
.reduce((first, second) -> second) // Get latest
.map(Event::getEntity);
}
public List<T> findAll() {
return events.stream()
.collect(Collectors.toMap(
e -> e.getEntity().getId(),
Event::getEntity,
(oldVal, newVal) -> newVal // Keep latest
))
.values()
.stream()
.collect(Collectors.toList());
}
}
abstract class Event<T> {
private final T entity;
private final Instant timestamp;
// Constructor, getters
}
6. With Validation and Hooks
public class ValidatingRepository<T extends Entity<Long>> {
private final Map<Long, T> storage = new ConcurrentHashMap<>();
private final AtomicLong idGenerator = new AtomicLong(1);
private final List<Validator<T>> validators = new ArrayList<>();
private final List<Consumer<T>> preSaveHooks = new ArrayList<>();
private final List<Consumer<T>> postSaveHooks = new ArrayList<>();
public T save(T entity) {
// Validate
validators.forEach(validator -> validator.validate(entity));
// Pre-save hooks
preSaveHooks.forEach(hook -> hook.accept(entity));
// Save
if (entity.getId() == null) {
entity.setId(idGenerator.getAndIncrement());
}
storage.put(entity.getId(), entity);
// Post-save hooks
postSaveHooks.forEach(hook -> hook.accept(entity));
return entity;
}
public ValidatingRepository<T> addValidator(Validator<T> validator) {
validators.add(validator);
return this;
}
public ValidatingRepository<T> addPreSaveHook(Consumer<T> hook) {
preSaveHooks.add(hook);
return this;
}
}
@FunctionalInterface
interface Validator<T> {
void validate(T entity) throws ValidationException;
}
Usage Example:
ValidatingRepository<User> userRepo = new ValidatingRepository<User>()
.addValidator(user -> {
if (user.getEmail() == null || !user.getEmail().contains("@")) {
throw new ValidationException("Invalid email");
}
})
.addPreSaveHook(user -> user.setUpdatedAt(Instant.now()));
The most common approach for simple applications is Option 1 (ConcurrentHashMap). For production applications without a database, Option 4 (file-based) provides persistence. Choose based on your specific requirements for thread safety, persistence, and complexity.