When expressing a relationship in Hibernate, add the following annotations such as @OneToMany.
User.java
@Getter
@Setter
@NoArgsConstructor
@Entity
public class User {
public User(Long id, String name, Integer age, Set<Post> posts){
this.id = id;
this.name = name;
this.age = age;
this.posts = posts;
}
private Long id;
private String name;
private Integer age;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user" )
private Set<Post> posts = new HashSet<>();
}
Posts are annotated with @OneToMany. Either FetchType.EAGER or FetchType.LAZY can be specified in fetch of this argument. By the way, if not specified, it defaults to LAZY. So what's the difference between the two?
In the case of LAZY, Posts will not be loaded when the User instance is called in Hibernate. In other words, user.getPosts () will be Null. On the other hand, in the case of EAGER, the object with the relation is also read when the instance is called, so user.getPosts () is not Null either.
LAZY: You need to be careful about Null, but you can use memory efficiently. EAGER: Not null, but heavy load.
The default LAZY is recommended for Spring Boot. In the previous example, it is possible that Posts will be displayed only when the User logs in, so it seems preferable to prepare a separate Repository class and specify the read conditions.
LAZY is basically recommended, but sometimes it is useful to use EAGER to prevent NullPointerExceptions errors.
https://howtoprogramwithjava.com/hibernate-eager-vs-lazy-fetch-type/
Recommended Posts