gpt4 book ai didi

java - 在spring data jpa中使用join查询多表的列

转载 作者:行者123 更新时间:2023-12-02 12:00:24 25 4
gpt4 key购买 nike

描述:

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

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时出现错误;如果我为'typeName'添加@Transient,它可以成功保存,但是当我查询实体Shop_Employee时,'typeName'的值为空。

最佳答案

您的查询应返回两个对象 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;

关于java - 在spring data jpa中使用join查询多表的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47300459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com