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;
}
}