I have 2 entities, User and Post. Using spring-boot
Users have many posts and Posts have one user. I annotated them as shown below. When I make an request for all posts in DB, It returns a list for Posts like below.
POST 1 and POST 2 have same User property and only one of them can fetch related User. When another Post has another different User for the first time, it can fetch that User.
I need full User object for each Post entry.
(I use Lombok [@Data])
Result (json)
[{
"id": 1,
"context": "POST 1",
"user": {
"id": 1,
"username": "user_1",
"picture": "pic_1",
"is_active": true,
"is_verified": true
}
},
{
"id": 2,
"context": "POST 2",
"user": 1,
},
{
"id": 3,
"context": "POST 3",
"user": {
"id": 2,
"username": "user_2",
"picture": "pic_2",
"is_active": true,
"is_verified": true
}
}]
Post.java
@Data
@Entity(name = "Post")
@Table(name = "post")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Post extends PersistentObject implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String context;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
@JsonIgnoreProperties(ignoreUnknown = true, value = {"password", "isActive", "isVerified", "blockedUsers"})
private User user;
}
User.java
@Data
@Entity(name = "User")
@Table(name = "user")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "posts", "following_locations", "blocked_users"})
@DynamicUpdate
public class User extends PersistentObject implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonProperty("username")
private String username;
@JsonProperty("password")
private String password;
@JsonProperty("picture")
private String picture;
@JsonProperty("is_active")
private Boolean isActive;
@JsonProperty("is_verified")
private Boolean isVerified;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JsonBackReference(value = "user_posts")
@JsonProperty("posts")
private List<Post> posts;
@OneToMany(mappedBy = "id", fetch = FetchType.LAZY)
@JsonBackReference(value = "user_following_locations")
@JsonProperty("following_locations")
public List<Location> followingLocations;
@OneToMany(mappedBy = "blocker", fetch = FetchType.LAZY)
@JsonProperty("blocked_users")
private List<BlockedUser> blockedUsers;
}