`

Hibernate关联映射-one to one单向外键关联

 
阅读更多

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;
	}
	
}

 

 

 

 

分享到:
评论

相关推荐

    hibernate one-to-one 一对一唯一外键关联映射_单向 and 双向

    hibernate one-to-one 一对一唯一外键关联映射_单向 and 双向

    Hibernate关联映射

    Hibernate 一对一外键单向关联 Hibernate 一对一主键单向关联 Hibernate 一对一连接表单向关联 Hibernate 一对多外键单向关联 Hibernate 一对多连接表单向关联 Hibernate 多对一外键单向关联 Hibernate 多对一连接...

    Hibernate关联关系映射目录

    Hibernate关联关系映射 单向关联 │ ├─ 一对一外键单向关联 │ ├─ 一对一主键单向关联 │ ├─ 一对一连接表单向关联 │ ├─ 一对多外键单向关联 │ ├─ 一对多连接表单向关联 │ ├─ 多对一外键单向关联 │ ...

    Hibernate一对一唯一外键关联映射(单向关联)

    博文链接:https://shaqiang32.iteye.com/blog/201311

    Hibernate学习笔记

    020 &lt;one-to-one&gt;、&lt;many-to-one&gt;单端关联上的 lazy(懒加载)属性 021 继承关联映射 022 component(组件)关联映射 023 复合主键 关联映射 024 其它 关联映射 025 hibernate 悲观锁、乐观锁 026 hibernate 操作树形...

    Hibernate_实体关联关系映射--学习总结

    Hibernate 实体关联关系映射 学习总结 把一对一 一对多 单向 双向 主键 外键 链接表等讲的比较清楚

    hibernate学习笔记

    hibernate一对一唯一外键关联映射(单向关联Person----&gt;IdCard) 10 hibernate一对一唯一外键关联映射(双向关联Person&lt;----&gt;IdCard) 11 session flush测试(hibernate_session_flush) 12 hihernate一对多关联映射...

    Hibernate教程04_关系映射之一对一单向外键关联

    http://blog.csdn.net/e421083458/article/details/8794127 该源码为Hibernate教程配套源码

    Hibernate_Annotation关联映射

    和其它许多批注一样,在多对多关联中很多值是自动生成,党双向多对多关联中没有定义任何物理映射时,Hibernate根据以下规则生成相应的值,关联表名:主表表名+下划线+从表表名,关联到主表的外键名:主表名+下划线+...

    Hibernate高级映射实例

    Hibernate高级映射的几个单向关系,单向一对一(共享主键方式、唯一外键方式),单向多对一,单向一对多,单向多对多。

    详解Hibernate一对一映射配置

    个人的很详细的Hibernate一对一映射配置详解,对初学者有帮助!

    unidirectional-one2one-foreignkey:该存储库正在存储有关Hibernate映射示例的源代码-一对一-one source code

    Hibernate映射-单向关联 外键一对一关联 在此示例中,我创建两个表:人员和地址。 这两个表都有一个自动递增的id作为主键。 人员表持有地址表中的外键。

    HibernateAPI中文版.chm

    5.1.10. 多对一(many-to-one) 5.1.11. 一对一 5.1.12. 自然ID(natural-id) 5.1.13. 组件(component), 动态组件(dynamic-component) 5.1.14. properties 5.1.15. 子类(subclass) 5.1.16. 连接的子类(joined-...

    hibernate3.2中文文档(chm格式)

    5.1.10. 多对一(many-to-one) 5.1.11. 一对一 5.1.12. 自然ID(natural-id) 5.1.13. 组件(component), 动态组件(dynamic-component) 5.1.14. properties 5.1.15. 子类(subclass) 5.1.16. 连接的子类(joined-...

    Hibernate_3.2.0_符合Java习惯的关系数据库持久化

    5.1.10. 多对一(many-to-one) 5.1.11. 一对一 5.1.12. 自然ID(natural-id) 5.1.13. 组件(component), 动态组件(dynamic-component) 5.1.14. properties 5.1.15. 子类(subclass) 5.1.16. 连接的子类(joined-...

    Hibernate+中文文档

    5.1.10. 多对一(many-to-one) 5.1.11. 一对一 5.1.12. 自然ID(natural-id) 5.1.13. 组件(component), 动态组件(dynamic-component) 5.1.14. properties 5.1.15. 子类(subclass) 5.1.16. 连接的子类(joined-...

    精通 Hibernate:Java 对象持久化技术详解(第2版).part2

     15.2 映射单向多对多关联  15.3 映射双向多对多关联关系  15.3.1 关联两端使用元素  15.3.2 在inverse端使用元素  15.3.3 使用组件类集合  15.3.4 把多对多关联分解为两个一对多关联  15.4 小结  15.5 思考...

    Hibernate中文详细学习文档

    5.1.10. 多对一(many-to-one) 5.1.11. 一对一 5.1.12. 自然ID(natural-id) 5.1.13. 组件(component), 动态组件(dynamic-component) 5.1.14. properties 5.1.15. 子类(subclass) 5.1.16. 连接的子类(joined-...

Global site tag (gtag.js) - Google Analytics