Hibernate二级缓存

来源:互联网 发布:支持绑定第三方域名 编辑:程序博客网 时间:2024/06/05 05:20

使用Java工程实现一个Hibernate二级缓存,使用Ehcache方法,工程目录如图


首先新建一个pojo

package com.hibernate.pojo;


import java.io.Serializable;
import java.util.Date;


public class User implements Serializable{
/**

*/
private static final long serialVersionUID = 1L;


private String id;


private String name;


private String password;


private Date createTime;


private Date expireTime;


public String getId() {
return id;
}


public void setId(String id) {
this.id = id;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getPassword() {
return password;
}


public void setPassword(String password) {
this.password = password;
}


public Date getCreateTime() {
return createTime;
}


public void setCreateTime(Date createTime) {
this.createTime = createTime;
}


public Date getExpireTime() {
return expireTime;
}


public void setExpireTime(Date expireTime) {
this.expireTime = expireTime;
}


}

然后建立对应的User.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">  
<hibernate-mapping package="com.hibernate.pojo"> <!--  所在的包 --> 
    <class name="User" table="user">  
        <id name="id">  
            <generator class="native"/> <!-- 自增 --> 
        </id>  
        <property name="name"/>  
        <property name="password"/>  
        <property name="createTime"/>  
        <property name="expireTime"/>  
    </class>  
</hibernate-mapping> 

新建dao借口,并且实现

package com.hibernate.dao;


import java.util.List;


import com.hibernate.pojo.User;
import com.page.ben.Pager;




public interface UserDao {
public void saveUser(User user);


public User findUserByName(String name);


public User findUserById(String name);


public void updateUser(User user);


public void remove(User user);

public long geCount();

public List<User> findByPage(Pager page);
}

package com.hibernate.dao;


import java.util.List;


import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;


import com.hibernate.pojo.User;
import com.hibernate.utils.HibernateUtil;
import com.page.ben.Pager;


public class UserDaoImpl implements UserDao{
private Session s = null;  
private Transaction tx = null;  


@Override
public void saveUser(User user) {
 
       try{  
           s = HibernateUtil.getSession();  
           tx = s.beginTransaction();  
           s.save(user);  
           tx.commit();  
       }catch(HibernateException e){
        tx.rollback();
       }finally{  
           if(s!=null){  
               s.close();  
           }  
       }  

}


@Override
public User findUserByName(String name) { 
User user = null;
String sql="from User where name=?";
       try{  
           s = HibernateUtil.getSession(); 
           tx = s.beginTransaction();           
           Query query = s.createQuery(sql);
           query.setString(0, name);
           query.setCacheable(true);
           user = (User)query.uniqueResult();
           query = null;
           tx.commit ();
       }catch(HibernateException e){
        tx.rollback();
       }finally{  
           if(s!=null){  
               s.close();  
           }  
       }  
       return user;
}


@Override
public User findUserById(String name) {
User user = null;
String sql="from User where name=?";
       try{  
           s = HibernateUtil.getSession(); 
           tx = s.beginTransaction();           
           Query query = s.createQuery(sql);
           query.setString(0, name);
           query.setCacheable(true);
           user = (User)query.uniqueResult();
           tx.commit ();
       }catch(HibernateException e){
        tx.rollback();
       }finally{  
           if(s!=null){  
               s.close();  
           }  
       }  
       return user;
}


@Override
public void updateUser(User user) {
String sql="update User set password=? where name=?";
try{  
           s = HibernateUtil.getSession(); 
           tx = s.beginTransaction();           
           Query query = s.createQuery(sql);
           query.setString(0, user.getPassword());
           query.setString(1, user.getName());
           query.executeUpdate();
           tx.commit ();
       }catch(HibernateException e){
        tx.rollback();
       }finally{  
           if(s!=null){  
               s.close();  
           }  
       }  

}


@Override
public void remove(User user) {
String sql="delete from User  where name=?";
try{  
           s = HibernateUtil.getSession(); 
           tx = s.beginTransaction();             
           Query query = s.createQuery(sql);
           query.setString(0, user.getName());
           query.executeUpdate();
           tx.commit ();
       }catch(HibernateException e){
        tx.rollback();
       }finally{  
           if(s!=null){  
               s.close();  
           }  
       }  

}


@Override
public long geCount(){
long count=0;
String sql="select count(*) from User";
try{  
           s = HibernateUtil.getSession(); 
           tx = s.beginTransaction();           
           Query query = s.createQuery(sql);
           count= (long) query.uniqueResult();
           tx.commit ();
       }catch(HibernateException e){
        tx.rollback();
       }finally{  
           if(s!=null){  
               s.close();  
           }  
       }  
return count;
}


@Override
public List<User> findByPage(Pager page) {
List<User> list=null;
StringBuffer buf = new StringBuffer("from User order by id desc");
String sql=buf.toString();
System.out.println(sql);
try{  
System.out.println("---------");
           s = HibernateUtil.getSession(); 
           tx = s.beginTransaction();           
           Query query = s.createQuery(sql);
           query.setFirstResult((page.getPageNo()-1)*page.getPageSize());
query.setMaxResults(page.getPageSize());
query.setCacheable(true);
           list= query.list();
           query=null;
           tx.commit ();
       }catch(HibernateException e){
        tx.rollback();
       }finally{  
           if(s!=null){  
               s.close();  
           }  
       }  
System.out.println("---------"+list.size());
return list;
}


}


然后写一个通用类用来读Hibernate的文件类

package com.hibernate.utils;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class HibernateUtil {
private static SessionFactory sessionFactory;
/**
* 主要为了获得session
* @return
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/*getsession方法*/
public static Session getSession(){  
       return sessionFactory.openSession();  
   }  
private HibernateUtil(){

}
static{
/*加载配置文件*/
Configuration configuration=new Configuration();
configuration.configure();
sessionFactory =configuration.buildSessionFactory();

}
}

在src先放入配置文件hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>


<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://127.0.0.1:3306/hibernate
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">Test</property>


<property name="hbm2ddl.auto">update</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="show_sql">true</property>
<property name="defaultAutoCommit">true</property>
<property name="maxActive">10000</property>
<property name="maxIdle">50</property>
<property name="maxWait">3000</property>
<property name="initialSize">10</property>
<property name="minIdle">20</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>


<!-- 配置二级缓存提供商,注意此处并不是缓存的jar包 -->
<!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>


<!-- 把user.hbm.xml这个映射文件引入进来。 -->
<mapping resource="com/hibernate/pojo/User.hbm.xml" />
</session-factory>




</hibernate-configuration>

同时还有缓存配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">  
      
    <!-- 如果缓存内存溢出,则存储到硬盘空间 -->  
    <diskStore path="java.io.path"/>  
    <!-- 内存支持的最大对象的数量 --> 
    <!-- 对象是否永久生效,建议为false,这样下面的两个参数才会有效 -->  
    <!-- 对象的间隔周期,默认单位为秒。即60秒后如果还没人用这个对象,会提前销毁 -->  
     <!-- 对象的生命周期,默认单位为秒 -->  
     <!-- 是否支持溢出到硬盘,建议为true -->  
     <!-- 硬盘上支持的最大对象的数量 -->  
     <!-- 对象的替换策略 -->  
      <defaultCache  
                        
        maxElementsInMemory="10000"   
        eternal="false"     
        timeToIdleSeconds="2" 
        timeToLiveSeconds="3"
        overflowToDisk="true"   
        maxElementsOnDisk="10000000" 
        memoryStoreEvictionPolicy="LRU" 
       />       
</ehcache>  

写一个测试类

package com.hibernate.test;


import java.util.Date;
import java.util.List;


import com.hibernate.dao.UserDao;
import com.hibernate.dao.UserDaoImpl;
import com.hibernate.pojo.User;
import com.page.ben.Pager;
import com.page.service.PageService;
import com.page.service.impl.PageServiceImpl;


public class Test {
private static String pagerMethod;
private static Pager page;
private static int currentPage = 1;


public static String getPagerMethod() {
return pagerMethod;
}
public static void setPagerMethod(String pagerMethod) {
Test.pagerMethod = pagerMethod;
}
public static Pager getPage() {
return page;
}
public static void setPage(Pager page) {
Test.page = page;
}
public static int getCurrentPage() {
return currentPage;
}
public static void setCurrentPage(int currentPage) {
Test.currentPage = currentPage;
}
private static UserDao dao = new UserDaoImpl();  


public static void main(String[] args) {  
       for(int i=0;i<50;i++){
        User user = new User();  
        user.setName("admin"+i);  
        user.setPassword("123");  
        user.setCreateTime(new Date());  
        user.setExpireTime(new Date());
//        dao.saveUser(user);  
       }


        User user3 = new User();  
        user3.setName("用户名");  
        user3.setPassword("456");  
//        dao.updateUser(user3);
//        dao.remove(user3);
//        System.out.println(dao.geCount());
//      分页测试 
        String inpage="1";
          String inmeth=null;
//        String inmeth="first";//首页
//        String inmeth="forward";//下一页
//          String inmeth="backward";//上一页
//        String inmeth="last";//末页


        PageServiceImpl pageServiceImpl=new PageServiceImpl();
        if(inpage==null){
currentPage=1;
}else {
currentPage=Integer.valueOf(inpage);  
}
pagerMethod = inmeth;  
int rows = 0;
rows = (int)dao.geCount();
page = new Pager(5, rows);
// System.out.println("首页"+page.getFirstPageNo());
// System.out.println("末页"+page.getLastPageNo());
// System.out.println("下一页"+page.getNextPageNo());
// System.out.println("页数"+page.getPageCount());
// System.out.println("当前页"+page.getPageNo());
// System.out.println("每页显示数"+page.getPageSize());
// System.out.println("上一页"+page.getPrePageNo());
// System.out.println("行数"+page.getRowCount());
//
page = pageServiceImpl.getPagerByMethodName(page,pagerMethod, currentPage, rows);
System.out.println("---------------------");
System.out.println("首页"+page.getFirstPageNo());
System.out.println("末页"+page.getLastPageNo());
System.out.println("下一页"+page.getNextPageNo());
System.out.println("页数"+page.getPageCount());
System.out.println("当前页"+page.getPageNo());
System.out.println("每页显示数"+page.getPageSize());
System.out.println("上一页"+page.getPrePageNo());
System.out.println("行数"+page.getRowCount());
List<User> list = dao.findByPage(page);
System.out.println("======================");
for (User user : list) {
System.out.println(user.getId()+"  "+user.getName());
}
System.out.println("总记录数"+rows);
System.out.println("总页数"+page.getPageCount());
System.out.println("每页行数"+page.getPageSize());
System.out.println("当前页"+currentPage);

List<User> lists = dao.findByPage(page);
for (User user : list) {
System.out.println(user.getId()+"  "+user.getName());
}
   //缓存测试
        User user2=dao.findUserByName("admin0");
        System.out.println(user2.getPassword()+"  "+user2.getCreateTime());
        User user4=dao.findUserById("admin0");
        System.out.println(user4.getPassword()+"  "+user4.getCreateTime());
        try {
Thread.sleep(2001);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        long a=System.currentTimeMillis();
        User user5=dao.findUserById("admin0");
        System.out.println(System.currentTimeMillis()-a);
        System.out.println(user5.getPassword()+"  "+user5.getCreateTime());
        
        
        long b=System.currentTimeMillis();
        User user6=dao.findUserById("admin0");
        System.out.println(System.currentTimeMillis()-b);
        System.out.println(user6.getPassword()+"  "+user6.getCreateTime());
}


}

其中工程中用到了分页的一个自己封装jar包,实现可以看另一篇博客

http://blog.csdn.net/wang_shuyu/article/details/53675928


0 0
原创粉丝点击