我正在使用Java EE 7和Java 8以及Hibernate(5.0.X)在Wildfly 10.1.0-Final上,我需要使用投影将JPQL查询结果加载到DTO中,但我找不到任何关于如何加载子集合DTO的文档。
例如,如果我有以下用户、角色和权限实体:
@Entity
public class User
{
@Id
private long id;
private String userName;
private String firstName;
private String lastName;
private JobTitle jobTitle;
private Email email;
private boolean isRemote;
@ManyToMany
private Set<Tag> tags;
@ManyToMany
// @JoinColumn definitions...
private Set<Role> roles;
// getters/setters...
}
@Entity
public class Role
{
@Id
private long id;
private String name;
private String description;
@ManyToMany
// @JoinColumn definitions...
private Set<Privilege> privileges;
// getters/setters...
}
@Entity
public class Privilege
{
@Id
private long id;
private String key;
private String name;
private String description;
// getters/setters...
}
我希望使用投影将一些查询结果加载到以下不可变的DTO中(假设所有DTO都已根据id实现了hashCode和equals):
public class UserDTO
{
private final long id;
private final String userName;
private final Set<RoleDTO> roles = new HashSet<>();
public UserDTO(long id, String userName, Collection<RoleDTO> roles) // not sure if this is correct for projection..
{
this.id = id;
this.userName = userName;
this.roles.addAll(roles);
}
public Set<Role> getRoles()
{
return Collections.unmodifiableSet(roles);
}
// getters
}
public class RoleDTO
{
private final long id;
private final String name;
private final Set<PrivilegeDTO> privileges = new HashSet<>();
public RoleDTO(long id, String name, Set<PrivilegeDTO> privileges)
{
this.id = id;
this.name = name;
this.privileges.addAll(privileges);
}
public Set<Privilege> getPrivileges()
{
return Collections.unmodifiableSet(privileges);
}
// other getters
}
public class PrivilegeDTO
{
private final long id;
private final String key;
public PrivilegeDTO(long id, String key)
{
this.id = id;
this.key = key;
}
// getters
}
要实现这个目标,JPQL查询的结构应该是什么样子的?我相信我可以通过连接操作完成任务,然后将结果处理成DTO对象,类似于以下代码(加载ID最新的50个用户):
List<Object[]> results = em.createQuery("SELECT u.id, u.userName, r.id, "
+ "r.name, p.id, p.key FROM User u "
+ "LEFT JOIN u.roles r "
+ "LEFT JOIN r.privileges p "
+ "ORDER BY u.id DESC")
.setMaxResults(50).getResultList();
Map<Long, UserDTO> users = new HashMap<>();
Map<Long, RoleDTO> roles = new HashMap<>();
Map<Long, PrivilegeDTO> privileges = new HashMap<>();
for(Object[] objArray : results)
{
// process these into the DTO objects,
}
重构需要从PrivilegeDTO对象开始,然后是RoleDTO,最后是UserDTO。这将允许不可变性,因为在构建RoleDTO对象时需要PrivilegeDTO对象,否则您将不得不稍后添加它们,这意味着RoleDTO不是不可变的。
使用Streams进行操作可能会很有趣,但我更喜欢能够直接从查询中构建它,这似乎会更快。这是否可能?
非常感谢!