3

当我在 hql 中使用构造函数作为打击时:

String jpql = "select top 10 new Result(a,b) from A a,B b where a.id=b.id" Query query = entityManager.createQuery(jpql);

控制台打印出 20 条 sql 语句。不是我预期的一条。但是当构造函数只包含表 A 和 B 的字段时,它只执行一个 sql。我想知道为什么会这样。感谢您的帮助!

抱歉不清楚,这里有一些细节:

List list = baseDao.findListByQL("select new List(a,b) from A a,B b where a.id=b.id");

方法“findListByQL”刚刚使用“Query query = entityManager.createQuery(jpql);”调用了一个方法 得到一些结果。

和休眠打印一些sql如下:

Hibernate: select a0_.id as col_0_0_, b1_.id as col_1_0_ from dbo.A a0_, dbo.B b1_ where a0_.id=b1_.id
Hibernate: select a0_.id as id103_0_, a0_.name as name103_0_ from dbo.A a0_ where a0_.id=?
Hibernate: select b0_.id as id106_0_, b0_.score as score106_0_ from dbo.B b0_ where b0_.id=?
Hibernate: select a0_.id as id103_0_, a0_.name as name103_0_ from dbo.A a0_ where a0_.id=?
Hibernate: select b0_.id as id106_0_, b0_.score as score106_0_ from dbo.B b0_ where b0_.id=?
Hibernate: select a0_.id as id103_0_, a0_.name as name103_0_ from dbo.A a0_ where a0_.id=?
Hibernate: select b0_.id as id106_0_, b0_.score as score106_0_ from dbo.B b0_ where b0_.id=?
Hibernate: select a0_.id as id103_0_, a0_.name as name103_0_ from dbo.A a0_ where a0_.id=?
Hibernate: select b0_.id as id106_0_, b0_.score as score106_0_ from dbo.B b0_ where b0_.id=?
Hibernate: select a0_.id as id103_0_, a0_.name as name103_0_ from dbo.A a0_ where a0_.id=?
Hibernate: select b0_.id as id106_0_, b0_.score as score106_0_ from dbo.B b0_ where b0_.id=?
Hibernate: select a0_.id as id103_0_, a0_.name as name103_0_ from dbo.A a0_ where a0_.id=?
Hibernate: select b0_.id as id106_0_, b0_.score as score106_0_ from dbo.B b0_ where b0_.id=?
Hibernate: select a0_.id as id103_0_, a0_.name as name103_0_ from dbo.A a0_ where a0_.id=?
Hibernate: select b0_.id as id106_0_, b0_.score as score106_0_ from dbo.B b0_ where b0_.id=?
Hibernate: select a0_.id as id103_0_, a0_.name as name103_0_ from dbo.A a0_ where a0_.id=?
Hibernate: select b0_.id as id106_0_, b0_.score as score106_0_ from dbo.B b0_ where b0_.id=?
Hibernate: select a0_.id as id103_0_, a0_.name as name103_0_ from dbo.A a0_ where a0_.id=?
Hibernate: select b0_.id as id106_0_, b0_.score as score106_0_ from dbo.B b0_ where b0_.id=?

但是当 "new List" 构造函数使用一些字段属性如 "new List(a.name,b.score)" 时,它只打印一个 sql。

4

1 回答 1

0

当您执行以下 HQL 时:

select new List(a,b) from A a,B b where a.id=b.i

您正在返回整个实体 A 和 B。即使没有看到这些实体的代码,它们也可能映射了一些EAGER 关系@ManyToOne,例如or @OneToOne

在一个 EAGER 关系中,每次你用这个关系点击一个实体,它都会把这个实体关联起来。这可以解释这多个 SQL。

但是,当您执行以下 HQL 时:

select new List(a.name,b.score) from A a,B b where a.id=b.i

您只返回一些字段。在这种情况下,EAGER 关系被“忽略”,因为您没有使用实体类。

如果您提供有关实体类 A 和 B 的更多详细信息,我们可以指定关于您的实体中的这种行为以及如何改变这种行为的确切解释。

于 2015-08-19T10:19:30.980 回答