jpa 是否可以在一个查询中不使用@OneToMany注解而获得所有子实体?

pepwfjgg  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(98)

假设我有以下实体:

*UserEntities

@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;
}
  • 以及UserHobbyEntity
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;
}

现在我想让所有用户(使用分页)在不使用@OneToMany的情况下拥有他/她的爱好,并Map到名为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;
    }
}

当我调用下面的repository方法时,spring Boot 说**”Could not determine appropriate instantiation strategy - no matching constructor found and one or more arguments does not define alias for bean-injection”**:

@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);
}

当我将List<String> hobbies更改为String hobby时,它可以工作,但我想获得所有爱好:

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;
        
    }
}
68bkxrlz

68bkxrlz1#

你不能在jpql表达式的select子句中使用子查询(见此),这解释了错误。
如果你想实现这个结果,你必须声明一对多的关系,但是你可以将它标记为惰性,这样除非显式请求,否则它不会被获取。

相关问题