我有以下课程:
@Entity
public class TestContentElementResponse
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@OneToMany(mappedBy = "testContentElementResponse", cascade = CascadeType.ALL, orphanRemoval = false)
private Set<ResponseAttribute> associatedResponseAttributes = new HashSet<ResponseAttribute>();
@ManyToOne
@JoinColumn(name = "userfulltestId", referencedColumnName = "id", nullable = false)
private UserFullTest userFullTest;
@ManyToOne
@JoinColumn(name = "testContentElementId", referencedColumnName = "id", nullable = false)
private TestContentElement testContentElement;
@OneToOne(cascade = CascadeType.ALL)
private TestContentElementScore testContentElementScore;
@ManyToOne
@JoinColumn(name = "userId", referencedColumnName = "id", nullable = false)
private User user;
Run Code Online (Sandbox Code Playgroud)
TestContentElementResponse.class 表示测试中的一个用户响应。一项测试可以包含 30 个问题,因此每个用户有 30 个回答。
现在,我想为一个用户调用所有 TestContentElementResponse(通用 ID 为 UserFullTestId),并为每个 TestContentElementResponse 调用所有 ResponseAttributes。
我可以使用条件查询来完成此操作,但我不确定是否使用 SELECT 或 JOIN FetchMode。我确实知道 JOIN 将对数据库进行一次大调用,而 SELECT 将对数据库进行多次快速调用。但是,我不知道哪些因素可以帮助我决定哪种方法是最佳的。
(当然,我会进行测试,但这只会回答哪种方法是最佳的,不会解释原因)
帮助将不胜感激
这是一个很好的讨论,并有一些具体的例子:
http://www.mkyong.com/hibernate/hibernate-fetching-strategies-examples/
如果您使用“原始 SQL”(SQL 语句或存储过程)进行编码,答案通常是显而易见的:单个复杂的“select/join”查询几乎总是优于多个查询。
就 Hibernate 而言,答案是“join”通常比 select 更好。
建议:修改 spring.xml 以启用“show_sql”,并比较结果。
附:
另外两个很好的链接:
| 归档时间: |
|
| 查看次数: |
9420 次 |
| 最近记录: |