`

Hibernate 一对一映射之主键关联 Annotation Example

    博客分类:
  • ORM
 
阅读更多

0.pom.xml

......        
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<hibernate-version>3.6.10.Final</hibernate-version>
		<javassist-version>3.12.1.GA</javassist-version>
		<slf4j-nop-version>1.6.6</slf4j-nop-version>
		<mysql-connector-version>5.1.21</mysql-connector-version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate-version}</version>
		</dependency>

		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>${javassist-version}</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-nop</artifactId>
			<version>${slf4j-nop-version}</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql-connector-version}</version>
		</dependency>
	</dependencies>
......

 

1.schema.sql

drop table if exists idcard;
drop table if exists student;
create table idcard 
(
	iid integer not null, 
	num integer, 
	primary key (iid)
);
create table student 
(	
	sid integer not null auto_increment, 
	name varchar(255), 
	primary key (sid)
);

表结构如下图所示

 

 

2.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.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
		<property name="connection.username">root</property>
		<property name="connection.password">123456</property>

		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>
		<property name="format_sql">false</property>

	<!-- <mapping resource="org/fool/model/Student.hbm.xml" /> -->
	<!-- <mapping resource="org/fool/model/IdCard.hbm.xml" /> -->
		<mapping class="org.fool.model.Student" />
		<mapping class="org.fool.model.IdCard" />

	</session-factory>

</hibernate-configuration>

 这里使用Student表和IdCard表进行一对一关联

 

3.Student.java

package org.fool.model;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

@Entity
@Table(name = "student")
public class Student {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "sid")
	private int id;

	@Column(name = "name")
	private String name;

	@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "student")
	@Fetch(FetchMode.SELECT)
	private IdCard idCard;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public IdCard getIdCard() {
		return idCard;
	}

	public void setIdCard(IdCard idCard) {
		this.idCard = idCard;
	}

}

 以上的annotation就相当于以下的Student.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="org.fool.model.Student" table="student">

		<id name="id" column="sid" type="integer">
			<generator class="identity">
			</generator>
		</id>

		<property name="name" column="name" type="string" />

		<one-to-one name="idCard" class="org.fool.model.IdCard"
			cascade="all" fetch="select"></one-to-one>

	</class>

</hibernate-mapping>

 

4.IdCard.java

package org.fool.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "idcard")
public class IdCard {
	@Id
	@GenericGenerator(name = "generator", strategy = "foreign", 
		parameters = @Parameter(name = "property", value = "student"))
	@GeneratedValue(generator = "generator")
	@Column(name = "iid")
	private int id;

	@Column(name = "num")
	private int num;

	@OneToOne(fetch = FetchType.LAZY)
	@PrimaryKeyJoinColumn
	@Fetch(FetchMode.SELECT)
	private Student student;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}

}

 以上的annotation就相当于以下的IdCard.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="org.fool.model.IdCard" table="idcard">

		<id name="id" column="iid" type="integer">
			<generator class="foreign">
				<param name="property">student</param>
			</generator>
		</id>

		<property name="num" column="num" type="integer" />

		<one-to-one name="student" class="org.fool.model.Student"
			fetch="select"></one-to-one>

	</class>

</hibernate-mapping>

 

5.HibernateUtil.java

package org.fool.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static SessionFactory sessionFactory;

	static {
		try {
			sessionFactory = new Configuration().configure()
					.buildSessionFactory();
		} catch (Exception ex) {
			System.err.println("构造SessionFactory异常发生: " + ex.getMessage());
		}

	}

	public static Session openSession() {
		Session session = sessionFactory.openSession();
		return session;
	}

	public static void closeSession(Session session) {
		if (null != session) {
			session.close();
		}
	}

}

 

6.HibernateTest.java

package org.fool.test;

import org.fool.model.IdCard;
import org.fool.model.Student;
import org.fool.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateTest {
	public static void main(String[] args) throws Exception {
		// insert();
		// selectStudent();
		// updateStudent();
	    // delete();
	}

	/**
	 * 添加信息
	 */
	public static void insert() {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;

		try {
			tx = session.beginTransaction();
			
			Student student = new Student();
			student.setName("zhangsan");
			
			IdCard idCard = new IdCard();
			idCard.setNum(123456);
			
			student.setIdCard(idCard);
			idCard.setStudent(student);
			
			session.save(student);

			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (null != tx) {
				tx.rollback();
			}
		} finally {
			HibernateUtil.closeSession(session);
		}
	}

	/**
	 * 查询学生信息
	 */
	public static void selectStudent() {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		
		Student student = null;

		try {
			tx = session.beginTransaction();

			student = (Student) session.get(Student.class, 1);
			
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (null != tx) {
				tx.rollback();
			}
		} finally {
			HibernateUtil.closeSession(session);
		}
		
		System.out.println(student.getName());
		System.out.println(student.getIdCard().getNum());
	}

	/**
	 * 更新学生信息
	 */
	public static void updateStudent() {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		
		Student student = null;

		try {
			tx = session.beginTransaction();
			
			student = (Student) session.get(Student.class, 1);
			
			student.setName("lisi");

			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (null != tx) {
				tx.rollback();
			}
		} finally {
			HibernateUtil.closeSession(session);
		}
		
		System.out.println(student.getName());
	}

	/**
	 * 级联删除
	 */
	public static void delete() {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		
		Student student = null;

		try {
			tx = session.beginTransaction();
			
			student = (Student) session.get(Student.class, 1);
			
			session.delete(student);

			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (null != tx) {
				tx.rollback();
			}
		} finally {
			HibernateUtil.closeSession(session);
		}
	}

}

 

7.总结

主键关联:一对一默认使用的是立即加载,如果需要使用延迟加载,那么需要在one-to-one元素中将constrained属性设为true,并且将待加载的一方的class元素中lazy属性设为true(或者不去设置,因为该属性默认值是true);一对一加载时默认 使用左外连接,可以通过修改fetch属性为select,修改成每次发送一条select语句的形式。

  • 大小: 15.6 KB
分享到:
评论

相关推荐

    Hibernate一对一双向外键关联(annotation/xml)

    在Java的持久化框架Hibernate中,一对一双向外键关联是一种常见的关系映射方式,用于表示两个实体类之间一对一的关联关系。在这个场景下,每个实体都有一个引用指向另一个实体,形成双向关联。本篇文章将深入探讨...

    Hibernate多对多单向关联(annotation/xml)

    在Java的持久化框架Hibernate中,多对多(Many-to-Many)关联是一种常见的关系映射类型,它用于表示两个实体之间可以有多个对应的关系。本篇将详细讲解如何使用Hibernate实现多对多单向关联,包括注解(Annotation)...

    注解配置 javabean hibernate 关联关系

    关联关系是数据库中的表与表之间的一种联系,比如一对一(OneToOne)、一对多(OneToMany)、多对一(ManyToOne)和多对多(ManyToMany)。在Hibernate中,我们可以通过以下注解来配置关联关系: 1. `@OneToOne`: ...

    Hibernate Annotation笔记

    Hibernate作为Java领域内最流行的ORM框架之一,在过去的几年中经历了显著的发展,已经成为Java数据库持久化的事实标准。它不仅功能强大,而且灵活性高、性能优越。随着Java 5的发布及其对注解的支持,Hibernate引入...

    Hibernate 中文 html 帮助文档

    6.2.5. 一对多关联(One-to-many Associations) 6.3. 高级集合映射(Advanced collection mappings) 6.3.1. 有序集合(Sorted collections) 6.3.2. 双向关联(Bidirectional associations) 6.3.3. 双向关联,...

    Hibernate教程

    7.2.5. 一对多关联(One-to-many Associations) 7.3. 高级集合映射(Advanced collection mappings) 7.3.1. 有序集合(Sorted collections) 7.3.2. 双向关联(Bidirectional associations) 7.3.3. 三重关联...

    最全Hibernate 参考文档

    1.1. 开始Hibernate之旅 1.2. 第一个持久化类 1.3. 映射cat 1.4. 与Cat同乐 1.5. 结语 2. 架构(Architecture) 2.1. 概况(Overview) 2.2. 实例状态 2.3. JMX整合 2.4. 对JCA的支持 3. 配置 3.1. 可编程的配置方式 ...

    hibernate 体系结构与配置 参考文档(html)

    一对多关联(One-to-many Associations) 6.3. 高级集合映射(Advanced collection mappings) 6.3.1. 有序集合(Sorted collections) 6.3.2. 双向关联(Bidirectional associations) 6.3.3. 双向关联,涉及...

    Hibernate3的帮助文档

    7.2.5. 一对多关联(One-to-many Associations) 7.3. 高级集合映射(Advanced collection mappings) 7.3.1. 有序集合(Sorted collections) 7.3.2. 双向关联(Bidirectional associations) 7.3.3. 三重关联...

    spring加入hibernate annotation方式.zip

    接下来是Hibernate,它是Java领域的一个流行ORM(对象关系映射)框架。Hibernate允许开发者用Java对象来操作数据库,而无需直接编写SQL语句,极大地提高了开发效率。Hibernate支持多种数据持久化方式,其中注解配置...

    hibernate3.3.2_参考文档

    这些映射文件定义了类和表之间的字段对应、主键生成策略、关联关系等信息。例如,一个用户类可能会有一个对应的`User.hbm.xml`文件,其中包含如下的映射配置: ```xml &lt;hibernate-mapping&gt; &lt;class name="com....

    hibernate的anntation,可是看看,对于学习hibernate很有帮助

    Hibernate是一个流行的Java持久化框架,它允许开发者将对象模型映射到关系数据库,极大地简化了数据库操作。在本文中,我们将深入探讨Hibernate的注解(Annotation)特性,这对于理解和使用Hibernate进行开发非常有...

    javaexample

    通过阅读源代码,我们可以学习到如何使用注解(Annotation)或者XML配置来实现对象关系映射,如何定义实体类的关联(一对一、一对多、多对多),以及事务管理的实践。 此外,这个例子还可能涉及错误处理和日志记录...

    hibernate3.04中文文档.chm

    7.2.5. 一对多关联(One-to-many Associations) 7.3. 高级集合映射(Advanced collection mappings) 7.3.1. 有序集合(Sorted collections) 7.3.2. 双向关联(Bidirectional associations) 7.3.3. 三重关联...

    hibernate 框架详解

    一对多关联(One-to-many Associations) 7.3. 高级集合映射(Advanced collection mappings) 7.3.1. 有序集合(Sorted collections) 7.3.2. 双向关联(Bidirectional associations) 7.3.3. 三重关联...

    Hibernate3+中文参考文档

    6.2.5. 一对多关联(One-to-many Associations) 6.3. 高级集合映射(Advanced collection mappings) 6.3.1. 有序集合(Sorted collections) 6.3.2. 双向关联(Bidirectional associations) 6.3.3. 三重关联...

    Hibernate参考文档

    6.2.5. 一对多关联(One-to-many Associations) 6.3. 高级集合映射(Advanced collection mappings) 6.3.1. 有序集合(Sorted collections) 6.3.2. 双向关联(Bidirectional associations) 6.3.3. 双向关联,...

    hibernate注解

    Hibernate作为一款优秀的Java持久层框架,提供了强大的ORM(Object-Relational Mapping)功能,它能够将Java对象模型映射到关系数据库的表上,使得对数据库的操作更加简单、直观。随着Java 5的引入,注解成为了简化...

    hibernate_doc

    Hibernate Annotation是Hibernate的一个扩展,它引入了注解方式来进行ORM配置,使得代码更加简洁且易于维护。3.4版本的主要亮点包括: 1. **实体类注解**:如`@Entity`用于标记实体类,`@Table`定义对应数据库表,`...

Global site tag (gtag.js) - Google Analytics