Detailed explanation of examples of two types of Hibernate class mapping
This article mainly introduces the basic class mapping and object relational mapping of Hibernate mapping in detail. It is of great practical value. Friends who need it can refer to it.
Recall some of the things we established when we didn’t learn ssh. For database tables, the database is first modeled as an E-R diagram, and then the relationship model is established through the entity model, and then the corresponding tables are established. There are three types of relationships between entities, one-to-one, one-to-many (or many-to-one), and many-to-many. Now, if we want to map the corresponding table based on the class, we can only map the database table through the relationship between classes and mapping files. We learn UML modeling. There are five relationships between classes, inheritance, implementation, association, dependency, aggregation/combination. The relationship between entity classes in hibernate is also In this way, we are already familiar with the code implementation corresponding to different relationships, so the entity class is review knowledge.
The essence of Hibernate is object relational mapping (ObjectRelational Mapping). ORM realizes saving object data to the database. In the past, we operated on the relational table and performed additions, deletions and modifications. Query and other tasks, now we no longer operate on the relational table, but directly operate on the object. ORM mapping files in hibernate usually have the suffix .hbm.xml. Using this mapping file is not only easy to read, but also can be modified manually, or you can use some tools to generate mapping documents. The mapping in hibernate will be introduced below.
Hibernate mapping classification, as shown in the figure below.
1 Basic class mapping
Create corresponding tables based on entity classes, this simple relationship Basic mapping for hibernate.
User1 entity class code is as follows:
//user实体。 public classUser1 { //用户编号。 private String id; //名字。 private String name; //密码。 private String password; //创建日期。 private Date createTime; //失效时间。 private Date expireTime; public String getId() { return id; } // publicvoid setId(String id) { // this.id= id; // } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(Stringpassword) { this.password = password; } public Date getCreateTime() { return createTime; } public void setCreateTime(DatecreateTime) { this.createTime = createTime; } public Date getExpireTime() { return expireTime; } public void setExpireTime(DateexpireTime) { this.expireTime = expireTime; } }
User1.hbm.xml mapping file is as follows:
<hibernate-mapping package="com.bjpowernode.hibernate"> <class name="User1" table="t_user1"> <id name="id"column="user_id" length="32"access="field"> <generator class="uuid" /> </id> <!-- 设置主键不能重复和不能为空的属性. --> <property name="name" length="30"unique="true" not-null="true"/> <property name="password"/> <property name="createTime" type="date" column="create_time"/> <property name="expireTime"/> </class> </hibernate-mapping>
Convert the User1 object into the table t_user1 in the relational database through the User1.hbm.xml mapping file.
The converted result is as follows:
2 Object relational mapping
2.1 Many-to-one association mapping (one-way)
For example, the relationship between users and groups is a many-to-one relationship, and multiple users correspond to one group.
#Map entities into tables and map corresponding entities into tables. The corresponding attributes are mapped to table fields.
Many-to-one association mapping maintains association fields on the many side. In our example, it maintains relationship fields on the user side.
User.hbm.xml file.
<hibernate-mapping package="org.hibernate.auction"> <class name="com.bjpowernode.hibernate.User" table="t_user" > <id name="id"> <generator class="native" /> </id> <property name="name"/> <many-to-one name="group" column="groupid"cascade="save-update"></many-to-one> </class> </hibernate-mapping>
Group.hbm.xml file.
<hibernate-mapping package="org.hibernate.auction"> <class name="com.bjpowernode.hibernate.Group" table="t_group"> <id name="id"> <generator class="native" /> </id> <property name="name"/> </class> </hibernate-mapping>
The code we look at here is the *.hbm.mlx code, because for the association between classes, during implementation, one class acts as another Private members of a class, we all understand this when learning UML modeling. What we mainly look at here is the M of ORM, which is the *.hbm.xml file.
2.2 One-to-one association mapping
One-to-one association mapping is relatively common in real life, such as the relationship between a person and his home address, through The person object can find content related to his home address.
2.2.1 One-to-one mapping (one-way primary key association)
One-to-one one-to-one primary key association , relying on the fact that their primary keys are equal. You can see IdCard from Person, that is, the primary key in t_idCard is taken as the primary key of t_Pseron.
In the Xml file:
<class name="com.bjpowernode.hibernate.Person"table="t_person" > <id name="id"> <!-- 采用foreign生成策略,foreign会取得关联对象的标识 --> <generator class="foreign" > <!--property指的是关联对象。 --> <param name="property">idCard</param> </generator> </id> <property name="name"/> <!-- 一对一关联映射,主键关联. --> <!-- one-to-one标签指示hibernate如何加载其关联对象,默认根据主键加载. 也就是拿到关系字段值,根据对端的主键来加载关联对象. constrained="true",表示当前主键(Person的主键)还是一个外键 . 参照了对端的主键(IdCard的主键),也就是会生成外键约束语句. --> <one-to-one name="idCard" constrained="true"/> </class>
<hibernate-mapping package="org.hibernate.auction"> <class name="com.bjpowernode.hibernate.IdCard" table="t_idCard" > <id name="id"> <generator class="native" /> </id> <property name="cardNo"/> </class> </hibernate-mapping>
The one-to-one relationship is through one-to- defined by one element.
2.2.2 One-to-one mapping (two-way primary key association)
The difference between one-to-one two-way primary key association and one-to-one one-way primary key association is that a pair For a one-way primary key association, the idCard can be seen on the person side, but the idCard cannot be seen on the Person side. The two-way association means that person can also be seen on the idCard side, that is, not only adding the
<hibernate-mapping package="org.hibernate.auction"> <class name="com.bjpowernode.hibernate.IdCard" table="t_idCard" > <id name="id"> <generator class="native" /> </id> <property name="cardNo"/> <one-to-one name="person"/> </class> </hibernate-mapping>
##2.2.3 One-to-one mapping (one-way unique foreign key Association)
一对一单向唯一外键关联,也就是多对一关联的特例,把多的一端限制为一,就是一对一唯一外键关联。同多对一一样,在一端加入另一端的并采用
先上代码。
IdCard.hbm.xml
<hibernate-mapping package="org.hibernate.auction"> <class name="com.bjpowernode.hibernate.IdCard" table="t_idCard" > <id name="id"> <generator class="native" /> </id> <property name="cardNo"/> </class> </hibernate-mapping>
Person.hbm.xml
<hibernate-mapping package="org.hibernate.auction"> <class name="com.bjpowernode.hibernate.Person" table="t_person" > <id name="id"> <!-- 采用foreign生成策略,foreign会取得关联对象的标识 --> <generator class="native" /> </id> <property name="name"/> <many-to-one name="idCard" unique="true"></many-to-one> </class> </hibernate-mapping>
图如下所示:
在t_pserson端加上一个外键字段idCard,限制idCard的唯一性就是一对一唯一外键关联。
2.2.4 一对一映射(双向唯一外键关联)
一对一唯一外键单向关联我们已经了解了,双向反过来就是在没有的一端加上就可以了。
我们的IdCard.hbm.xml中采用
<hibernate-mapping package="org.hibernate.auction"> <class name="com.bjpowernode.hibernate.IdCard" table="t_idCard" > <id name="id"> <generator class="native" /> </id> <property name="cardNo"/> <one-to-one name="person" property-ref="idCard"></one-to-one> </class> </hibernate-mapping>
而person.hbm.xml同一对一唯一外键单向关联一样。
<class name="com.bjpowernode.hibernate.Person" table="t_person" > <id name="id"> <!-- 采用foreign生成策略,foreign会取得关联对象的标识 --> <generator class="native" /> </id> <property name="name"/> <many-to-one name="idCard" unique="true"></many-to-one> </class>
从上述中可以总结出,对于一对一关联映射,主键关联和唯一外键关联单向和双向产生出的表结构是一样的,不同的是在加载的时候不同。也就是一对一双向关联和一对一单向关联的相比,只是改变了一对一关联映射的加载,而没有改变存储。
2.3 一对多关联映射
2.3.1 一对多关联映射(单向)
上面我们介绍了多对一,我们反过来看一对多不就是多对一吗?那还用再进行不同的映射吗?有什么差别吗?一对多和多对一映射原理是一致的,存储是相同的,也就是生成的数据库的表是一样的,他们之间不同的是维护的关系不同。
他们之间不同点是维护的关系不同
多对一维护的关系是:多指向一的关系,有了此关系,加载多的时候可以将一加载上来。
一对多维护的关系是:一指向多的关系,有了此关系,在加载一的时候可以将多加载上来。
代码如下所示。
Class.hbm.xml
<class name="com.bjpowernode.hibernate.Classes" table="t_Classes" > <id name="id"> <generator class="native" /> </id> <property name="name"/> <set name="students"> <!-- <keycolumn="classesid" not-null="true"/> --> <key column="classesid" /> <one-to-many class="com.bjpowernode.hibernate.Student"/> </set> </class>
Students.hbm.xml
<class name="com.bjpowernode.hibernate.Student" table="t_student" > <id name="id"> <generator class="native" /> </id> <property name="name"/> </class>
从班级能看到学生,是班级来维护关系,不是学生来维护关系,学生不知道自己是哪个班,所以在存储学生的时候,班级的代码不知道。为了更新学生是哪个班级的要发出很多update语句来告诉学生是哪个班级的。当我们设置classesid not-null=“true”时,则将无法保存数据,解决办法我们改为双向关联映射。
2.3.2 一对多关联映射(双向)
为了解决一对多单向可能存在的问题,我们采用双向一对多,每一方都能维护对方。
一对多双向关联映射方式:
在一的一端的集合上采用
标签,在多的一端加入一个外键。 在多的一端采用
的标签
!~注意
代码如下所示。
<class name="com.bjpowernode.hibernate.Classes" table="t_Classes" > <id name="id"> <generator class="native" /> </id> <property name="name"/> <set name="students" inverse="true"> <!-- <keycolumn="classesid" not-null="true"/> --> <key column="classesid" /> <one-to-many class="com.bjpowernode.hibernate.Student"/> </set> </class>
<class name="com.bjpowernode.hibernate.Student" table="t_student" > <id name="id"> <generator class="native" /> </id> <property name="name"/> <many-to-one name="classes"column="classesid"/> </class>
注意:Inverse属性
1、 Inverse中文意思为相反的,反转。在hibernate中inverse可以用在一对多和多对多双向关联上,inverse默认是false,为false的时候表示本端可以维护关系,如果inverse为true,则本端不能维护关系,会交给另一端维护关系,本端失效,所以在一对多关联映射我们通常在多的一端维护关系,让一的一端失效。
2、Inverse是控制方向上的反转,只影响存储。
比较一对多单向和双向映射,从存储结构上看没有什么区别,但是从配置文件上看,一对多双向比一对多单向,一对多双向关联的配置文件中在多的一端的配置文件上存在
2.4 多对多关联映射
2.4.1 多对多关联映射(单向)
多对多对象关系映射,需要加入一张新表完成基本映射。如下图所示。
代码。
Role.hbm.xml
<class name="com.bjpowernode.hibernate.Role" table="t_role"> <id name="id"> <generator class="native" /> </id> <property name="name"/> </class>
User.hbm.xml
<class name="com.bjpowernode.hibernate.User" table="t_user" > <id name="id"> <generator class="native" /> </id> <property name="name"/> <set name="roles" table="t_user_role"> <key column="user_id"/> <many-to-many class="com.bjpowernode.hibernate.Role" column="role_id"/> </set> </class>
2.4.2 多对多关联映射(双向)
双向多对多对象关系映射,是两端都能将对方加载上来,双向都需要加上标签映射。
要注意:
生成中间表名必须一样
生成中间表字段必须一样
代码如下所示。
Role.hbm.xml
<class name="com.bjpowernode.hibernate.Role" table="t_role"> <id name="id"> <generator class="native" /> </id> <property name="name"/> <set name="users" table="t_user_role"> <key column="role_id"/> <many-to-many class="com.bjpowernode.hibernate.User" column="user_id"/> </set> </class>
User.hbm.xml
<class name="com.bjpowernode.hibernate.User"table="t_user" > <id name="id"> <generator class="native" /> </id> <property name="name"/> <set name="roles" table="t_user_role"> <key column="user_id"/> <many-to-many class="com.bjpowernode.hibernate.Role" column="role_id"/> </set> </class>
区别:单向多对多和双向多对多存储结构没有任何的区别,但他们的映射文件是有区别的,加载过程是不同的。
3 关系映射总结
综上所述,可以看出,同一类映射,无论是单向还是双向,他们的存储结构是相同的,之所以映射文件不同,是因为加载时不同(在增删改时)。
无论是多对一、一对多、一对一还是多对一,A对B,A就是主动方,A主动想要了解B的情况,这样把B设置到A端。而双向,也就是A对B,A想了解B的信息,而B也想了解A的信息,那就要同时把A设置到B端了。
【相关推荐】
1. 特别推荐:“php程序员工具箱”V0.1版本下载
2. Java免费视频教程
3. 阿里巴巴Java开发手册
The above is the detailed content of Detailed explanation of examples of two types of Hibernate class mapping. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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.

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

Hibernate is an open source ORM framework that binds the data mapping between relational databases and Java programs to each other, making it easier for developers to access data in the database. Using the Hibernate framework can greatly reduce the work of writing SQL statements and improve the development efficiency and reusability of applications. Let's introduce the Hibernate framework from the following aspects. 1. Advantages of the Hibernate framework: object-relational mapping, hiding database access details, making development

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)

Caching helps reduce database network calls when executing queries. Level 1 cache and session linking. It is implemented implicitly. The first level cache exists until the session object exists. Once the session object is terminated/closed, there will be no cached objects. Second level cache works for multiple session objects. It is linked with the session factory. Second level cache objects are available to all sessions using a single session factory. These cache objects will be terminated when a specific session factory is closed. To implement the second level cache we need to add the following dependencies to use the second level cache. <!--https://mvnrepository.com/artifact/net.sf.ehcache/ehcache--><de

1. hibernate mapping configures the class tag, which is used to establish the relationship between the class and the table. name: class name, table: table name id tag, the corresponding relationship between the attribute being established and the primary key in the table property, and the establishment of ordinary attributes in the class. The corresponding relationship with the fields of the table (1) First of all, we must learn how to write the mapping configuration file. Everyone must know that the written mapping configuration file should be in the same package as the entity class, and the name should be class name.hbm.xml. So we need to create a Customer.hbm.xml file under the com.meimeixia.hibernate.demo01 package, but how should its constraints be written? Available in Hiberna
