Let's assume that I have following entities:
让我们假设我有以下实体:
@Embeddable
@Data
public class ContactInformation implements Serializable {
@Column()
private String name;
@Column()
private String surname;
}
public class UserEntity {
@Embedded
private ContactInformation contactInformation;
@Column()
@NotEmpty
private String email;
@Column()
@NotEmpty
private String password;
}
public class UserHobbyEntity extends BaseEntity {
@Column(name = )
@NotEmpty
private String hobbyName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", referencedColumnName = "id")
@OnDelete(action = OnDeleteAction.CASCADE)
private UserEntity userEntity;
}
Now I want to get all users (using paginate) with his/her hobbies without using @OneToMany
and map to new class called SearchUserModel
:
现在,我希望获得所有用户(使用Pages)的兴趣爱好,而不使用@OneToMany,并映射到名为SearchUserModel的新类:
public class SearchUserModel {
private String userId;
private String name;
private String surname;
private List<String> hobbies;
public SearchUserModel(String userId,
String name, String surname,
List<String> hobbies) {
this.userId = userId;
this.name = name;
this.surname = surname;
this.hobbies = hobbies;
}
}
When I call the following repository method, spring boot says that " Could not determine appropriate instantiation strategy - no matching constructor found and one or more arguments did not define alias for bean-injection":
当我调用下面的存储库方法时,Spring Boot说“无法确定适当的实例化策略--找不到匹配的构造函数,并且一个或多个参数没有为Bean注入定义别名”:
@Repository
public interface UserRepository extends JpaRepository<UserEntity, String> {
@Query("""
SELECT new com.package.to.SearchUserModel(
user.id,
user.contactInformation.name,
user.contactInformation.surname,
(SELECT uh.hobbyName FROM UserHobbyEntity uh WHERE uh.userEntity.id = user.id)
)
FROM UserEntity user
WHERE user.id != :userId
""")
Page<SearchUserModel> getUsersForUser(String userId, Pageable pageable);
}
When i changed List<String> hobbies
to String hobby
, it works but I want to get all hobbies:
当我将列表<字符串>业余爱好更改为字符串业余爱好时,它起作用了,但我想获得所有的爱好:
public class SearchUserModel {
private String userId;
private String name;
private String surname;
// this is working but i want to get all hobbies for each user
public SearchUserModel(String userId,
String name, String surname,
String hobby) {
this.userId = userId;
this.name = name;
this.surname = surname;
}
}
更多回答
优秀答案推荐
You can't use subqueries in select clause of jpql expression (see this), this explains the error.
您不能在jpql表达式的SELECT子句中使用子查询(见此),这解释了错误。
You have to declare one to many relation anyway if you wish to achieve this result, but you can mark it as lazy, so it will not be fetched unless explicitly requested.
如果您希望实现此结果,则无论如何都必须声明一对多关系,但您可以将其标记为惰性,因此除非显式请求,否则不会获取它。
更多回答
我是一名优秀的程序员,十分优秀!