我正在尝试使用Spring Projections,但无法使其正常工作。我需要将OneToOne关系作为投影,因此就像投影中的投影一样。看起来它将起作用,但是嵌套类未在Json中映射。我的实体:
@Entity(name = "user")
@Data
public class User {
@Id
private String id;
@NotNull
private LocalDateTime creationDate;
private LocalDateTime lastLoginDate;
private LocalDateTime lastPasswordChangeDate;
private String name;
@PrimaryKeyJoinColumn
@OneToOne(cascade = CascadeType.ALL)
private ProviderCredentials providerCredentials;
private boolean deleted;
private String adminAccountId;
@Entity(name = "provider_credentials")
@Data
public class ProviderCredentials {
@Id
private String idUser;
private String loginName;
@NotNull
private String password;
@NotNull
private long deletedAt;
private String passwordVersion;
}
预测是这些:
public interface SecondaryUserVO {
String getId();
String getName();
LocalDateTime getCreationDate();
LocalDateTime getLastLoginDate();
LocalDateTime getLastPasswordChangeDate();
ProviderCredentialsDTO getProviderCredentials();
}
public interface ProviderCredentialsDTO {
String getIdUser();
}
最奇怪的是正在执行的sql很有意义。
select
user0_.id as col_0_0_,
user0_.name as col_1_0_,
user0_.creationDate as col_2_0_,
user0_.lastLoginDate as col_3_0_,
user0_.lastPasswordChangeDate as col_4_0_,
providercr1_.idUser as col_5_0_,
providercr1_.idUser as iduser1_1_,
providercr1_.deleted_at as deleted_2_1_,
providercr1_.login_name as login_na3_1_,
providercr1_.password as password4_1_,
providercr1_.password_version as password5_1_
from
user user0_
left outer join
provider_credentials providercr1_
on user0_.id=providercr1_.idUser
where
user0_.admin_account_id=?
但是json始终是:
[
{
"creationDate": "2020-06-10T15:55:42.523397",
"name": "John Lennon",
"id": "257ef67d-ca9d-48ac-8638-824376ec1cd2"
}
]
我想要的是:
[
{
"creationDate": "2020-06-10T15:55:42.523397",
"name": "John Lennon",
"id": "257ef67d-ca9d-48ac-8638-824376ec1cd2",
"providerCredentials" : {"idUser" : "257ef67d-ca9d-48ac-8638-824376ec1cd2"}
}
]
我尝试了不同的方法,但是似乎没有任何效果。遵循Spring页面上的官方说明,但没有用。
您可以在JPQL qeury中使用Dto。在一个简单的示例下面。
@Entity
@Data
public class User {
@Id
private Long id;
private String name;
@OneToOne
private Creds creds;
}
@Entity
@Data
public class Creds {
@Id
private Long id;
private String password;
}
// if you need projection like this
@Data
public static class UserDto {
private Long userId;
private String name;
private String password;
public UserDto(Long userId, String name, String password) {
this.userId = userId;
this.name = name;
this.password = password;
}
}
{
// this gives you UserDto
Query query = em.createQuery("select new uz.owl.dto.foo.UserDto(u.id, u.name, c.password) from User u join u.creds c");
}