how2j.cn

下载区
文件名 文件大小
hibernate.rar 6m

工具版本兼容问题
Hibernate有缓存机制,可以通过用id作为key把product对象保存在缓存中

同时hibernate也提供Query的查询方式。假设数据库中有100条记录,其中有30条记录在缓存中,但是使用Query的list方法,就会所有的100条数据都从数据库中查询,而无视这30条缓存中的记录

N+1是什么意思呢,首先执行一条sql语句,去查询这100条记录,但是,只返回这100条记录的ID
然后再根据id,进行进一步查询。

如果id在缓存中,就从缓存中获取product对象了,否则再从数据库中获取


步骤 1 : 先运行,看到效果,再学习   
步骤 2 : 模仿和排错   
步骤 3 : Hibernate使用Iterator实现N 1   

步骤 1 :

先运行,看到效果,再学习

edit
老规矩,先下载右上角的可运行项目,配置运行起来,确认可用之后,再学习做了哪些步骤以达到这样的效果。
在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。
模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较正确答案 ( 可运行项目 ) 和自己的代码,来定位问题所在。
采用这种方式,学习有效果,排错有效率,可以较为明显地提升学习速度,跨过学习路上的各个槛。

推荐使用diffmerge软件,进行文件夹比较。把你自己做的项目文件夹,和我的可运行项目文件夹进行比较。
这个软件很牛逼的,可以知道文件夹里哪两个文件不对,并且很明显地标记出来
这里提供了绿色安装和使用教程:diffmerge 下载和使用教程
步骤 3 :

Hibernate使用Iterator实现N 1

edit
首先通过Query的iterator把所有满足条件的Product的id查出来

然后再通过it.next()查询每一个对象
如果这个对象在缓存中,就直接从缓存中取了
否则就从数据库中获取

N+1中的1,就是指只返回id的SQL语句,N指的是如果在缓存中找不到对应的数据,就到数据库中去查
Hibernate使用Iterator实现N 1
package com.how2java.test; import java.util.Iterator; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.how2java.pojo.Product; public class TestHibernate { public static void main(String[] args) { SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session s = sf.openSession(); s.beginTransaction(); String name = "iphone"; Query q =s.createQuery("from Product p where p.name like ?"); q.setString(0, "%"+name+"%"); Iterator<Product> it= q.iterate(); while(it.hasNext()){ Product p =it.next(); System.out.println(p.getName()); } s.getTransaction().commit(); s.close(); sf.close(); } }


HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。


问答区域    
2023-08-24 在Chat-gpt上查到的关于N+1的问题
Shu_Enryu




①N+1 中的N是代表查询的主体的个数。 +1的意思是每个主体都需要进行一次额外的查询。 如果,你检索了6个实体,主查询的数量是6(N=6),而每个实体的关联数据都会导致额外的查询。因此,总的查询次数会变成:6(主查询)+ 6(每个实体的关联数据查询)+ 1(主查询的关联数据查询)= 13。 ②N+1问题产生的原因 在Hibernate中,默认情况下,关联数据是采用懒加载(Lazy Loading)机制来获取的,这意味着在主查询时并不会立即加载关联数据,而是在访问这些关联数据时才会触发加载。 这种懒加载的设计是为了优化性能,因为有时候关联数据可能很庞大,如果一开始就加载所有的关联数据,可能会导致不必要的性能开销和内存占用。然而,这也可能导致N+1查询问题。 举个例子,假设你有一个"订单"实体,每个订单关联着一个"客户"实体。当你从数据库中查询6个订单时,每个订单关联的客户数据默认情况下是没有被加载的。如果你在遍历这6个订单并访问每个订单的客户数据时,Hibernate会针对每个订单执行额外的查询来获取其关联的客户数据。 ③如果想要观察到从缓存直接提取的这个现象,需要在查询之前先提取一次。 代码在“代码”中有提供,现象在“异常”里面,数据库在上传的“截图”里。 可以看到我的检索的主体有6个,查询执行了13次。但id为18,19,20的SQL并没有在后面进行,也就是说从它们三个已经缓存中存在了,然后获取。 感觉chat-gpt解释的第①个问题还是有点牵强,有没有懂的大神指正啊?
加载中
package com.how2java.test;

import java.util.Iterator;

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

import com.how2java.pojo.Product;

public class TestHibernate {
	public static void main(String[] args) {
		SessionFactory sf = new Configuration().configure().buildSessionFactory();
		Session s = sf.openSession();
		s.beginTransaction();
		System.out.println("假设我们已经将id为18,19,20的元素取出");
		Product id18 = (Product)s.get(Product.class, 18);
		Product id19 = (Product)s.get(Product.class, 19);
		Product id20 = (Product)s.get(Product.class, 20);
		
		
		String name = "PP";
        
        Query q =s.createQuery("from Product p where p.name like ?");
         
        q.setString(0, "%"+name+"%");
		
		System.out.println("仔细检查输出结果, 发现id为18,19,20的元素没有进行SQL");
		Iterator<Product> it = q.iterate();
		while (it.hasNext()) {
			Product p = it.next();
			System.out.println(p.getName());
		}

		s.getTransaction().commit();
		s.close();
		sf.close();
	}

}
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
情報: MLog clients using java 1.4+ standard logging. [木 8 24 15:49:32 JST 2023]
情報: Initializing c3p0-0.9.1 [built 16-January-2007 14:46:42; debug? true; trace: 10] [木 8 24 15:49:32 JST 2023]
情報: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@71210d71 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@d70f7066 [ acquireIncrement -> 2, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge32cayammdod1i8m5w9|7f416310, idleConnectionTestPeriod -> 3000, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 50000, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 100, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@7ff1f643 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 1hge32cayammdod1i8m5w9|13c27452, jdbcUrl -> jdbc:mysql://localhost:3306/test?characterEncoding=GBK, properties -> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 1hge32cayammdod1i8m5w9|101df177, numHelperThreads -> 3 ] [木 8 24 15:49:32 JST 2023]
假设我们已经将id为18,19,20的元素取出
Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product_ product0_ where product0_.id=?
Hibernate: select users0_.pid as pid0_1_, users0_.uid as uid1_, user1_.id as id3_0_, user1_.name as name3_0_ from user_product users0_ inner join user_ user1_ on users0_.uid=user1_.id where users0_.pid=?
Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product_ product0_ where product0_.id=?
Hibernate: select users0_.pid as pid0_1_, users0_.uid as uid1_, user1_.id as id3_0_, user1_.name as name3_0_ from user_product users0_ inner join user_ user1_ on users0_.uid=user1_.id where users0_.pid=?
Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product_ product0_ where product0_.id=?
Hibernate: select users0_.pid as pid0_1_, users0_.uid as uid1_, user1_.id as id3_0_, user1_.name as name3_0_ from user_product users0_ inner join user_ user1_ on users0_.uid=user1_.id where users0_.pid=?
仔细检查输出结果, 发现id为18,19,20的元素没有进行SQL
Hibernate: select product0_.id as col_0_0_ from product_ product0_ where product0_.name like ?
PP4
PP2
PP5
Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product_ product0_ where product0_.id=?
Hibernate: select users0_.pid as pid0_1_, users0_.uid as uid1_, user1_.id as id3_0_, user1_.name as name3_0_ from user_product users0_ inner join user_ user1_ on users0_.uid=user1_.id where users0_.pid=?
PP6
Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product_ product0_ where product0_.id=?
Hibernate: select users0_.pid as pid0_1_, users0_.uid as uid1_, user1_.id as id3_0_, user1_.name as name3_0_ from user_product users0_ inner join user_ user1_ on users0_.uid=user1_.id where users0_.pid=?
PP3
Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product_ product0_ where product0_.id=?
Hibernate: select users0_.pid as pid0_1_, users0_.uid as uid1_, user1_.id as id3_0_, user1_.name as name3_0_ from user_product users0_ inner join user_ user1_ on users0_.uid=user1_.id where users0_.pid=?
PP1





回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2020-04-22 为什么这个没有在缓存中获取而是执行了两次
hz52




如题 下面是控制台内容 Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product product0_ where product0_.id=? Hibernate: select users0_.pid as pid0_1_, users0_.uid as uid1_, user1_.id as id3_0_, user1_.name as name3_0_ from user_product users0_ inner join user user1_ on users0_.uid=user1_.id where users0_.pid=? 5 : iphone0 Hibernate: select product0_.id as col_0_0_ from product product0_ where product0_.id=? 5 : iphone0
加载中
Product p=(Product) s.get(Product.class, 5);
		System.out.println(p.id+" : "+p.name);
		Query q=s.createQuery("from Product p1 where p1.id=?");
		q.setInteger(0, 5);
		Iterator<Product> it=q.iterate();
		while(it.hasNext())
		{
			Product p1=it.next();
			System.out.println(p1.id+" : "+p1.name);
		}

							


1 个答案

四方1
答案时间:2023-07-31
我也是这个问题。不过我知道为啥。感觉站长的代码有点问题,不应该用getname,用getid就没事,getname的话,缓存里没有name所以要额外找一次。



回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2020-03-29 这个标题N+1有点疑惑啊
2018-12-05 你们的控制台打印的语句多不多?
2017-12-07 我觉得用下面的代码能更清楚的讲明白N+1的效果, 也就是从缓存中读取的效果


提问太多,页面渲染太慢,为了加快渲染速度,本页最多只显示几条提问。还有 4 条以前的提问,请 点击查看

提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
关于 JAVA 框架-Hibernate-N+1 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 578362961
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: https://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图