Pure Java Code simulation hibernate first-level caching principle, easy to understand.
Copy Code code 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 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 cache");
return Stus.get (ID);
} else {
SYSTEM.OUT.PRINTLN ("Fetch data from database");
Student S=mydb.getstudentbyid (ID);
Place data obtained 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);
Initializing the database
List.add (S1);
List.add (S2);
List.add (S3);
}
Provides a common query method in the database
public static Student Getstudentbyid (Integer ID) {
for (Student s:list) {
if (S.getid (). Equals (ID)) {
return s;
}
}
Returns empty if the query is not available
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;
}
}