1

I have two entities with one to many relationships:

public class User {
    @Id
    @GeneratedValue
    private Long id;
    private String username;
    private String phoneNumber;
    private Timestamp creationDate;
    @OneToMany(mappedBy = "user")
    private List<Role> roles;

}

public class Role {
    @Id
    @GeneratedValue
    private long id;
    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    private User user;

}

but when I call get method to load user information I can see in the log file that additional query to retrieve user's roles also called. How can I prevent it with spring data rest?

5
  • try setting fetchType as LAZY Commented Feb 26, 2018 at 10:41
  • it doesn't work with spring-data-rest entities. Also fetchType is lazy by default. Commented Feb 26, 2018 at 10:43
  • the default lazy stackoverflow.com/questions/46684015/… Commented Feb 26, 2018 at 10:52
  • What you have to shown is how you retrieve and manipulate the User entities. As a hint, enable the SQL logs you could see whether the query for the roles is performed in a second time Commented Feb 26, 2018 at 10:54
  • actually, I found that problem with show_sql property turned on, but thanks for advice. Commented Feb 26, 2018 at 10:55

2 Answers 2

2

Define FetchType to LAZY as below.

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;

By default, JPA fetchType for ManyToOne is EAGER. Refer here

Sign up to request clarification or add additional context in comments.

1 Comment

I tried that approach and it didn't work. Actually, I loaded all users(not roles) so not sure how the mapping of child entity will fix that...
1

Since you are using SDR, to prevent Roles from loading when you get Users you can:

1) Create repository for Roles. If you had one check if it exported (@RepositoryRestResource(exported = true) - by default just add this annotation without this parameter).

2) Or make User projection without roles:

@Projection(name = "justUser", types = User.class)
public interface JustUser {
    String getUsername();
    String getPhoneNumber();
    Timestamp getCreationDate();
}

Then use it in your request, like this:

GET /users?projection=justUser

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.