Skip to content
Advertisement

findAll not fetching OnetoMany fields values in Spring JPA

I am working on a Spring Boot app and I am using a OneToMany annotation to have nested object list inside my another entity object.

But while fetching the data that I posted using JPA,while using findAll the OneToMany field is getting returned null. I am able to post the data and its sucessfully creating the tables in an organised way but not able to fetch the complete data i.e grants_list.

Can someone help?

Posting the code below:

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> {


}

Can someone help? Thanks

Advertisement

Answer

In JPA, OneToMany collections are by default fetched lazily, using hibernate all collections are fetched lazily, therefore, until you attempt to access them they will be null. You can override this by changing the mapping to

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)

You can omit the targetEntity, it’s inferred by the type being mapped.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement