Home > other >  Spring Data JPA: How to get the data from a nested 1-to-1 relationship?
Spring Data JPA: How to get the data from a nested 1-to-1 relationship?

Time:10-12

I'm relatively new to spring data jpa but i've been working with orm in the typescript world (typeorm/mikrorm). I have a simple 1-to-1 uni-directional relationship between a Book and a Picture.

My Book entinty

public class Book implements Serializable {
    ...
    @JsonIgnore
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="picture_id", nullable = false)
    private Picture picture;
}

The picture entity

public class Picture implements Serializable {
    ....
    @Id
    private Long id;
    @Column(nullable = false)
    private String url;
}

So I've created my services and I'm able to persist the data into the database. For the database i'm using mysql which is running on my local machine.

In my controllers, On the GetMapping i want to get the book with it's picture for example when i hit the server at http//:127.0.0.1/api/v1/books/book/1 I want to get the following as response:

Postman

{
    "id": 4,
    "title": "book1",
    "picture":{
        "id": 1,
        "url": "url1" 
    }
}

Instead I'm getting the following response:

{
    "id": 4,
    "title": "book1"
}

Here is what I've tried in the BookController.java and it seems not working, at some point I'm not getting the picture object for the book.

@RestController
@RequestMapping(path = "/api/v1/books")
@RequiredArgsConstructor
public class BookController {
    private final BookService bookService;
    private final PictureService pictureService;
....

    @GetMapping("/book/{bookId}")
    public ResponseEntity<Book> getBook(@PathVariable("bookId") Long bookId){
        return ResponseEntity.status(200).body(this.bookService.getBook(bookId));
    }

}

CodePudding user response:

that is because you told Jackson to ignore that property. Just remove the @JsonIgnore annotation

  • Related