简体   繁体   中英

Hibernate native query method

So, I am doing an assignment where I have a 2 Entities - User and Car with a OneToMany relationship respectively.

Therefore User will posses a List of Cars .

I need to implement a controller method, which will be displaying all the cars that user posses by UserId(which is a foreign key for Car entity)

Method is: [GET] - /users/{id}/cars

Right now If I am simply seleting all users I am getting raw JSON 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"
  }]
}

But I don't want to have a data about User, because it's not necessary as I am already specifing in get request that I am selecting a certain user. So I wan't to have only the list of cars that certain user posses.

The JSON output that I am looking for is:

{  
   "Id":"1",
   "make":"BMW",
   "model":"760",
   "numberplate":"123FFF"
},
{  
   "Id":"2",
   "make":"Opel",
   "model":"Astra",
   "numberplate":"789BFX"
}

ATM I have a CarRepository which extends JpaRepository with a method:

@Query(value = "SELECT * FROM Cars c where c.id = :id", nativeQuery = true)
    Optional<Car> findByUserId(@Param("id") Long id);

But for some reason I am getting a "java.util.NoSuchElementException: No value present" exception. When trying to use findByUserId Query method.

Controller part that doesnt work:

@GetMapping("/users/{id}/cars")
    public ResponseEntity<Car> getAllCarsByUserId(@PathVariable("id") Long id)
    {
        return ResponseEntity.ok(carRepository.findByUserId(id).get());
    }

Repository:

public interface CarRepository extends JpaRepository<Car, Long> {

    @Query(value = "SELECT * FROM Cars c where c.user_id = :id", nativeQuery = true)
    List<Car> findByUserId(@Param("id") Long id);

}

Could you be so cool to help me to geet done with that issue?

Thank You in advance! :)

Here is my understanding of what you are looking for:

Repositoy

@Repository
public interface CarRepository extends JpaRepository<Car, Long> {

  @Query(value = "SELECT * FROM T_CARS c where c.USER_ID = :id", nativeQuery = true)
  Collection<Car> findByUserId(@Param("id") Long id);

}

Controller

class UserController {

  @Autowired
  private CarRepository carRepository;

  @GetMapping("/users/{id}/cars")
  public ResponseEntity<Collection<Car>> getAllCarsByUserId(@PathVariable("id") Long id) {
      return ResponseEntity.ok(carRepository.findByUserId(id));
  }

}

I hope that it works for you :)

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