Home Database Mysql Tutorial one-to-one双向关联之加载

one-to-one双向关联之加载

Jun 07, 2016 pm 03:28 PM
about association load

关于hibernate的加载方式有两种,一种是get加载,一种是load加载,load属于延迟加载,使用了动态代理。这不是我们所关心的,我们看一看一对一双向关联在加载时有什么特点,想要观察特点,不得不看hibernate为我们生成的sql语句。 husband类与上一篇没有变化

关于hibernate的加载方式有两种,一种是get加载,一种是load加载,load属于延迟加载,使用了动态代理。这不是我们所关心的,我们看一看一对一双向关联在加载时有什么特点,想要观察特点,不得不看hibernate为我们生成的sql语句。

husband类与上一篇没有变化如下:

/**
 * 
 */
package com.maybe.test_1;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

/**
 * @author MayBe
 *
 * function:
 */
@Entity
@Table(name="t_husband")
public class Husband {
	
	private Integer id;
	private String name;
	private Wife wife;
	@Id
	@GeneratedValue
	public Integer getId() {
		return id;
	}
	
	public String getName() {
		return name;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}

	@OneToOne(mappedBy="husband")
	public Wife getWife() {
		return wife;
	}

	public void setWife(Wife wife) {
		this.wife = wife;
	}
	

}
Copy after login

wife类也没有变化:

/**
 * 
 */
package com.maybe.test_1;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

/**
 * @author MayBe
 *
 * function:
 */
@Entity
@Table(name="t_wife")
public class Wife {
	
	private Integer id;
	private String name;
	private Husband husband;
	@Id
	@GeneratedValue
	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	@OneToOne
	public Husband getHusband() {
		return husband;
	}
	public void setHusband(Husband husband) {
		this.husband = husband;
	}
	

}
Copy after login

junit测试方法如下:
@Test
	public void One_to_oneLoadTest1(){
		//一对一双向关联

		Session s = sessionFacotry.getCurrentSession();
		
		s.beginTransaction();
		
		Husband hus = (Husband)s.get(Husband.class, 2);	

                System.out.println("*****************");
				
		Wife wif = (Wife)s.get(Wife.class, 3);


		s.getTransaction().commit();
	
	}
Copy after login

假设我们在数据中存在一个id为2的husband,他与id为2的wife是关联的。在数据库有一个id为3的wife,她与id为3的husband是关联的,我们运行一下这个测试,输出sql语句如下:
2014-02-04 16:52:20 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:182 - HHH000228: Running hbm2ddl schema update
   2014-02-04 16:52:20 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:193 - HHH000102: Fetching database metadata
   2014-02-04 16:52:20 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:205 - HHH000396: Updating schema
   2014-02-04 16:52:21 INFO org.hibernate.tool.hbm2ddl.TableMetadata:66 - HHH000261: Table found: hibernate.dbo.t_husband
   2014-02-04 16:52:21 INFO org.hibernate.tool.hbm2ddl.TableMetadata:67 - HHH000037: Columns: [id, name]
   2014-02-04 16:52:21 INFO org.hibernate.tool.hbm2ddl.TableMetadata:69 - HHH000108: Foreign keys: []
   2014-02-04 16:52:21 INFO org.hibernate.tool.hbm2ddl.TableMetadata:70 - HHH000126: Indexes: [pk__t_husban__3213e83f0f624af8]
   2014-02-04 16:52:21 INFO org.hibernate.tool.hbm2ddl.TableMetadata:66 - HHH000261: Table found: hibernate.dbo.t_wife
   2014-02-04 16:52:21 INFO org.hibernate.tool.hbm2ddl.TableMetadata:67 - HHH000037: Columns: [id, husband_id, name]
   2014-02-04 16:52:21 INFO org.hibernate.tool.hbm2ddl.TableMetadata:69 - HHH000108: Foreign keys: [fk_fi3kodkmubgryyblf4935y4dk]
   2014-02-04 16:52:21 INFO org.hibernate.tool.hbm2ddl.TableMetadata:70 - HHH000126: Indexes: [pk__t_wife__3213e83f1332dbdc]
   2014-02-04 16:52:21 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:242 - HHH000232: Schema update complete
   Hibernate: 
    select
        husband0_.id as id1_0_0_,
        husband0_.name as name2_0_0_,
        wife1_.id as id1_1_1_,
        wife1_.husband_id as husband_3_1_1_,
        wife1_.name as name2_1_1_ 
    from
        t_husband husband0_ 
    left outer join
        t_wife wife1_ 
            on husband0_.id=wife1_.husband_id 
    where
        husband0_.id=?
*****************
Hibernate: 
    select
        wife0_.id as id1_1_0_,
        wife0_.husband_id as husband_3_1_0_,
        wife0_.name as name2_1_0_,
        husband1_.id as id1_0_1_,
        husband1_.name as name2_0_1_ 
    from
        t_wife wife0_ 
    left outer join
        t_husband husband1_ 
            on wife0_.husband_id=husband1_.id 
    where
        wife0_.id=?
Hibernate: 
    select
        wife0_.id as id1_1_1_,
        wife0_.husband_id as husband_3_1_1_,
        wife0_.name as name2_1_1_,
        husband1_.id as id1_0_0_,
        husband1_.name as name2_0_0_ 
    from
        t_wife wife0_ 
    left outer join
        t_husband husband1_ 
            on wife0_.husband_id=husband1_.id 
    where
        wife0_.husband_id=?
Copy after login

首先加载husband对象时会把相关联的字段全部加载出来。

但是可以看出来加载wife表的时候会执行两次查询,虽然这两次查询的内容是一样的,但是第一次是查询出的是主表的信息,第二次是为了查出从表信息,这是hibernate的默认加载策略,因为t_wife表有外键,如果加载的表有从表,他会默认加载同时夹在两个表的信息。是否加载从表信息是由fetch进行设置的。

我们把wife类one-to-one新添加一个属性

/**
 * 
 */
package com.maybe.test_1;

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

/**
 * @author MayBe
 *
 * function:
 */
@Entity
@Table(name="t_wife")
public class Wife {
	
	private Integer id;
	private String name;
	private Husband husband;
	@Id
	@GeneratedValue
	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	@OneToOne(fetch=FetchType.LAZY)
	public Husband getHusband() {
		return husband;
	}
	public void setHusband(Husband husband) {
		this.husband = husband;
	}
	
}
Copy after login

我们把抓取方式改成懒抓取,加载输出如下所示:

2014-02-04 17:07:38 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:182 - HHH000228: Running hbm2ddl schema update
2014-02-04 17:07:38 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:193 - HHH000102: Fetching database metadata
2014-02-04 17:07:38 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:205 - HHH000396: Updating schema
2014-02-04 17:07:39 INFO org.hibernate.tool.hbm2ddl.TableMetadata:66 - HHH000261: Table found: hibernate.dbo.t_husband
2014-02-04 17:07:39 INFO org.hibernate.tool.hbm2ddl.TableMetadata:67 - HHH000037: Columns: [id, name]
2014-02-04 17:07:39 INFO org.hibernate.tool.hbm2ddl.TableMetadata:69 - HHH000108: Foreign keys: []
2014-02-04 17:07:39 INFO org.hibernate.tool.hbm2ddl.TableMetadata:70 - HHH000126: Indexes: [pk__t_husban__3213e83f0f624af8]
2014-02-04 17:07:40 INFO org.hibernate.tool.hbm2ddl.TableMetadata:66 - HHH000261: Table found: hibernate.dbo.t_wife
2014-02-04 17:07:40 INFO org.hibernate.tool.hbm2ddl.TableMetadata:67 - HHH000037: Columns: [id, husband_id, name]
2014-02-04 17:07:40 INFO org.hibernate.tool.hbm2ddl.TableMetadata:69 - HHH000108: Foreign keys: [fk_fi3kodkmubgryyblf4935y4dk]
2014-02-04 17:07:40 INFO org.hibernate.tool.hbm2ddl.TableMetadata:70 - HHH000126: Indexes: [pk__t_wife__3213e83f1332dbdc]
2014-02-04 17:07:40 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:242 - HHH000232: Schema update complete
Hibernate:
select
husband0_.id as id1_0_0_,
husband0_.name as name2_0_0_,
wife1_.id as id1_1_1_,
wife1_.husband_id as husband_3_1_1_,
wife1_.name as name2_1_1_
from
t_husband husband0_
left outer join
t_wife wife1_
on husband0_.id=wife1_.husband_id
where
husband0_.id=?
*****************
Hibernate:
select
wife0_.id as id1_1_0_,
wife0_.husband_id as husband_3_1_0_,
wife0_.name as name2_1_0_
from
t_wife wife0_
where
wife0_.id=?

这样wife类只加载自己主表的信息,不考虑从表的信息了( 当然把husband也是如此,可以自己去试试)。

hibernate默认的加载策略为eager加载,也就是急抓取,会把所关联的信息一次性全部得到,而lazy则都是在你用到从表才会去加载。

我们改变一下测试类内容:

	public void One_to_oneLoadTest1() {
		// 一对一双向关联

		Session s = sessionFacotry.getCurrentSession();

		s.beginTransaction();

		Husband hus = (Husband) s.get(Husband.class, 2);

    	

		System.out.println("*****************");
		Wife wif = (Wife) s.get(Wife.class, 3);
		

		System.out.println(wif.getHusband().getName());
		s.getTransaction().commit();

	}
Copy after login

输出如下:

2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:182 - HHH000228: Running hbm2ddl schema update
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:193 - HHH000102: Fetching database metadata
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:205 - HHH000396: Updating schema
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.TableMetadata:66 - HHH000261: Table found: hibernate.dbo.t_husband
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.TableMetadata:67 - HHH000037: Columns: [id, name]
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.TableMetadata:69 - HHH000108: Foreign keys: []
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.TableMetadata:70 - HHH000126: Indexes: [pk__t_husban__3213e83f0f624af8]
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.TableMetadata:66 - HHH000261: Table found: hibernate.dbo.t_wife
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.TableMetadata:67 - HHH000037: Columns: [id, husband_id, name]
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.TableMetadata:69 - HHH000108: Foreign keys: [fk_fi3kodkmubgryyblf4935y4dk]
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.TableMetadata:70 - HHH000126: Indexes: [pk__t_wife__3213e83f1332dbdc]
2014-02-04 17:10:51 INFO org.hibernate.tool.hbm2ddl.SchemaUpdate:242 - HHH000232: Schema update complete
Hibernate:
select
husband0_.id as id1_0_0_,
husband0_.name as name2_0_0_,
wife1_.id as id1_1_1_,
wife1_.husband_id as husband_3_1_1_,
wife1_.name as name2_1_1_
from
t_husband husband0_
left outer join
t_wife wife1_
on husband0_.id=wife1_.husband_id
where
husband0_.id=?
*****************
Hibernate:
select
wife0_.id as id1_1_0_,
wife0_.husband_id as husband_3_1_0_,
wife0_.name as name2_1_0_
from
t_wife wife0_
where
wife0_.id=?
Hibernate:
select
husband0_.id as id1_0_0_,
husband0_.name as name2_0_0_,
wife1_.id as id1_1_1_,
wife1_.husband_id as husband_3_1_1_,
wife1_.name as name2_1_1_
from
t_husband husband0_
left outer join
t_wife wife1_
on husband0_.id=wife1_.husband_id
where
husband0_.id=?
Hibernate:
select
wife0_.id as id1_1_0_,
wife0_.husband_id as husband_3_1_0_,
wife0_.name as name2_1_0_
from
t_wife wife0_
where
wife0_.husband_id=?
GossipMan

这样才会加载从表的信息,对于一些其他的语句,可能是hibernate自动生成的其他语句,但只要理解其中的思想就可以了,不要在意这些细节。

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

Error loading plugin in Illustrator [Fixed] Error loading plugin in Illustrator [Fixed] Feb 19, 2024 pm 12:00 PM

When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

Stremio subtitles not working; error loading subtitles Stremio subtitles not working; error loading subtitles Feb 24, 2024 am 09:50 AM

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

PHP implements infinite scroll loading PHP implements infinite scroll loading Jun 22, 2023 am 08:30 AM

With the development of the Internet, more and more web pages need to support scrolling loading, and infinite scrolling loading is one of them. It allows the page to continuously load new content, allowing users to browse the web more smoothly. In this article, we will introduce how to implement infinite scroll loading using PHP. 1. What is infinite scroll loading? Infinite scroll loading is a method of loading web content based on scroll bars. Its principle is that when the user scrolls to the bottom of the page, background data is asynchronously retrieved through AJAX to continuously load new content. This kind of loading method

Outlook freezes when inserting hyperlink Outlook freezes when inserting hyperlink Feb 19, 2024 pm 03:00 PM

If you encounter freezing issues when inserting hyperlinks into Outlook, it may be due to unstable network connections, old Outlook versions, interference from antivirus software, or add-in conflicts. These factors may cause Outlook to fail to handle hyperlink operations properly. Fix Outlook freezes when inserting hyperlinks Use the following fixes to fix Outlook freezes when inserting hyperlinks: Check installed add-ins Update Outlook Temporarily disable your antivirus software and then try creating a new user profile Fix Office apps Program Uninstall and reinstall Office Let’s get started. 1] Check the installed add-ins. It may be that an add-in installed in Outlook is causing the problem.

How to solve the problem that css cannot be loaded How to solve the problem that css cannot be loaded Oct 20, 2023 am 11:29 AM

The solutions to the problem that CSS cannot be loaded include checking the file path, checking the file content, clearing the browser cache, checking the server settings, using developer tools and checking the network connection. Detailed introduction: 1. Check the file path. First, please make sure the path of the CSS file is correct. If the CSS file is located in a different part or subdirectory of the website, you need to provide the correct path. If the CSS file is located in the root directory, the path should be direct. ; 2. Check the file content. If the path is correct, the problem may lie in the CSS file itself. Open the CSS file to check, etc.

What should I do if Windows 7 fails to load the USB driver? What should I do if Windows 7 fails to load the USB driver? Jul 11, 2023 am 08:13 AM

When installing the win7 system, some netizens encountered a situation where loading the USB driver failed. The USB device could not be recognized in the new win7 system, and common USB flash drives, mice and other devices could not be used. So what should I do if the installation of win7 fails to load the USB driver? Let Xiaobai teach you how to solve the problem of failure to load the USB driver when installing win7. Method 1: 1. First, we turn on the computer and enter the computer system, and check the computer system version in the computer system. Confirm whether the version of the computer system is consistent with the version of the device driver. 2. After confirming the driver version, connect the USB device to the computer system. The computer system shows that the device cannot connect to the system. 3. On the connection information page, click the Help button to view the help information. 4. If the computer department

How to use JavaScript to achieve the infinite scroll effect of automatically loading when scrolling to the bottom of the page? How to use JavaScript to achieve the infinite scroll effect of automatically loading when scrolling to the bottom of the page? Oct 27, 2023 pm 06:30 PM

How does JavaScript achieve the infinite scroll effect of automatically loading when scrolling to the bottom of the page? The infinite scroll effect is one of the common features in modern web development. It can automatically load more content when scrolling to the bottom of the page, allowing users to obtain more data or resources without manually clicking buttons or links. In this article, we'll explore how to use JavaScript to achieve this functionality and provide specific code examples. To achieve the infinite scrolling effect of automatically loading when scrolling to the bottom of the page, it is mainly divided into the following

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

See all articles