Pure Java code simulates Hibernate level 1 cache principle, which is simple and easy to understand.
The code copy is as follows:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LevelOneCache {
//This object is used to simulate hibernate level 1 cache
private static Map<Integer, Student> stus=new HashMap<Integer, Student>();
public static void main(String[] args) {
getStudent(1);
getStudent(1);
getStudent(1);
getStudent(2);
getStudent(2);
}
public static Student getStudent(Integer id){
if(stus.containsKey(id)){
System.out.println("Fetch data from cache");
return stus.get(id);
} else {
System.out.println("Fetch data from database");
Student s=MyDB.getStudentById(id);
//Put the data obtained from the database into the cache
stus.put(id, s);
return s;
}
}
}
//Simulate database
class MyDB{
private static List<Student> list=new ArrayList<Student>();
static{
Student s1=new Student();
s1.setName("Name1");
s1.setId(1);
Student s2=new Student();
s2.setName("Name2");
s2.setId(2);
Student s3=new Student();
s3.setName("Name3");
s3.setId(3);
//Initialize the database
list.add(s1);
list.add(s2);
list.add(s3);
}
//Providing public query methods in the database
public static Student getStudentById(Integer id){
for(Student s:list){
if(s.getId().equals(id)){
return s;
}
}
//If the query cannot be found, the return empty
return null;
}
}
//domain object
class Student{
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}