`

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

alter table idcard2 drop foreign key FK62B3D2E778B7ECB9;
drop table if exists idcard2;
drop table if exists student2;
create table idcard2 
(
	iid varchar(255) not null, 
	num integer, 
	student_id varchar(255) unique, 
	primary key (iid)
);
create table student2 
(
	sid varchar(255) not null, 
	name varchar(255), primary key (sid)
);
alter table idcard2 add index FK62B3D2E778B7ECB9 (student_id), 
add constraint FK62B3D2E778B7ECB9 foreign key (student_id) references student2 (sid); 

表结构如下图所示

 

 

2.Student2.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.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

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

@Entity
@Table(name = "student2")
public class Student2 {

	@Id
	@GenericGenerator(name = "uuid", strategy = "uuid")
	@GeneratedValue(generator = "uuid")
	@Column(name = "sid")
	private String id;

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

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

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public IdCard2 getIdCard() {
		return idCard;
	}

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

}

 以上的Annotation的就相当于以下的Student2.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.Student2" table="student2">

		<id name="id" column="sid" type="string">
			<generator class="uuid">
			</generator>
		</id>

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

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

	</class>

</hibernate-mapping>

 

3.IdCard2.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.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "idcard2")
public class IdCard2 {

	@Id
	@GenericGenerator(name = "uuid", strategy = "uuid")
	@GeneratedValue(generator = "uuid")
	@Column(name = "iid")
	private String id;

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

	@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
	@JoinColumn(name = "student_id", unique = true)
	private Student2 student;

	public String getId() {
		return id;
	}

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

	public int getNum() {
		return num;
	}

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

	public Student2 getStudent() {
		return student;
	}

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

}

 以上的Annotation的就相当于以下的IdCard2.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.IdCard2" table="idcard2">

		<id name="id" column="iid" type="string">
			<generator class="uuid">
			</generator>
		</id>

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

		<many-to-one name="student" class="org.fool.model.Student2"
			column="student_id" cascade="all" unique="true" lazy="false"></many-to-one>

	</class>

</hibernate-mapping>

 4.HibernateTest2.java

 

package org.fool.test;

import org.fool.model.IdCard2;
import org.fool.model.Student2;
import org.fool.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateTest2 {
	public static void main(String[] args) {
		// insert();
		// selectStudent();
		// selectIdCard();
		// updateStudent();
		// delete();
	}

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

		try {
			tx = session.beginTransaction();

			Student2 student = new Student2();
			student.setName("zhangsan");

			IdCard2 idCard = new IdCard2();
			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;

		Student2 student = null;

		try {
			tx = session.beginTransaction();

			student = (Student2) session.get(Student2.class,
					"8aea139d397170d801397170d9480000");

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

		System.out.println(student.getName());
	}

	/**
	 * 查询IdCard信息
	 */
	public static void selectIdCard() {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;

		IdCard2 idCard = null;

		try {
			tx = session.beginTransaction();

			idCard = (IdCard2) session.get(IdCard2.class,
					"8aea139d397170d801397170d9570001");

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

		System.out.println(idCard.getNum());
		System.out.println(idCard.getStudent().getName());
	}
	
	/**
	 * 更新学生信息
	 */
	public static void updateStudent() {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		
		Student2 student = null;
		
		try {
			tx = session.beginTransaction();
			
			student = (Student2) session.get(Student2.class, "8aea139d397170d801397170d9480000");
		
			student.setName("lisi");
			
			tx.commit();
		} catch(Exception ex) {
			ex.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;
		
		IdCard2 idCard = null;
		
		try {
			tx = session.beginTransaction();
			
			idCard = (IdCard2) session.get(IdCard2.class, "8aea139d397170d801397170d9570001");
		
			session.delete(idCard);
			
			tx.commit();
		} catch(Exception ex) {
			ex.printStackTrace();
			if (null != tx) {
				tx.rollback();
			}
		} finally {
			HibernateUtil.closeSession(session);
		}
	}
}

 

5.插入一条数据后的结果

 

6.小结

外键关联:本质上是一对多的蜕化形式。将many-to-one元素中增加unique="true"属性,就变成了一对一。

 

  • 大小: 11.7 KB
  • 大小: 10.5 KB
分享到:
评论

相关推荐

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

    本篇将深入探讨Hibernate中的一对一单向外键关联,通过注解和XML配置两种方式进行实现。这种关联允许一个实体类与另一个实体类之间存在一对一的关系,并且只在其中一个实体类中维护这种关系。 首先,我们来理解一对...

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

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

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

    在Java的持久化框架Hibernate中,一对多关系是常见的实体关联类型,表示一个实体可以与多个其他实体相关联。在本教程中,我们将探讨如何使用注解和XML配置实现Hibernate的一对多单向关联。 首先,让我们理解一对多...

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

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

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

    在Java的持久化框架Hibernate中,多对一的单向关联是一种常见的关系映射方式,它主要用于处理数据库中两个实体间的一种关联关系。在这种关系中,一个实体(多个实例)可以与另一个实体(单个实例)相关联。本文将...

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

    本主题将深入探讨使用Hibernate进行多对多双向关联的实现,既可以通过注解(Annotation)方式,也可以通过XML配置文件来完成。 首先,我们来看多对多关联的基本概念。在数据库设计中,当两个实体之间存在多个实例...

    Hibernate Annotation笔记

    随着Java 5的发布及其对注解的支持,Hibernate引入了一种全新的配置方式——注解配置。 ##### 1. 传统的Hibernate配置方法 传统的Hibernate配置依赖于外部XML文件来进行数据库映射。这些映射通常被定义为一组XML...

    注解配置 javabean hibernate 关联关系

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

    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. 双向关联...

    HibernateAPI中文版.chm

    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. 双向关联...

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

    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 中文 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 体系结构与配置 参考文档(html)

    一对多关联(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 参考文档

    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_3.2.0_符合Java习惯的关系数据库持久化

    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. 双向关联...

    spring加入hibernate annotation方式.zip

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

    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. 三重关联...

    SSH笔记-映射文件配置

    本笔记将详细介绍SSH映射文件配置的三个核心部分:基础配置参数使用、多对一映射以及一对多映射。 **基础配置参数使用** SSH的基础配置通常位于`~/.ssh/config`文件中,此文件可以定义不同的主机别名和相关设置。...

Global site tag (gtag.js) - Google Analytics