简体   繁体   中英

A query for JpaRepository to pass it to controller

I am doing a home assignment where I have 2 classes, which are User and Car . User has a OneToMany relationship to Car entity, therefore I need to implement a controller method, which will be selecting all cars of a special user (by ID)

I guess it has something todo with @Query annotation in UserRepository which extends JpaRepository . I am using a JpaRepository, which has generics.

Example: GET method - /users/{id}/cars

The data should be received in JSON format smth like that:

{
  "id":"1",
  "name":"Taavet Prulskih",
  "cars":[{
    "Id":"1",
    "make":"BMW",
    "model":"760",
    "numberplate":"123FFF"
  },
  {
    "Id":"2",
    "make":"Opel",
    "model":"Astra",
    "numberplate":"789BFX"
  }]
}

Question is: how does the query will be looking like?

You can use SpringData query methods, just create new method in CarRepository like that:

List<Car> findByUser_id(String id);

More examples in Query methods documentation .

You can create an UserDTO like this:

private static class UserDTO(){
private Long id;
private String name;
private List<Cars> cars;
//getters and setters
}

With JPA you can get the user that you want, in your repository:

User findByUserId(Long id)

And then fill the DTO like this:

UserDTO dto = new UserDTO();
User user = repository.findByUserId(id);
dto.setId(user.getUserId);
dto.setName(user.getName);
dto.setCars(user.getCars); //get the list of cars of the user and sets entire list to dto.cars

return dto;//finally return dto to controller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM