Java simulation Hibernate-level caching sample sharing _java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.