Spring Boot Rest API Returns Empty JSON Used with Lombok

Viewed 2329

I have Spring Boot Application with Web, JPA, H2, Web, Lombok dependency. I have entities as follows

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Getter
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer pageCount;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

}
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Getter
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String firstName;

    @Column
    private String lastName;

}

I am getting following JSON in repose for the /books REST endpoint

[
    {},
    {}
]

If I add getters and setters to entity it works fine. How can I get the actual values in response without adding getters setters as I am using @Data annotation

4 Answers

First of all , In spring it is not a good approach to return the entity object directly from a controller to be converted to json. Use the DTO approach so that you will always have a DTO object returned from the controller endpoint. This way you will have more control over the type and structure of data you want to retun from the endpoint.

Read here about the advantages of using a DTO .

Secondly, verify that your tables follow the basic spring jpa naming conventions or is same as the entity class names if not please add the @Table(name="") annotation to specify the table name. Check that data is being populated to your entity classes.

Remove the @Data annotation.

@Data should not be used on JPA Entities as Entity toString, equals, and hashCode methods need to be authored in a very specific manner. See here for details.

After searching a lot and looking on the answers to my question found a solution. If I run my spring boot app using java -jar from cmd it works fine. But not with IDE so issue was with IDE configuration.

I am using Eclipse IDE

Right Click on your project -> Properties

Then from Properties window

Java Compiler -> Annotation Processing -> Enable Annotation Processing

This option should be checked then annotations gets processed. I followed https://www.baeldung.com/lombok-ide from Tinku's answer on this question.

enter image description here

If you are using Eclipse check to have Lombok installed:

enter image description here

Related