Search code examples
javasqlspring-bootjpajpql

How to select multiple data in one SQL Query in JAVA JPA Spring Boot


I have User entity which holds List of Groups. Each group has two lists: submissionDocumentType and reviewDocumentType. What is the most efficient way to get List of GroupDetails objects for User using as few as possible database calls (see final expected result below)?

User.java

public class User {
@Id
@GeneratedValue(generator ="uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;

@ManyToMany(mappedBy = "users")
private Set<UserGroup> userGroups;

UserGroup

public class UserGroup {

@Id
@GeneratedValue(generator ="uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;

@ManyToMany(mappedBy = "submissionUserGroups")
private List <DocumentType> submissionDocumentType;


@ManyToMany(mappedBy = "reviewUserGroups")
private List <DocumentType> reviewDocumentType;

GroupDetails.java

public class GroupDetails {

private String groupTitle;
private List<String> reviewDocTypes;
private List<String> submitDocTypes;

Expected response from GET method

[
{
    "groupTitle": "Group one",
    "reviewDocTypes": [
        "Prasymas Eazy",
        "Prasymas Tgwz",
        "Prasymas Gien",
        "Prasymas Docs",
        "Prasymas Ecyd",
        "Prasymas Sjvz"
    ],
    "submitDocTypes": [
        "Prasymas Buor",
        "Prasymas Kzhc",
        "Prasymas Zokx",
        "Prasymas Vvtb",
        "Prasymas Docs",
        "Prasymas Lutj",
        "atostogu prasymas"
    ]
},
{
    "groupTitle": "Group two",
    "reviewDocTypes": [
        "Prasymas Tgwz",
        "Prasymas Gien",
        "Prasymas Kzhc",
        "Prasymas Kblj",
        "Prasymas Docs",
        "Prasymas Ecyd"
    ],
    "submitDocTypes": [
        "Prasymas Tgwz",
        "Prasymas Wmwx",
        "Prasymas Buor",
        "Prasymas Gien",
        "Prasymas Kzhc",
        "Prasymas Kblj",
        "Prasymas Docs",
        "Prasymas Xdau",
        "Prasymas Lutj",
        "Prasymas Ecyd",
        "atostogu prasymas"
    ]
}
]

Solution

  • I guess you can do it in one query. As you can see in the reference documentation :

    Spring Data allows modeling dedicated return types, to more selectively retrieve partial views of the managed aggregates.The easiest way to limit the result of the queries to only the name attributes is by declaring an interface that exposes accessor methods for the properties to be read

    So we can fetch the result using a query method like this :

    interface UserRepository extends Repository<User, String> {
        Collection<GroupDetails> findById(String userId);
    }