Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Springboot API returns empty response

I built a simple Springboot API which is hooked up to a H2 db that contains some test data. However when I hit the API endpoint I get an empty response.

[{}]

When I debug my application the user object that is returned by the controller contains the user I am expecting.

Debugged user object

UserController.java

@RestController
@RequestMapping("api/user")
public class UserController {

    private UserService userService;

    public UserController(@Autowired UserService userService){
        this.userService = userService;
    }

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public Set<User> getAllUsers(){
        final Set<User> users = userService.getAllUsers();
        return users;
    }
}

UserRepo.java

public interface UserRepository extends CrudRepository<User, Long> {

    @Query("SELECT usr from User usr")
    Set<User> getAllUsers();
}

UserService.java

public interface UserService {

    Set<User> getAllUsers();
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository repository;

    public UserServiceImpl(@Autowired UserRepository userRepository){
        this.repository = userRepository;
    }

    @Override
    public Set<User> getAllUsers(){
        final Set<User> users = repository.getAllUsers();
        return users;
    }
}

User.java

@Entity
@Getter
public class User {

    @Id
    private Long id;
    private String username;
    private String firstname;
    private String lastname;
    private String email;
    private String role;
    private String premium;
}
like image 505
Richard Payne Avatar asked Sep 18 '26 10:09

Richard Payne


2 Answers

You'll have to set the class members of User public to allow jackson serialise them, i.e.,

// User.java
@Entity
public class User {
    @Id
    public Long id;
    public String username;
    public String firstname;
    public String lastname;
    public String email;
    public String role;
    public String premium;
}

Note: if you'd like to not serialise a field, use @JsonIgnore instead of setting it as private, e.g.,

@Entity
public class User {
    ...
    @JsonIgnore
    public String role;
    ...
}
like image 188
Tony L. Avatar answered Sep 19 '26 22:09

Tony L.


This was a rather strange issue of which I am still unable to say which. However, removing lombok's @getter and @setter annotations then implementing traditional ones fixed this issue.

like image 23
Richard Payne Avatar answered Sep 20 '26 00:09

Richard Payne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!