Java emulates hibernate level 1 cache example sharing

  • 2020-04-01 03:11:51
  • OfStack

Pure Java code simulates Hibernate level 1 caching principle, simple to understand.


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 caching
 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 the cache ");
   return stus.get(id);
  } else {
   System.out.println(" Fetch data from the database ");
   Student s=MyDB.getStudentById(id);
   //Puts the data retrieved from the database into the cache
   stus.put(id, s);
   return s;
  }
 }
}
//Analog 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);
 }
 //A common query method is provided in the database
 public static Student getStudentById(Integer id){
  for(Student s:list){
   if(s.getId().equals(id)){
    return s;
   }
  }
  //Null is returned if the query fails
  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;
 }
}


Related articles: