Hibernate includesTwo levels of Cache:
① The session-level cache is always enabled by default.
② Optional sessionfactory level second-level cache.
The session-levelLevel 1 CacheDevelopers do not need to care about it. By default, it is always valid. When the application saves the Persistent Object and modifies the Persistent object, the session does not immediately flush the change to the database, instead, it is cached in the first-level cache of the current session, unless the program explicitly calls the flush method of the session, or when the program closes the session, these changes will be flushed to the underlying database at a time. Through this cache, the interaction with the database can be reduced, thus improving the database access performance.
Script. SQL:
create table person(id int primary key auto_increment,name varchar(15),age int);insert into person(name,age) values('tom',20);insert into person(name,age) values('sun',23);
Person. Java:
public class Person {private int id;private String name;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
Person. HBM. xml:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
Testhibernatecache. Java:
public class TestHibernateCache {public static void main(String[] args) {Session session=HibernateSessionFactory.getSession();Person person=(Person) session.get(Person.class,1);System.out.println(person.getId()+" "+person.getName()+" "+person.getAge());Person person2=(Person) session.get(Person.class,1);System.out.println(person2.getId()+" "+person2.getName()+" "+person2.getAge());HibernateSessionFactory.closeSession();session=HibernateSessionFactory.getSession();Person person3=(Person) session.get(Person.class,1);System.out.println(person3.getId()+" "+person3.getName()+" "+person3.getAge());}}
Run testsessioncache. Java and the console outputs: