使用hibernate-release-5.2.10.Final开启二级缓存配置
首先要导入所需要的jar包和配置文件分别为hibernate-release-5.2.10.Final包中的required文件夹中的所有jar包和optional文件夹中ehcache文件夹的所有jar包和project文件夹中etc文件夹中的ehcache.xml配置文件和hibernate.cfg.xml配置文件结构图如下:
User.java代码如下:
package demo;
public class User {
private int id;
private String userName;
private String pwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
相对应的映射文件User.hbm.xml文件如下:
ehcache.xml配置如下:
hibernate.cfg.xml配置如下:
TestUtils.java代码如下:
package demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
public class TestUtils {
private static SessionFactory sf;
static {
sf = new Configuration().configure().addClass(User.class).buildSessionFactory();
}
// 先运行此测试因为数据库没有数据
@Test
public void testSave() {
// TODO Auto-generated method stub
Session session = sf.openSession();
session.beginTransaction();
User user = new User();
user.setUserName("张三");
user.setPwd("12342342");
session.save(user);
session.getTransaction().commit();
session.close();
}
// 测试是否有开启二级缓存
@Test
public void testGet() {
// TODO Auto-generated method stub
Session session = sf.openSession();
session.beginTransaction();
User user = session.get(User.class, 1);
System.out.println(user);
session.getTransaction().commit();
session.close();
Session session2 = sf.openSession();
session2.beginTransaction();
user = session2.get(User.class, 1);
System.out.println(user);
session2.getTransaction().commit();
session2.close();
}
}
运行结果: