JPA多个查询而不是一个

时间:2013-04-30 14:00:13

标签: java hibernate jpa

我有两个实体:

@Entity
@Table(name = "ACCOUNT")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class MyCloudAccount implements Serializable {

    ...

    @OneToMany(mappedBy = "account", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<ServerInstance> servers = new HashSet<ServerInstance>();

    ...
}

@Entity
@Table(name = "SERVER_INSTANCE")
public class ServerInstance implements Serializable {

    ...

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ACCOUNT_ID")
    private MyCloudAccount account;

    ...
}

我通过此代码收到所有帐户:

StringBuilder sql = new StringBuilder();
sql.append("SELECT e FROM ");
sql.append(persistentClass.getName());
sql.append(" e");
return entityManager.createQuery(sql.toString()).getResultList();

这会为帐户生成一个查询,为服务器生成N个查询,而不是一个具有外部联接的查询。如何强制JPA以最佳方式进行查询?

1 个答案:

答案 0 :(得分:2)

我发现使用Java持久性查询语言

更方便

你可以这样做:

@NamedQueries{
    @NamedQuery(name="myQuery" query="SELECT a FROM MyCloudAccount JOIN FETCH a.servers")
}
public class MyCloudAccount{
    ...
}

然后你可以做

TypedQuery<MyCloudAccount> query = em.createNamedQuery("MyCloudAccount.myQuery", MyCloudAccount.class);
List<MyCloudAccount> results = query.getResultList();

修改 您实际上已经在使用JPQL。问题的关键是使用JOIN FECTH命令。