Hibernate的关联关系很多,也非常的复杂.
常见的有 one to one ,one to many ,many to one, many to many等等.
学习这些,关联关系.这个基本上占据了Hibernate学习的七成时间。熟悉这些映射模型,需要大量的实践才能掌握。
以下,就先拿最简单关联关系讲起..one to one 关联的实例, 比如1个人只有一个居住地址, 1个人只有一张唯一的身份证。
这里就拿,人和地址作为1对1的关联关系。
做这些实例采用 有如下开发工具:
eclipse 3.3
mysql 5.4 数据库.
tomcat 6.0
本实例,将通过Mapping 映射文件自动生成数据库表;
建立两个Pojo类,一个Person,一个Address类.
具体代码如下:
package pack.java.model;
import java.io.Serializable;
/**
* 一个人只有一个地址;
* 1对1,单向关联
* @author Administrator
*
*/
public class Person implements Serializable{
private static final long serialVersionUID = -6313867775683964530L;
private Integer id;
private String name;
private Integer age;
private Address address;
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;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address类代码: 应为是单向关联,则address类不需要关联到person类.
package pack.java.model;
import java.io.Serializable;
/**
*
* 一对一的关系;
* @author Administrator
*
*/
public class Address implements Serializable{
private static final long serialVersionUID = 3635140598485086087L;
private Integer addressID;
private String addressDetail;
public Integer getAddressID() {
return addressID;
}
public void setAddressID(Integer addressID) {
this.addressID = addressID;
}
public String getAddressDetail() {
return addressDetail;
}
public void setAddressDetail(String addressDetail) {
this.addressDetail = addressDetail;
}
}
接下来,手动建立Person.hbm.xml文件,或者也可以通过myEclipse工具直接生成.
Person.hbm.xml 代码如下:
<?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="pack.java.model.Person" table="ZHT_PERSON">
<id name="id" type="java.lang.Integer" column="ID">
<generator class="identity"></generator>
</id>
<property name="name" type="java.lang.String"></property>
<property name="age" type="java.lang.Integer"></property>
<!--
在Person里面的many-to-one里面的unique='true'是代表,唯一的,也就是一对一的关系.
column 是address 对象里面的属性名称、
name 是person 对象里面的对象名称。
-->
<many-to-one
name="address"
class="pack.java.model.Address"
column="addressID"
unique="true"
cascade="save-update,persist"
>
</many-to-one>
</class>
</hibernate-mapping>
建立Address.hbm.xml文件:
<?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="pack.java.model.Address" table="ZHT_ADDRESS">
<id name="addressID" column="addressID" type="java.lang.Integer">
<generator class="identity"></generator>
</id>
<!-- 属性映射 -->
<property name="addressDetail" type="java.lang.String"></property>
</class>
</hibernate-mapping>
建立好之后,然后建立一个Hibernate的配置文件,添加连接数据库的一些基本信息.以及Mapping文件的映射地址.
Hibernate.cfg.xml文件:
<?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="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="connection.url">jdbc:mysql://localhost/test</property>
<property name="connection.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!--自动创建sql脚本-->
<property name="hbm2ddl.auto">create</property>
<property name="connection.show_sql">true</property>
<property name="connection.format_sql">true</property>
<!-- Mapping映射文档; -->
<mapping resource="pack/java/model/Address_one_to_one.hbm.xml"/>
<mapping resource="pack/java/model/Person_one_to_one.hbm.xml"/>
</session-factory>
</hibernate-configuration>
最后,我们在建立一个HibernateSessionFactory文件,这个文件可以自动生成..
具体代码如下:
package pack.java.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "pack/java/hibernate/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
最后,我们可以在新建一个Test类来测试,这些Hibernate映射关系了.
package pack.java.test;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import pack.java.hibernate.HibernateSessionFactory;
import pack.java.model.Address;
import pack.java.model.Person;
/**
* 测试;
* @author Administrator
*
*/
public class HibernateDaoDemo {
/**
* 测试主方法;
* @param args
*/
public static void main(String[] args) {
Session session = getSession();
HibernateDaoDemo hibernateDaoDemo = new HibernateDaoDemo();
//保存person对象;
hibernateDaoDemo.savePerson(session);
//查询;
List<Person> personList = hibernateDaoDemo.queryPerson(session);
for(Person person:personList){
System.out.println(person.getId()+","+person.getName()+","+person.getAge()+","+person.getAddress());
}
}
/**
* 创建session;
* @return
*/
private static Session getSession(){
return HibernateSessionFactory.getSession();
}
/**
* 保存Person;
* @param session
*/
private void savePerson(Session session){
Person person = new Person();
person.setAge(23);
person.setName("周海涛");
Address address = new Address();
address.setAddressDetail("中国湖南株洲市");
person.setAddress(address);
session.beginTransaction().begin();
//保存;
session.save(person);
session.beginTransaction().commit();
System.out.println("保存成功!");
}
/**
* 查询Person;
* @param session
* @return
*/
private List<Person> queryPerson(Session session){
Query query = session.createQuery("from Person p where p.name=:name");
query.setParameter("name", "ZhouHaiTao");
List<Person> list = query.list();
return list;
}
}