查询多表'连接在spring数据jpa中的列

时间:2017-11-15 06:06:32

标签: java spring-mvc spring-boot spring-data-jpa

说明:

我有两个表,Shop_EmployeeShop_Employee_Type。我想在显示员工详细信息时直接显示typeName,但我不想在这两个实体之间配置关系(OneToManyManyToOne)。因为这会加载所有Shop_Employee_Type列的值,但这些值对我来说毫无用处,我只需要typeName Shop_Employee_Type。 以下是我的代码,但它不起作用。

ShopEmployeeType:

@Entity
@Data
//@DynamicUpdate
public class ShopEmployeeType {
    @Id
    private String typeId;
    private String shopId;
    private String typeName;
    private Integer typeStatus;
    private String typeDescription;
}

Shop_Employee:

@Entity
@Data
public class ShopEmployee {

    @Id
    private  String employeeId;
    private String shopId;
    private String typeId;
    private String name;
    private String code;
    private String phone;
    private Integer status;
    private String idcardNumber;
    private String image;
    //@Transient
    private String typeName;

    public ShopEmployee() {
    }
}

存储库:

@Query(value = "select u.*,t.type_name from shop_employee u inner join shop_employee_type t on u.type_id=t.type_id", nativeQuery = true)
List<ShopEmployee> findAllData();

这可以按照我的意愿显示typeName,但是当我保存新实体Shop_Employee时会出现错误;如果我为&#39; typeName&#39;添加@Transient,则可以成功保存,但&#39; typeName&#39;的值当我查询实体Shop_Employee时,它为null。

1 个答案:

答案 0 :(得分:1)

您的查询应该返回两个对象Shop_Employee和一个String,因此返回结果不应该是List<ShopEmployee>它应该是:

@Query(value = "select u.*, t.type_name from shop_employee ...", nativeQuery = true)
List<Object[]> findAllData();

然后您可以使用以下内容获取ShopEmployee

List<Object[]> list = findAllData();
for(Object[] obj : list){
   ShopEmployee shopEmployee = (ShopEmployee) obj[0];
   String type_name = (String) obj[1];
}

因此,在ShopEmployee实体中,您不需要使用:

//@Transient
//private String typeName;