我有一个实体如下:
public class User {
@Id
@Column
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idgenx_gx")
private Long id;
@Column
private String name;
@Column
private String lastname;
@ManyToOne(fetch = FetchType.LAZY, optional = true)
private Country country;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Organization organization;
}
它的dto:
public class UserDTO {
private Long id;
private String name;
private String lastname;
private String organizationName;
private Country country;
}
使用JPA Criteria API我想从数据库中选择所有用户,所以我做了如下:
final CriteriaBuilder builder = getCriteriaBuilder();
final CriteriaQuery<UserDTO> query = builder.createQuery(UserDTO.class);
final Root<User> from = query.from(User.class);
Join<User, Organization> joinOrg = from.join(User_.organization, JoinType.LEFT);
query.multiselect(from.get(User_.id), from.get(User_.name), from.get(User_.lastname),
joinOrg.get(Organization_.name), from.get(User_.country));
query.distinct(true);
return getEntityManager().createQuery(query).getResultList();
这个问题是它只返回country不为null的用户,因为生成的查询包含:inner join Country on User.country=Country.id
其中必须加入。
我该如何解决这个问题?
答案 0 :(得分:1)
您可以尝试通过添加联接来强制JoinType.LEFT
,例如:
Join<User, Country> joinCountry = from.join("country", JoinType.LEFT);
query.multiselect(from.get("id"), from.get("name"), from.get("lastname")
,joinOrg.get("name"), joinCountry );
无论如何,这个问题可能在其他地方,因为我无法在我的环境中重新产生这个问题。