Home Database Mysql Tutorial Hibernate之1-N关联映射

Hibernate之1-N关联映射

Jun 07, 2016 pm 04:09 PM
hibernate association mapping

一、Hibernate之1-N关联映射 1. 哪边是 1 , 哪边是多 ? 需要从业务的角度来说明。例如,Employee 和 Department 之间就是 n-1 的关联关系,Order 和 Customer 之间也是 n-1 的关联关系。 1). 关联关系是有方向的: 2). 如何在类中来建立关联关系呢 ? 解:

一、Hibernate之1-N关联映射

1. 哪边是 1 , 哪边是多 ?

需要从业务的角度来说明。例如,Employee 和 Department 之间就是 n-1 的关联关系,Order 和 Customer 之间也是 n-1 的关联关系。

1). 关联关系是有方向的:
\ 2). 如何在类中来建立关联关系呢 ? 解:通过成员变量的方式即可.

2. 单向 n-1 关联关系

1). 域对象中,在 Order 中声明一个 Customer 类型的成员变量,并提供 setter、getter

public class Order {

private Integer Z喎?http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcmRlcklkOzxicj4KICAgICAgICAgIHByaXZhdGUgU3RyaW5nIG9yZGVyTmFtZTs8YnI+CiAgICAgPGJyPgogICAgICAgICAgcHJpdmF0ZSBDdXN0b21lciBjdXN0b21lcjs8YnI+Cjxicj4KICAgICAgICAgIC8vLi4uPGJyPgogICAgIH08YnI+Cjxicj4KMqOpLiDK/b7dse2jujxicj4KPGltZyBzcmM9"http://www.2cto.com/uploadfile/Collfiles/20141107/2014110709203821.png" alt="\">


3). 如何进行映射:通过 many-to-one 来映射

①. 注意:需要映射在 ORDERS 数据表中的外键列!

column="CUSTOMER_ID"
class="Customer">


4). API 操作时
①. save 时,若先保存 Order, 在保存 Customer,则会多出 UPDATE 语句;若先保存 Customer,再保存 Order,则只有 INSERT. 建议先保存 1 的一端的对象

②. get 时,
◆默认情况下,关联对象采取 懒加载 策略。即在获取 Order 时,若不使用关联的 Customer 的属性, 则不加载 Customer 对象
◆有懒加载就可能会发生懒加载异常:org.hibernate.LazyInitializationException。 ◇什么时候出现懒加载异常? 获取一个对象,没有初始化其关联的属性,若在 Session 已经关闭的情况下,访问关联的属性,就会抛出懒 加载异常。

③. update 时,
◆若对象本身是一个持久化对象,则在 flush Session 时,会级联更新其关联的对象的属性。
◆若对象是游离对象,则不会更新关联对象的属性。但可以通过设置 cascade 属性来使其能够进行更新

④. delete 时,
◆删除对象,只需要 ID 属性
◆防止发生外键约束异常

3. 单向 1-n 关联关系

1). 域对象:增加集合属性

public class Customer {

private Integer customerId;
private String customerName;

//访问 n 的一端的集合属性
private Set orders = new HashSet();

//....
}

注意:
①. 当 Session 从数据库中加载 Java 集合时, 创建的是 Hibernate 内置集合类的实例,
因此在持久化类中定义集合属性时必须把属性声明为 Java 接口类型
②. 在定义集合属性时, 通常把它初始化为集合实现类的一个实例.
避免应用程序访问取值为 null 的集合的方法抛出 NullPointerException


2).关系数据模型
\

3). 如何进行映射,在Customer.hbm.xml中通过 set 元素

order-by="ORDER_NAME ASC">




4). API 具体操作:

①. save 时:因为由 1 的一端来维护关联关系,所以一定会多出 UPDATE 语句! 最好不是有 1 的一端来维护关联关系
②. update 时:
◆若把集合对象 clear,默认情况下是把多的一端的外键置空
③. delete 时:可以删除 1 的一端,但是把多的一端的外键置空

5). set 的 order-by 属性:可以指定在查询集合时,按集合元素对应的数据表的列进行排序!

order-by="ORDER_NAME ASC">








----------------------------------------------------双向关联映射-----------------------------------------------------
4. 双向 1-n 关联关系

1). 如何进行映射(下面是Customer表,注意两者之间的对应关系)



2). set 元素的 inverse 属性可以指定由哪一方来维护关联关系, 一般地,在双向 1-n 关联关系中,1 的一端的 set 的 inverse 都设置为 true,表示有 n 的一端来维护关联关系!
◆ 比如说在Customer表中:
order-by="ORDER_NAME ASC" inverse="true">



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to integrate Hibernate in SpringBoot project How to integrate Hibernate in SpringBoot project May 18, 2023 am 09:49 AM

Integrating Hibernate in SpringBoot Project Preface Hibernate is a popular ORM (Object Relational Mapping) framework that can map Java objects to database tables to facilitate persistence operations. In the SpringBoot project, integrating Hibernate can help us perform database operations more easily. This article will introduce how to integrate Hibernate in the SpringBoot project and provide corresponding examples. 1.Introduce dependenciesIntroduce the following dependencies in the pom.xml file: org.springframework.bootspring-boot-starter-data-jpam

Selected Java JPA interview questions: Test your mastery of the persistence framework Selected Java JPA interview questions: Test your mastery of the persistence framework Feb 19, 2024 pm 09:12 PM

What is JPA? How is it different from JDBC? JPA (JavaPersistence API) is a standard interface for object-relational mapping (ORM), which allows Java developers to use familiar Java objects to operate databases without writing SQL queries directly against the database. JDBC (JavaDatabaseConnectivity) is Java's standard API for connecting to databases. It requires developers to use SQL statements to operate the database. JPA encapsulates JDBC, provides a more convenient and higher-level API for object-relational mapping, and simplifies data access operations. In JPA, what is an entity? entity

Java Errors: Hibernate Errors, How to Handle and Avoid Java Errors: Hibernate Errors, How to Handle and Avoid Jun 25, 2023 am 09:09 AM

Java is an object-oriented programming language that is widely used in the field of software development. Hibernate is a popular Java persistence framework that provides a simple and efficient way to manage the persistence of Java objects. However, Hibernate errors are often encountered during the development process, and these errors may cause the program to terminate abnormally or become unstable. How to handle and avoid Hibernate errors has become a skill that Java developers must master. This article will introduce some common Hib

How to automatically associate MySQL foreign keys and primary keys? How to automatically associate MySQL foreign keys and primary keys? Mar 15, 2024 pm 12:54 PM

How to automatically associate MySQL foreign keys and primary keys? In the MySQL database, foreign keys and primary keys are very important concepts. They can help us establish relationships between different tables and ensure the integrity and consistency of the data. In actual application processes, it is often necessary to automatically associate foreign keys to the corresponding primary keys to avoid data inconsistencies. The following will introduce how to implement this function through specific code examples. First, we need to create two tables, one as the master table and the other as the slave table. Create in main table

What are the differences between hibernate and mybatis What are the differences between hibernate and mybatis Jan 03, 2024 pm 03:35 PM

The differences between hibernate and mybatis: 1. Implementation method; 2. Performance; 3. Comparison of object management; 4. Caching mechanism. Detailed introduction: 1. Implementation method, Hibernate is a complete object/relational mapping solution that maps objects to database tables, while MyBatis requires developers to manually write SQL statements and ResultMap; 2. Performance, Hibernate is possible in terms of development speed Faster than MyBatis because Hibernate simplifies the DAO layer and so on.

In C language, what are Evaluation, Precedence and Association? In C language, what are Evaluation, Precedence and Association? Sep 03, 2023 pm 09:49 PM

The "C" compiler evaluates expressions according to precedence and associativity rules. If an expression contains operators of different precedence, precedence rules are taken into account. Here, 10*2 is evaluated first because '*' has higher precedence than '-' and '='. If the expressions contain the same precedence, the associativity rule is considered, i.e. from left to right (or from right to the left).

How to perform bulk insert update operations in Hibernate? How to perform bulk insert update operations in Hibernate? Aug 27, 2023 pm 11:17 PM

In this article, we will see how to perform bulk insert/update in Hibernate. Whenever we execute a sql statement, we do it by making a network call to the database. Now, if we have to insert 10 entries into the database table, then we have to make 10 network calls. Instead, we can optimize network calls by using batch processing. Batch processing allows us to execute a set of SQL statements in a single network call. To understand and implement this, let us define our entity − @EntitypublicclassParent{@Id@GeneratedValue(strategy=GenerationType.AUTO)

What is the mapping method of one-to-many and many-to-many relationships in Java Hibernate What is the mapping method of one-to-many and many-to-many relationships in Java Hibernate May 27, 2023 pm 05:06 PM

Hibernate's one-to-many and many-to-many Hibernate is an excellent ORM framework that simplifies data access between Java applications and relational databases. In Hibernate, we can use one-to-many and many-to-many relationships to handle complex data models. Hibernate's one-to-many In Hibernate, a one-to-many relationship means that one entity class corresponds to multiple other entity classes. For example, an order can correspond to multiple order items (OrderItem), and a user (User) can correspond to multiple orders (Order). To implement a one-to-many relationship in Hibernate, you need to define a collection attribute in the entity class to store

See all articles