<?xml version="1.0" encoding="GBK"?> <project name="hibernate" basedir="." default=""> <property name="src" value="src"/> <property name="dest" value="classes"/> <path id="classpath"> <fileset dir="../../lib"> <include name="**/*.jar"/> </fileset> <pathelement path="${dest}"/> </path> <target name="compile" description="Compile all source code"> <delete dir="${dest}"/> <mkdir dir="${dest}"/> <copy todir="${dest}"> <fileset dir="${src}"> <exclude name="**/*.java"/> </fileset> </copy> <javac destdir="${dest}" debug="true" includeantruntime="yes" deprecation="false" optimize="false" failonerror="true"> <src path="${src}"/> <classpath refid="classpath"/> <compilerarg value="-Xlint:deprecation"/> </javac> </target> <target name="run" description="Run the main class" depends="compile"> <java classname="lee.NewsManager" fork="yes" failonerror="true"> <classpath refid="classpath"/> </java> </target> </project>
<?xml version="1.0" encoding="GBK"?> <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120" diskPersistent="false"/> </ehcache>
<?xml version="1.0" encoding="GBK"?> <!-- 指定Hibernate配置文件的DTD信息 --> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- hibernate-configuration是配置文件的根元素 --> <hibernate-configuration> <session-factory> <!-- 指定连接数据库所用的驱动 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 --> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property> <!-- 指定连接数据库的用户名 --> <property name="connection.username">root</property> <!-- 指定连接数据库的密码 --> <property name="connection.password">32147</property> <!-- 指定数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- 根据需要自动创建数据库 --> <property name="hbm2ddl.auto">update</property> <!-- 指定连接池里最大连接数 --> <property name="hibernate.c3p0.max_size">20</property> <!-- 指定连接池里最小连接数 --> <property name="hibernate.c3p0.min_size">1</property> <!-- 指定连接池里连接的超时时长 --> <property name="hibernate.c3p0.timeout">5000</property> <!-- 指定连接池里最大缓存多少个Statement对象 --> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <property name="hibernate.c3p0.acquire_increment">2</property> <property name="hibernate.c3p0.validate">true</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <!-- 开启二级缓存 --> <property name="hibernate.cache.use_second_level_cache">true</property> <!-- 设置缓存提供者 --> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <!-- 开启二级缓存的统计功能 --> <property name="hibernate.generate_statistics">true</property> <!-- 设置使用结构化方式来维护缓存项 --> <property name="hibernate.cache.use_structured_entries">true</property> <!-- 启用查询缓存 --> <property name="hibernate.cache.use_query_cache">true</property> <!-- 指定根据当前线程来界定上下文相关Session --> <property name="hibernate.current_session_context_class">thread</property> <!-- 罗列所有持久化类的类名 --> <mapping class="org.crazyit.app.domain.News"/> </session-factory> </hibernate-configuration>
package lee; import org.hibernate.*; import org.hibernate.cfg.*; import org.hibernate.service.*; import org.hibernate.boot.registry.*; import java.util.*; import org.crazyit.app.domain.*; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class NewsManager { static Configuration conf = new Configuration() .configure(); // 以Configuration实例创建SessionFactory实例 static ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(conf.getProperties()).build(); static SessionFactory sf = conf.buildSessionFactory(serviceRegistry); public static void main(String[] args) throws Exception { NewsManager mgr = new NewsManager(); mgr.cacheQuery(); mgr.stat(); } private void noCacheQuery() { Session session = sf.getCurrentSession(); session.beginTransaction(); List titles = session.createQuery("select news.title from News news") // 其实无需设置,默认就是关闭缓存的。 .setCacheable(false) .list(); for(Object title : titles) { System.out.println(title); } System.out.println("-------------------------"); // 第二次查询,因为没有使用查询缓存,因此会重新发出SQL语句进行查询 titles = session.createQuery("select news.title from News news") // 其实无需设置,默认就是关闭缓存的。 .setCacheable(false) .list(); for(Object title : titles) { System.out.println(title); } session.getTransaction().commit(); } private void cacheQuery() { Session session = sf.getCurrentSession(); session.beginTransaction(); List titles = session.createQuery("select news.title from News news") // 开启查询缓存 .setCacheable(true) .list(); for(Object title : titles) { System.out.println(title); } session.getTransaction().commit(); System.out.println("-------------------------"); Session sess2 = sf.getCurrentSession(); sess2.beginTransaction(); // 第二次查询,使用查询缓存,因此不会重新发出SQL语句进行查询 titles = sess2.createQuery("select news.title from News news") // 开启查询缓存 .setCacheable(true) .list(); for(Object title : titles) { System.out.println(title); } sess2.getTransaction().commit(); } // 开启查询缓存,但使用iterate()方法查询,因此也不能缓存 public static void cacheQueryIterator() { Session session = sf.getCurrentSession(); session.beginTransaction(); Iterator it = session.createQuery("select news.title from News news") // 开启查询缓存 .setCacheable(true) .iterate(); while(it.hasNext()) { System.out.println(it.next()); } session.getTransaction().commit(); System.out.println("-------------------------"); Session sess2 = sf.getCurrentSession(); sess2.beginTransaction(); // 第二次查询,虽然使用了查询缓存,但由于使用iterate()获取查询结果, // 因此无法利用查询缓存。 it = sess2.createQuery("select news.title from News news") // 开启查询缓存 .setCacheable(true) .iterate(); while(it.hasNext()) { System.out.println(it.next()); } sess2.getTransaction().commit(); } private void stat() { //----------统计查询缓存---------- long hitCount = sf.getStatistics() //查询缓存的名字与HQL语句或SQL语句相同 .getQueryStatistics("select news.title from News news") .getCacheHitCount(); System.out.println("查询缓存命中的次数:" + hitCount); } }
package org.crazyit.app.domain; import javax.persistence.*; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ @Entity @Table(name="news_inf") @Cache(usage=CacheConcurrencyStrategy.READ_ONLY) public class News { // 消息类的标识属性 @Id @Column(name="news_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String title; private String content; // 无参数的构造器 public News() { } // 初始化全部成员变量的构造器 public News(Integer id , String title , String content) { this.id = id; this.title = title; this.content = content; } // id的setter和getter方法 public void setId(Integer id) { this.id = id; } public Integer getId() { return this.id; } // title的setter和getter方法 public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } // content的setter和getter方法 public void setContent(String content) { this.content = content; } public String getContent() { return this.content; } }