SpringData JPA多表查询返回自定义的实体

       在使用SpringData JPA查询的时候,一般都是返回Entity相关的结果。前段时间,在开发的 时候遇到了2个表联合查询,返回自定义的实体类,这个问题楼主也是查了好多资料,才得以解决,现在分享给大家,不足之处,敬请之出。

2个实体类UserInfo、UserLoginInfo 分别对应mysql的表user_info和user_login_info,实体类只截取了部分字段

@Data
@Entity
@Table(name = "user_info")
@JsonSerialize
public class UserInfo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private String uuid;

    @Column(name = "usr_sys_id")
    private String usrSysId;//用户号

    @Column(name = "reg_time")
    private String regTime;//注册时间
}
@Table(name = "user_login_info")
@Entity
@Data
@JsonSerialize
public class UserLoginInfo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Long uuid;

    @Column(name = "usr_sys_id")
    private String usrSysId;//用户号

    private String email; //邮箱

    @JsonIgnore
    @Column(name = "email_valid_stat")
    private String emailValidStat;// 邮箱状态

    @JsonIgnore
    @Column(name="user_type")
    private String userType;//用户类型
}

自定义的实体类UserInfoVo

@Data
@AllArgsConstructor
@JsonSerialize
public class UserInfoVo {
    
    private String usrSysId;
    
    private String email;
    
    private String loginName;
    
    private Integer stat;
    
    private String lstSuccTime;
    
    private String nationCode;
    
    private String phone;
    
    private String gender;

}

现在要根据usr_sys_id和usr_type两个字段,联表user_info和user_login_info查询用户相关的信息,返回类型结果是 UserInfoVo,

public interface UserLoginInfoRepository extends JpaRepository {

    Optional findByUsrSysId(String usrSysId);

    @Query(value = "SELECT new com.hylj.hust.vo.UserInfoVo( " +
            "uli.usrSysId , uli.email, uli.loginName, uli.stat, uli.lstSuccTime, ui.nationCode, ui.phone, ui.gender) " +
            "FROM UserLoginInfo uli inner join  UserInfo ui ON  " +
            "uli.usrSysId = ui.usrSysId AND uli.userType= :userType AND uli.usrSysId = :usrSysId", nativeQuery = false)
    Optional findByUsrSysIdAndUserType(@Param("usrSysId") String usrSysId, @Param("userType") String userType);
}

需要 注意的是,new com.hylj.hust.vo.UserInfoVo 此处应该写全类名,nativeQuery 要设置为false

你可能感兴趣的:(Java,springboot,springdata,jpa)