源代码下载地址:
http://download.csdn.net/detail/itjavawfc/7690569
源代码如下:
测试类:
import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.Transaction;
import entity.District;
import entity.Street;
import util.HibernateUtil;
public class RelationTest {
public static void main(String[] args){
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
/* District d1=new District(65,"大黄");
Street s1=new Street(1,d1,"j");
Street s2=new Street(2,d1,"ji");
Street s3=new Street(3,d1,"i");
Street s4=new Street(null,d1,"jo");
session.save(d1);
session.save(s1);
session.save(s2);
session.save(s3);
*/
/* District d1=new District(null,"武汉东湖黄冈");
Street s1=new Street();
s1.setStreet_name("武汉");
Street s2=new Street();
s2.setStreet_name("随州");
Street s3=new Street();
s2.setStreet_name("上市");
d1.getStreets().add(s1);
d1.getStreets().add(s2);
d1.getStreets().add(s3);
session.save(d1);
//session.save(s1);
//session.save(s2);
//session.save(s3);
*/
District d=(District)session.get(District.class, 1002);
System.out.println("您的所在区为:"+d.getName()+",所在街道如下:");
Iterator<Street> it=d.getStreets().iterator();
while(it.hasNext()){
Street s=it.next();
System.out.println(s.getId()+" ------------- "+s.getStreet_name()+" ------------- "+s.getStreet_name());
}
tx.commit();
session.close();
//HibernateUtil.close();
//-----------------------------------------------------------------------------------------------
System.out.println("-----------2222222222222------------------------------------------------------------------");
Session session2=HibernateUtil.getSession();
Transaction tx2=session2.beginTransaction();
District d2=(District)session2.load(District.class, 1002);
System.out.println("您的所在区为:"+d2.getName()+",所在街道如下:");
session2.close();
HibernateUtil.close();
}
}
两个实体类:
package entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class District implements Serializable {
private Integer id;
private String name;
private Set<Street> streets=new HashSet<Street>();
public Set<Street> getStreets() {
return streets;
}
public void setStreets(Set<Street> streets) {
this.streets = streets;
}
public District() {
super();
}
public District(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
District other = (District) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
package entity;
import java.io.Serializable;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
//@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Street implements Serializable {
private Integer id;
private District districtid;
private String street_name;
public Street() {
super();
}
public Street(Integer id, District districtid, String street_name) {
super();
this.id = id;
this.districtid = districtid;
this.street_name = street_name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public District getDistrictid() {
return districtid;
}
public void setDistrictid(District districtid) {
this.districtid = districtid;
}
public String getStreet_name() {
return street_name;
}
public void setStreet_name(String street_name) {
this.street_name = street_name;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((districtid == null) ? 0 : districtid.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((street_name == null) ? 0 : street_name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Street other = (Street) obj;
if (districtid == null) {
if (other.districtid != null)
return false;
} else if (!districtid.equals(other.districtid))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (street_name == null) {
if (other.street_name != null)
return false;
} else if (!street_name.equals(other.street_name))
return false;
return true;
}
}
两个DAO
package dao.impl;
import java.util.List;
import entity.Street;
public interface IStreetDAO {
void insert(Street entity);
void delete(Street entity);
void update(Street entity);
Street findById(Integer id);
List<Street> list();
}
package dao.impl;
import java.util.List;
import entity.District;
import entity.Street;
public interface IDistrictDAO {
void insert(Street entity);
void delete(District entity);
void update(District entity);
District findById(Integer id);
List<District> list();
/*
void insert(Street entity);
void delete(Street entity);
void update(Street entity);
Street findById(Integer id);
List<Street> list();
*/
}
两个DAO实现:
package dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;
import entity.District;
import entity.Street;
public class StreetDAOImpl implements IStreetDAO {
@Override
public void insert(Street entity) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
// Street s=new Street();
session.save(entity);
tx.commit();
session.close();
}
@Override
public void delete(Street entity) {
// TODO Auto-generated method stub
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
session.createQuery("delete Street").executeUpdate();
tx.commit();
session.close();
}
@Override
public void update(Street entity) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
session.update(entity);
tx.commit();
session.close();
}
@Override
public Street findById(Integer id) {
// TODO Auto-generated method stub
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
Street d=null;
try{
d=(Street)session.get(Street.class,id);
//System.out.println(d);
tx.commit();
}catch(HibernateException e){
tx.rollback();
}finally{
session.close();
}
// System.out.println(d);
return d;
}
@Override
public List<Street> list() {
// TODO Auto-generated method stub
return null;
}
}
package dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;
import entity.District;
import entity.Street;
public class DistrictDAOImpl implements IDistrictDAO {
@Override
public void insert(Street entity) {
// TODO Auto-generated method stub
}
@Override
public void delete(District entity) {
// TODO Auto-generated method stub
}
@Override
public void update(District entity) {
// TODO Auto-generated method stub
}
@Override
public District findById(Integer id) {
// TODO Auto-generated method stub
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
District d=null;
try{
d=(District)session.get(District.class,1001);
//System.out.println(d);
tx.commit();
}catch(HibernateException e){
tx.rollback();
}finally{
session.close();
}
// System.out.println(d);
return d;
}
@Override
public List<District> list() {
// TODO Auto-generated method stub
return null;
}
}
对应两个配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="entity.District" table="DISTRICT" schema="scott">
<cache usage="read-only" region="sampleCache1"/>
<id name="id" type="java.lang.Integer">
<column name="ID" precision="22" scale="0" />
<generator class="sequence" >
<param name="sequence">SEQ_DISTRICT</param>
</generator>
</id>
<property name="name" type="java.lang.String">
<column name="DISTRICT_NAME" length="7" not-null="true" />
</property>
<set name="streets" > <!-- cascade="all" cascade="all"-->
<!-- <cache usage="read-only"/> -->
<key column="DISTRICT_ID"/>
<one-to-many class="entity.Street"/>
</set>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="entity.Street" table="STREET" schema="scott">
<cache usage="read-only" region="sampleCache1"/>
<id name="id" type="java.lang.Integer">
<column name="ID" precision="22" scale="0" />
<generator class="native" >
<param name="sequence">SEQ_DISTRICT</param>
</generator>
</id>
<many-to-one name="districtid" class="entity.District">
<column name="DISTRICT_ID" length="7" not-null="true" />
</many-to-one>
<property name="street_name" type="java.lang.String">
<column name="street_name" length="7" not-null="true" />
</property>
</class>
</hibernate-mapping>
必须的ehcache.xml文件(在Hibernate目录中找)
<ehcache>
<diskStore path="d:/ehcache"/>
<!-- diskStore path="d:/ehcache"/ path="java.io.tmpdir"/ -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<cache name="sampleCache2"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/> -->
</ehcache>
Hibernate的配置文件:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:orcl
</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<property name="connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="myeclipse.connection.profile">
oracledriver
</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置二级缓存 ,启用二级缓存-->
<!--
<property name="cache.use_second_level_cache">true</property> -->
<property name="cache.use_query_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory -->
<!-- </property> -->
<mapping resource="entity/District.hbm.xml" />
<mapping resource="entity/Street.hbm.xml" />
</session-factory>
</hibernate-configuration>
工具类:
package util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sf=null;
private static HibernateUtil instance=new HibernateUtil();
private HibernateUtil(){
//读取文件
Configuration cfg=new Configuration().configure();
//解析再创建
ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sf=cfg.buildSessionFactory(sr);
}
//提供静态方法
public static Session getSession(){
return sf.openSession();
}
public static void close(){
if(sf!=null){
sf.close();
}
}
public static void main(String[] args){
System.out.println(HibernateUtil.getSession());
}
}
运行结果:
很明显第二条结果是从缓存中取出来的。
工程目录结构: