Spring Data Jap多表的列与联接

时间:2019-01-17 02:48:20

标签: java spring-data-jpa

我有两个表,user_info和user_password。我想在显示userInfo详细信息时直接显示typeName,但我不想配置这两个实体之间的关系(OneToMany或ManyToOne)。但这是行不通的,谁能帮助我?

@Data
@Entity
@DynamicUpdate
public class UserInfo {// user_info
    @Id
    private Integer id;
    private String name;
    private Byte gender;
    private String thirdPartId;
    private Integer age;
    private String telphone;
    private String registerMode;
}

@Entity
@Data
public class UserPassword {//user_password

    @Id
    private Integer id;
    private String encryptPassword;
    private Integer userId;


}


/** 
 * This is wish result entity
 * @author Mason
 * @version v1.0
 * @since 2019/1/16
 */
@Data
public class UserInfoPassword {
    private Integer id;
    private String name;
    private Byte gender;
    private String thirdPartId;
    private Integer age;
    private String telphone;
    private String registerMode;
    private String encryptPassword;
}

 @Query(value = "SELECT u.id,u.name,u.gender,u.third_part_id,u.age,u.telphone,u.register_mode,p.encrypt_password FROM user_info u " +
            "LEFT JOIN user_password p ON  u.id=p.user_id ", nativeQuery = true)
    List<UserInfoPassword > queryAll();
  

此返回类型UserInfoPassword将发生异常:   org.springframework.core.convert.ConverterNotFoundException:没有找到能够从类型[org.springframework.data.jpa.repository.query.AbstractJpaQuery $ TupleConverter $ TupleBackedMap]转换为类型[com.mason.sell.repository.model]的转换器。 UserInfoPassword]

如果我更改了返回对象,请执行以下操作:

 List<Object> userInfoPasswords = userInfoRepository.queryAll();
        for (Object o : userInfoPasswords) {
            UserInfoPassword uip = (UserInfoPassword) o;
            System.out.println(uip);
        }

然后将发生此异常:

  

java.lang.ClassCastException:[Ljava.lang.Object;无法转换为com.mason.sell.repository.model.UserInfoPassword

谁有很好的方法进行多表联接查询?

1 个答案:

答案 0 :(得分:0)

由于未提供任何映射,它将返回一个对象数组。

尝试一下:-

List<Object[]> userInfoPasswords = userInfoRepository.queryAll();
for (Object o[] : userInfoPasswords) {
    System.out.println("id: " + o[0]); // or call the setter of new UserInfoPassword
    System.out.println("name: " + o[1]);
    // ... and so on
}