java模拟hibernate一级缓存示例分享
时间:2023-06-18 08:43:55
纯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;
}
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
spring boot配置ssl实现HTTPS的方法
![](https://img.aspxhome.com/file/2023/2/102002_0s.png)
Android下的POS打印机调用的简单实现
java如何反编译jar包并修改class文件重新打包
![](https://img.aspxhome.com/file/2023/3/81933_0s.jpg)
@Configuration与@Component作为配置类的区别详解
C#中Dynamic和Dictionary性能比较
![](https://img.aspxhome.com/file/2023/1/122661_0s.png)
android实现录屏功能
详解Spring Cloud Gateway基于服务发现的默认路由规则
![](https://img.aspxhome.com/file/2023/0/125260_0s.jpg)
C#中添加窗口的步骤详解
![](https://img.aspxhome.com/file/2023/6/91256_0s.jpg)
Java模拟HTTP Get Post请求 轻松实现校园BBS自动回帖
![](https://img.aspxhome.com/file/2023/3/104013_0s.jpg)
C#使用文件流FileStream和内存流MemoryStream操作底层字节数组byte[]
Android自定义View之圆形进度条式按钮
![](https://img.aspxhome.com/file/2023/7/138127_0s.png)
MyBatis注解式开发映射语句详解
![](https://img.aspxhome.com/file/2023/1/63771_0s.png)
c#实现汉诺塔问题示例
Android UI设计系列之ImageView实现ProgressBar旋转效果(1)
![](https://img.aspxhome.com/file/2023/5/138655_0s.png)
Spring创建Bean的生命周期详析
![](https://img.aspxhome.com/file/2023/8/71178_0s.png)
Java常用数字工具类 数字转汉字(1)
![](https://img.aspxhome.com/file/2023/3/63773_0s.jpg)
Springboot整合pagehelper分页功能
![](https://img.aspxhome.com/file/2023/0/65270_0s.png)
Java 设计模式中的命令模式详情
![](https://img.aspxhome.com/file/2023/3/59683_0s.png)
java按钮控件数组实现计算器界面示例分享
C#计算器编写代码
![](https://img.aspxhome.com/file/2023/5/108635_0s.gif)