java模仿hibernate一級緩存示例分享。本站提示廣大學習愛好者:(java模仿hibernate一級緩存示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是java模仿hibernate一級緩存示例分享正文
純Java代碼模仿Hibernate一級緩存道理,簡略易懂。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LevelOneCache {
//這個對象就是用來模仿hibernate一級緩存的
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("從緩存中取數據");
return stus.get(id);
} else {
System.out.println("從數據庫中取數據");
Student s=MyDB.getStudentById(id);
//將從數據庫中獲得的數據放入緩存
stus.put(id, s);
return s;
}
}
}
//模仿數據庫
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);
//初始化數據庫
list.add(s1);
list.add(s2);
list.add(s3);
}
//數據庫中供給公共的查詢辦法
public static Student getStudentById(Integer id){
for(Student s:list){
if(s.getId().equals(id)){
return s;
}
}
//查詢不到則前往空
return null;
}
}
//domain對象
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;
}
}