当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Java的Hibernate框架中的缓存与原生SQL语句的使用

详解Java的Hibernate框架中的缓存与原生SQL语句的使用

2019年07月22日  | 移动技术网IT编程  | 我要评论

hibernate缓存
缓存是所有关于应用程序的性能优化和它位于应用程序和数据库之间,以避免数据库访问多次,让性能关键型应用程序有更好的表现。

缓存对hibernate很重要,它采用了多级缓存方案下文所述:

2015122384816664.jpg (476×363)

第一级缓存:
第一级缓存是session的缓存,是一个强制性的缓存,通过它所有的请求都必须通过。 session对象不断自身的动力的对象,提交到数据库之前。

如果发出多个更新一个对象,hibernate试图拖延尽可能长的时间做了更新,以减少发出的更新sql语句的数量。如果您关闭会话,所有被缓存的对象都将丢失,要么持久,或在数据库中更新。

二级缓存:
二级缓存是可选的缓存和一级缓存,总是会征询任何试图找到一个对象的二级缓存之前。第二级缓存可以在每个类和每个集合基础上进行配置,主要负责在会话缓存的对象。

任何第三方缓存可以使用hibernate。org.hibernate.cache.cacheprovider接口提供,必须实施提供hibernate一个句柄缓存实现。

查询级别缓存:
hibernate也实现了查询结果集缓存与二级缓存的紧密集成在一起。

这是一个可选功能,需要两个额外的物理缓存中保存缓存的查询结果和地区当一个表的最后更新的时间戳。这只是针对那些使用相同的参数经常运行的查询非常有用。

二级缓存:
hibernate使用一级缓存,默认情况下,你什么都没有做使用第一级缓存。让我们直接进入可选的第二级缓存。并不是所有的类受益于缓存,这样一来就能禁用二级缓存是很重要的

hibernate二级缓存被设置为两个步骤。首先,必须决定要使用的并发策略。在此之后,可以配置缓存过期和使用缓存提供物理缓存属性。

并发策略:
并发策略是一个中介的负责存储数据项在缓存并从缓存中检索它们。如果要启用二级缓存,将必须决定,为每个持久化类和集合,要使用的缓存并发策略。

transactional: 使用这种策略的主要读取数据的地方,以防止过时的数据的并发事务,在更新的罕见情况下是至关重要的。

read-write: 再次使用这种策略的主要读取数据的地方,以防止并发事务陈旧的数据是至关重要的,在更新的罕见情况。

nonstrict-read-write: 这种策略不保证缓存与数据库之间的一致性。使用此策略,如果数据很少改变和陈旧数据的可能性很小关键是不关注。

read-only: 并发策略适用于数据,永远不会改变。使用数据仅供参考。

如果我们要使用第二级缓存为我们的employee类,让我们添加告诉hibernate使用可读写的高速缓存策略employee实例所需的映射元素。

<?xml version="1.0" encoding="utf-8"?>
<!doctype hibernate-mapping public 
 "-//hibernate/hibernate mapping dtd//en"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
  <class name="employee" table="employee">
   <meta attribute="class-description">
     this class contains the employee detail. 
   </meta>
   <cache usage="read-write"/>
   <id name="id" type="int" column="id">
     <generator class="native"/>
   </id>
   <property name="firstname" column="first_name" type="string"/>
   <property name="lastname" column="last_name" type="string"/>
   <property name="salary" column="salary" type="int"/>
  </class>
</hibernate-mapping>

 usage="read-write" 属性告诉hibernate使用一个可读写的并发策略定义的缓存。

缓存提供者:
考虑到会用你的缓存候选类的并发策略后,下一步就是选择一个缓存提供程序。hibernate迫使选择一个缓存提供整个应用程序。

2015122384847796.png (652×514)

在指定hibernate.cfg.xml配置文件中的缓存提供。选择ehcache作为第二级缓存提供程序:

<?xml version="1.0" encoding="utf-8"?>
<!doctype hibernate-configuration system 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
  <property name="hibernate.dialect">
   org.hibernate.dialect.mysqldialect
  </property>
  <property name="hibernate.connection.driver_class">
   com.mysql.jdbc.driver
  </property>

  <!-- assume students is the database name -->
  <property name="hibernate.connection.url">
   jdbc:mysql://localhost/test
  </property>
  <property name="hibernate.connection.username">
   root
  </property>
  <property name="hibernate.connection.password">
   root123
  </property>
  <property name="hibernate.cache.provider_class">
   org.hibernate.cache.ehcacheprovider
  </property>

  <!-- list of xml mapping files -->
  <mapping resource="employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>

现在,需要指定缓存区域的属性。ehcache都有自己的配置文件ehcache.xml,在应用程序在classpath中。在ehcache.xml中employee类高速缓存配置可能看起来像这样:

<diskstore path="java.io.tmpdir"/>
<defaultcache
maxelementsinmemory="1000"
eternal="false"
timetoidleseconds="120"
timetoliveseconds="120"
overflowtodisk="true"
/>

<cache name="employee"
maxelementsinmemory="500"
eternal="true"
timetoidleseconds="0"
timetoliveseconds="0"
overflowtodisk="false"
/>

就这样,现在启用employee类的二级缓存和hibernate现在二级缓存,每当浏览到一个雇员或当通过标识符加载雇员。

应该分析你所有的类,并选择适当的缓存策略为每个类。有时,二级缓存可能降级的应用程序的性能。所以建议到基准应用程序第一次没有启用缓存,非常适合缓存和检查性能。如果缓存不提高系统性能再有就是在使任何类型的缓存是没有意义的。

查询级别缓存:
使用查询缓存,必须先使用 hibernate.cache.use_query_cache="true"属性配置文件中激活它。如果将此属性设置为true,让hibernate的在内存中创建所需的高速缓存来保存查询和标识符集。

接下来,使用查询缓存,可以使用query类的setcacheable(boolean)方法。例如:

session session = sessionfactory.opensession();
query query = session.createquery("from employee");
query.setcacheable(true);
list users = query.list();
sessionfactory.closesession();

hibernate也支持通过一个缓存区域的概念非常细粒度的缓存支持。缓存区是这是给定一个名称缓存的一部分。

session session = sessionfactory.opensession();
query query = session.createquery("from employee");
query.setcacheable(true);
query.setcacheregion("employee");
list users = query.list();
sessionfactory.closesession();

此代码使用方法告诉hibernate来存储和查找在缓存中的员工方面的查询。


hibernate原生sql
可以使用原生sql来表达数据库查询,如果想利用数据库特有的功能,如查询提示或者oracle中的connect关键字。 hibernate3.x允许使用手写sql语句,包括存储过程,所有的创建,更新,删除和load操作。

应用程序将从会话创建一个原生sql查询(session接口上)createsqlquery()方法:

public sqlquery createsqlquery(string sqlstring) throws hibernateexception
当传递一个包含sql查询到createsqlquery()方法,可以将sql结果与任何现有的hibernate实体,联接,或者一个标量结果使用addentity()方法,addjoin(),和addscalar()方法关联的字符串。

标量查询:
最基本的sql查询是从一个或多个表中得到标量(数值)的列表。以下是语法使用原生sql标量的值:

string sql = "select first_name, salary from employee";
sqlquery query = session.createsqlquery(sql);
query.setresulttransformer(criteria.alias_to_entity_map);
list results = query.list();

实体的查询:
上面的查询都是返回标量值,也就是从resultset中返回的“裸”数据。以下是语法通过addentity()方法来从原生sql查询获得实体对象作为一个整体。

string sql = "select * from employee";
sqlquery query = session.createsqlquery(sql);
query.addentity(employee.class);
list results = query.list();

命名sql查询:
以下是语法通过addentity()方法来从原生sql查询获得实体对象和使用命名sql查询。

string sql = "select * from employee where id = :employee_id";
sqlquery query = session.createsqlquery(sql);
query.addentity(employee.class);
query.setparameter("employee_id", 10);
list results = query.list();

native sql 例子:
考虑下面的pojo类:

public class employee {
  private int id;
  private string firstname; 
  private string lastname;  
  private int salary; 

  public employee() {}
  public employee(string fname, string lname, int salary) {
   this.firstname = fname;
   this.lastname = lname;
   this.salary = salary;
  }
  public int getid() {
   return id;
  }
  public void setid( int id ) {
   this.id = id;
  }
  public string getfirstname() {
   return firstname;
  }
  public void setfirstname( string first_name ) {
   this.firstname = first_name;
  }
  public string getlastname() {
   return lastname;
  }
  public void setlastname( string last_name ) {
   this.lastname = last_name;
  }
  public int getsalary() {
   return salary;
  }
  public void setsalary( int salary ) {
   this.salary = salary;
  }
}

让我们创建下面的employee表来存储employee对象:

create table employee (
  id int not null auto_increment,
  first_name varchar(20) default null,
  last_name varchar(20) default null,
  salary   int default null,
  primary key (id)
);

以下将被映射文件。

<?xml version="1.0" encoding="utf-8"?>
<!doctype hibernate-mapping public 
 "-//hibernate/hibernate mapping dtd//en"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
  <class name="employee" table="employee">
   <meta attribute="class-description">
     this class contains the employee detail. 
   </meta>
   <id name="id" type="int" column="id">
     <generator class="native"/>
   </id>
   <property name="firstname" column="first_name" type="string"/>
   <property name="lastname" column="last_name" type="string"/>
   <property name="salary" column="salary" type="int"/>
  </class>
</hibernate-mapping>

最后,我们将创建应用程序类的main()方法来运行,我们将使用原生sql查询的应用程序:

import java.util.*; 
 
import org.hibernate.hibernateexception; 
import org.hibernate.session; 
import org.hibernate.transaction;
import org.hibernate.sessionfactory;
import org.hibernate.sqlquery;
import org.hibernate.criteria;
import org.hibernate.hibernate;
import org.hibernate.cfg.configuration;

public class manageemployee {
  private static sessionfactory factory; 
  public static void main(string[] args) {
   try{
     factory = new configuration().configure().buildsessionfactory();
   }catch (throwable ex) { 
     system.err.println("failed to create sessionfactory object." + ex);
     throw new exceptionininitializererror(ex); 
   }
   manageemployee me = new manageemployee();

   /* add few employee records in database */
   integer empid1 = me.addemployee("zara", "ali", 2000);
   integer empid2 = me.addemployee("daisy", "das", 5000);
   integer empid3 = me.addemployee("john", "paul", 5000);
   integer empid4 = me.addemployee("mohd", "yasee", 3000);

   /* list down employees and their salary using scalar query */
   me.listemployeesscalar();

   /* list down complete employees information using entity query */
   me.listemployeesentity();
  }
  /* method to create an employee in the database */
  public integer addemployee(string fname, string lname, int salary){
   session session = factory.opensession();
   transaction tx = null;
   integer employeeid = null;
   try{
     tx = session.begintransaction();
     employee employee = new employee(fname, lname, salary);
     employeeid = (integer) session.save(employee); 
     tx.commit();
   }catch (hibernateexception e) {
     if (tx!=null) tx.rollback();
     e.printstacktrace(); 
   }finally {
     session.close(); 
   }
   return employeeid;
  }

  /* method to read all the employees using scalar query */
  public void listemployeesscalar( ){
   session session = factory.opensession();
   transaction tx = null;
   try{
     tx = session.begintransaction();
     string sql = "select first_name, salary from employee";
     sqlquery query = session.createsqlquery(sql);
     query.setresulttransformer(criteria.alias_to_entity_map);
     list data = query.list();

     for(object object : data)
     {
      map row = (map)object;
      system.out.print("first name: " + row.get("first_name")); 
      system.out.println(", salary: " + row.get("salary")); 
     }
     tx.commit();
   }catch (hibernateexception e) {
     if (tx!=null) tx.rollback();
     e.printstacktrace(); 
   }finally {
     session.close(); 
   }
  }

  /* method to read all the employees using entity query */
  public void listemployeesentity( ){
   session session = factory.opensession();
   transaction tx = null;
   try{
     tx = session.begintransaction();
     string sql = "select * from employee";
     sqlquery query = session.createsqlquery(sql);
     query.addentity(employee.class);
     list employees = query.list();

     for (iterator iterator = 
              employees.iterator(); iterator.hasnext();){
      employee employee = (employee) iterator.next(); 
      system.out.print("first name: " + employee.getfirstname()); 
      system.out.print(" last name: " + employee.getlastname()); 
      system.out.println(" salary: " + employee.getsalary()); 
     }
     tx.commit();
   }catch (hibernateexception e) {
     if (tx!=null) tx.rollback();
     e.printstacktrace(); 
   }finally {
     session.close(); 
   }
  }
}

编译和执行:
下面是步骤来编译并运行上述应用程序。请确保在进行的编译和执行之前,适当地设置path和classpath。

执行manageemployee二进制文件来运行程序。

会得到以下结果,并记录将在employee表中创建。

$java manageemployee
.......various log messages will display here........

first name: zara, salary: 2000
first name: daisy, salary: 5000
first name: john, salary: 5000
first name: mohd, salary: 3000
first name: zara last name: ali salary: 2000
first name: daisy last name: das salary: 5000
first name: john last name: paul salary: 5000
first name: mohd last name: yasee salary: 3000

如果检查employee表,它应该记录下已:

mysql> select * from employee;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 26 | zara    | ali    |  2000 |
| 27 | daisy   | das    |  5000 |
| 28 | john    | paul   |  5000 |
| 29 | mohd    | yasee   |  3000 |
+----+------------+-----------+--------+
4 rows in set (0.00 sec)

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网