-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStudentManager.java
More file actions
58 lines (49 loc) · 1.66 KB
/
StudentManager.java
File metadata and controls
58 lines (49 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.yourssu.controller;
import com.yourssu.model.Student;
import java.util.HashMap;
import java.util.Map;
public class StudentManager implements EntityManager{
private final Map<Long, Student> studentCache;
private final Map<Long, Student> studentDB;
private final Map<Long, Boolean> flushFlag;
public StudentManager(Map<Long, Student> studentDB) {
studentCache = new HashMap<>();
flushFlag = new HashMap<>();
this.studentDB = studentDB;
}
@Override
public void persist(Student entity) {
if (!studentCache.containsKey(entity.getId())) {
studentCache.put(entity.getId(), entity);
flushFlag.put(entity.getId(), false);
}
}
@Override
public Student merge(Student entity) {
// cache nonempty
if (studentCache.get(entity.getId()) != null) {
Student cachedStudent = studentCache.get(entity.getId());
flushFlag.put(entity.getId(), false);
return cachedStudent;
}
// cache is empty
if (studentDB.get(entity.getId()) != null) {
Student dbStudent = studentDB.get(entity.getId());
studentCache.put(entity.getId(), dbStudent);
flushFlag.put(entity.getId(), false);
return dbStudent;
}
persist(entity);
return new Student(entity);
}
@Override
public void flush() {
for (Student student : studentCache.values()) {
if (flushFlag.get(student.getId())) {
continue;
}
studentDB.put(student.getId(), student);
flushFlag.put(student.getId(), true);
}
}
}