I’m trying a GET request that uses hateoas RepresentationModelAssembler in Spring Boot project with this method:
@GetMapping("/{postId}")
public EntityModel<Post> one(@PathVariable Long postId) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new CustomExceptionHandling.ResourceNotFoundException("Post", "ID", postId));
return assembler.toModel(post);
}
and this is my assembler
@Component
public static class PostModelAssembler implements RepresentationModelAssembler<Post, EntityModel<Post>> {
@Override
public @NonNull EntityModel<Post> toModel(@NonNull Post post) {
return EntityModel.of(post,
linkTo(methodOn(PostController.class).one(post.getId())).withSelfRel()
);
}
}
this is Post.java:
@Entity(name = "post")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "created_at")
@Builder.Default
private LocalDateTime createdAt = LocalDateTime.now();
private String caption;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
}
Received Response:
{
“createdAt”: “2023-01-01T12:00:00”,
“caption”: “Caption 1”,
“_links”: {
“self”: {
“href”: “http://localhost:8080/posts/1”
}
}
}
Expected Response:
a similar one that includes user and id.
NOTE: I tried using @JsonInclude(JsonInclude.Include.ALWAYS
and Include.NOT_NULL)
, @JsonProperty
, @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
, removed lombok and added public getters and setters, made id fields public, but nothing worked
EXTRA NOTE: when I added @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
it produced the error: “Type definition error: [simple type, class com.example.demo.model.Post]” and somewhere below it: “Invalid Object Id definition for com.example.demo.model.Post: cannot find property with name ‘id’ (through reference chain: org.springframework.hateoas.EntityModel[“content”])”
Ehab is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.