hibernate代码优化小技巧

多对多集联关系查询
  用户和角色两表
  在用户表中查询角色信息
用户表实体
private Set<Role> roleSet = new HashSet<Role>(); 
用户表映射关系配置
      <set name="roleSet" table="(1)t_userrole" (2)order-by="id desc" (3)inverse="true">
          <key column="(4)userId"/> 
            <many-to-many class="(5)com.baidu.zh.model.role.Role" column="(6)roleId"/> 
        </set>

(1)中间表 (2)在进行查询是由于set无序所以排序了,(3)控制反转,在这里设为“false时,当表关联后,如果我对用户表进行修改,则将发出一条删除语句,把中间表中的信息删除,(4)用户表中关联的键 (5)角色实体类(角色关联外键)

代码优化:当进行链表查询时 必须将 lazy=”false”,才能查到角色中的信息,负责就会报错,但加上这个属性,查询次数较多,所以一般不用添加而有其他办法:

首先:在web.xml中配置
  <filter>
  <filter-name>openSessionInView</filter-name>
  <filter-class>org.springframework.orm.hibernate3.support.OpenSession      InViewFilter</filter-class>
  </filter>
   <filter-mapping>
  <filter-name>openSessionInView</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>


下面来说说 缓存 我用的是 ehcache
(1)下载解压后 将导入 ehcache-core-2.4.3.jar
(2) ehcache.xml文件 放在src下
   <?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <!--
        缓存到硬盘的路径
    -->
    <diskStore path="e:/ehcache"></diskStore>
   
    <!--
        默认设置
        maxElementsInMemory : 在內存中最大緩存的对象数量。
        eternal : 缓存的对象是否永远不变。
        timeToIdleSeconds :可以操作对象的时间。
        timeToLiveSeconds :缓存中对象的生命周期,时间到后查询数据会从数据库中读取。
        overflowToDisk :内存满了,是否要缓存到硬盘。
    -->
    <defaultCache maxElementsInMemory="1" eternal="false"
        timeToIdleSeconds="500" timeToLiveSeconds="600" overflowToDisk="true"></defaultCache>
       
    <!--
        指定缓存的对象。
        下面出现的的属性覆盖上面出现的,没出现的继承上面的。
    -->
</ehcache>

(3)在hibernate.cfg.xml文件中的配置
    <!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
<property name="cache.use_second_level_cache">true</property>
<property   name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="cache.use_query_cache">true</property>
(4)在映射文件中的配置
     比如我们对菜单树要做缓存
我们就必须加上  <class-cache class="com.baidu.zhangy.model.menu.Menu" usage="read-write"/>
(5)查询时:query.setCacheable(true);

  这样就设置好了,我们在平台上打印的sql 就减少了一大半。
    

 

猜你喜欢

转载自pengbaowei0311.iteye.com/blog/2163565