java - JPQL 查询导致多次往返数据库甚至 EAGER 和 JOIN FETCH
问题描述
我试图理解为什么我的查询会导致对数据库的 2 次调用。据我了解,我在查询中有一个带有 FETCH 关键字的 EAGER 加载,这应该会导致一次往返,但在下面这不是这种情况。感谢任何提示!
TypedQuery<Recipe> query = em.createQuery("SELECT r FROM Recipe r" +
" LEFT JOIN FETCH r.ingredients ri LEFT JOIN FETCH r.author a WHERE r.id= :id ", Recipe.class);
query.setParameter("id", id);
食谱类:
@Entity
@Table(name = "recipes")
@Getter
@Setter
@NoArgsConstructor
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
@JsonSerialize(using = RecipeMetaSerializer.class)
public class Recipe implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private Long id;
@ManyToOne(fetch = FetchType.EAGER)
private User author;
@OneToMany(
mappedBy = "recipe",
orphanRemoval = true,
fetch = FetchType.LAZY,
cascade = CascadeType.PERSIST
)
private List<RecipeIngredient> ingredients;
}
首先加入表RecipeIngredient:
@Entity
@Table(name="recipe_ingredients")
@Getter
@Setter
@NoArgsConstructor
@IdClass(RecipeIngredientId.class)
public class RecipeIngredient implements Serializable {
@Id
@ManyToOne(fetch= FetchType.EAGER)
private Recipe recipe;
@Id
@ManyToOne(fetch= FetchType.LAZY)
private Ingredient ingredient;
.....
}
第二个连接表:
@Entity
@Table(name = "users")
@Getter
@Setter
@NoArgsConstructor
public class User {
@Id
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "author")
private List<Recipe> recipes;
}
JPQL 查询导致以下两个对 DB 的调用,都包含对表 users 的左外连接:
select recipe0_.id as id1_6_0_, ingredient1_.ingredient_id as ingredie4_5_0__, user2_.img_url as img_url2_7_2_, user2_.username as username4_7_2_ from recipes recipe0_ **left outer join recipe_ingredients** ingredient1_ on recipe0_.id=ingredient1_.recipe_id **left outer join users** user2_ on recipe0_.author_id=user2_.id where recipe0_.id=?
select recipe0_.id as id1_6_0_, user1_.username as username4_7_1_ from recipes recipe0_ **left outer join users** user1_ on recipe0_.author_id=user1_.id where recipe0_.id=?
我希望加入用户表一次,而不是两次。有什么想法吗?谢谢!
解决方案
看起来第二个查询是针对Recipe recipe
这里的
@Entity
public class RecipeIngredient {
@Id
@ManyToOne(fetch= FetchType.EAGER)
private Recipe recipe;
}
只需使用FetchType.LAZY
@Entity
public class RecipeIngredient {
@Id
@ManyToOne(fetch= FetchType.LAZY)
private Recipe recipe;
}
如果您使用entityManager.find()
方法,您将不会有第二个查询。将recipe
已经在缓存中。
但是对于 JPQL,Hibernate 认为recipe
在第一个查询中找到的 不在缓存中,所以它再次获取它(即使它是相同的recipe
)。
建议
始终在任何地方使用延迟加载。在运行时禁用急切加载是不可能的。此外,如果您想更改eager
为lazy
.
推荐阅读
- json - 如何在 Microsoft Excel 中解析 JSON 或 CSV 字符串中的单个值?还是谷歌表格?
- javascript - 搜索栏:包含在列表项标签中的锚标签不可选择
- python - 将变量提供给 SQL 语句的 Python 问题。cur.execute(None, {'id': test}) cx_Oracle.DatabaseError: ORA-00911: 无效字符
- neo4j - 如何在neo4j中使用每个路径的路径ID导出数据
- azure-active-directory - 尝试使用 Msal 从控制台应用程序访问 Web API 时出现 MsalServiceException:'AADSTS501461
- scala - 具有上限值的案例类 .copy
- c++ - 获取依赖类型的可变参数模板参数包
- android - 添加了 android 变量和 Glide 的 URL
- riak - Riak 中 node_gets 和 vnode_gets 的区别
- python - 如何将数据保存到 .txt 文件中而不是创建新文件(Python)