【问题标题】:findAll not fetching OnetoMany fields values in Spring JPAfindAll 没有在 Spring JPA 中获取 OnetoMany 字段值
【发布时间】:2021-10-08 01:03:13
【问题描述】:

我正在开发一个 Spring Boot 应用程序,我正在使用 OneToMany 注释在我的另一个实体对象中嵌套对象列表。

但是在获取我使用 JPA 发布的数据时,在使用 findAll 时,OneToMany 字段返回 null。 我能够以有组织的方式发布数据并成功创建表格,但无法获取完整的数据,即grants_list

有人可以帮忙吗?

下面贴出代码:

ClientModel.java

public class ClientModel {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private BigInteger id;
    private String client_id;
    private String client_name;
    private String client_secret;
    @OneToMany(targetEntity = ClientGrants.class, cascade = CascadeType.ALL)
    private List<ClientGrants> grants_list;
    private String status;
    @CreatedDate
    @Temporal(TemporalType.DATE)
    private Date created_at;
    private String created_by;
    @LastModifiedDate
    @Temporal(TemporalType.DATE)
    private Date modified_at;
    private String modified_by = null;
    private Date deleted_At = null;
    private String deleted_by = null;


//getters and setters
   // constructor
    }

ClientGrants.java

public class ClientGrants {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private BigInteger id;
    private String entity_id;
    private String entity_name;
    private String status;
    @CreatedDate
    @Temporal(TemporalType.DATE)
    private Date created_at;
    private String created_by;
    @LastModifiedDate
    @Temporal(TemporalType.DATE)
    private Date modified_at;
    private String modified_by = null;
    private Date deleted_At = null;
    private String deleted_by = null;
//getters and setters
// constructor
}

My service method:

public Map<String, Object> getClients() {
        List<ClientModel> clients = clientRepository.findAll();
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("clients", clients);
        return responseMap;

    }

My Repository:

@Repository
public interface ClientRepository extends JpaRepository<ClientModel, BigInteger> {


}

有人可以帮忙吗? 谢谢

【问题讨论】:

  • 注意 java 命名约定。不要在变量名中使用 _。使用驼峰式
  • 感谢您的提示

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


【解决方案1】:

在 JPA 中,OneToMany 集合默认是延迟获取的,使用 hibernate 时所有集合都是延迟获取的,因此,在您尝试访问它们之前,它们将为空。您可以通过将映射更改为

来覆盖它
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)

你可以省略targetEntity,它是由被映射的类型推断出来的。

【讨论】:

    猜你喜欢
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2019-10-12
    相关资源
    最近更新 更多