Hibernate
Hibeinate配置
多对一:在多的一方添加<many-to-one name="city" column="cid"/>
(name:在对象中的成员变量名称,column:外键列)
一对多:在一一方添加
<set name="districts" >
<key column="cid" />
<one-to-many class="District" />
</set>
(name:对象中成员变量名称,key:外键,one-to-many:标签中class对应多一方对象)
级联:cascade=”all”
二级缓存的配置(echcache):
将echcache.xml文件拷贝到src下
开启二级缓存,修改hibernate.cfg.xml文件
<property name="hibernate.cache. use_second_level_cache">true</property>
指定缓存产品提供商,修改hibernate.cfg.xml文件
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
指定哪些实体类使用二级缓存(两种方法)
* 在映射文件中采用<cache>标签
* 在hibernate.cfg.xml文件中,采用<class-cache>标签
get() – 直接返回对象,不存在则返回null;
load() – 返回代理对象,不存在则抛异常;
list() – 直接查出所有对象,没开启查询缓存是每次都读数据库;
Iterate () – 查询主键列,使用时再发出sql查出指定对象;
session.clear(),session.evict() (管理一级缓存)
<? 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="org.yhb.demo.hibernate.entity">
<class name="City" table="t_city">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
<set name="districts" >
<key column="cid" />
<one-to-many class="District" />
</set>
</class>
</hibernate-mapping>
<?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="org.yhb.demo.hibernate.entity">
<class name="District" table="t_district">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
<many-to-one name="city" column="cid" cascade="all"/>
</class>
</hibernate-mapping>
<?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">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property>
<property name="connection.username">username</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<!--
<property name="hbm2ddl.auto">create</property>
<property name="format_sql">true</property>
<property name="show_sql">true</property>
-->
<mapping resource="org/yhb/demo/hibernate/entity/City.hbm.xml" />
<mapping resource="org/yhb/demo/hibernate/entity/District.hbm.xml" />
</session-factory>
</hibernate-configuration>