首页 > 解决方案 > 如何在 java/hibernate/mysql 中加入 2 个或更多表?

问题描述

在我的应用程序中,我有四个表格 -

我为汽车和办公室写实体

@Entity
public class Car {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int car_id;

private int office_id;
...

@Entity
public class Office {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int office_id;
...

我使用 Hibernate 和 JPA 从数据库中检索数据,所以我编写了 CarRepository 来进行查询

public interface CarRepository extends JpaRepository<Car, Integer> {

@Query(value = "SELECT c FROM Car c WHERE c.car_type = ?1")
List<Car> findCarByType(String type);

@Query(value = "SELECT c FROM Car c WHERE c.brand = ?1")
List<Car> findCarByBrand(String brand);

@Query(value = "SELECT c FROM Car c WHERE c.model = ?1")
List<Car> findCarByModel(String model);

@Query(value = "SELECT c FROM Car c WHERE c.price = ?1")
List<Car> findCarByPrice(int price);

@Query(value = "SELECT o FROM Office o, Car c WHERE c.office_id = o.office_id")
List<Office> findCarOffice();

}

这是我的汽车控制器类

@Controller
@RequestMapping(path = "/cars")
public class CarController {

@Autowired
private CarRepository carRepository;

List<Car> cars;

@GetMapping(path = "/get")
public String getAllCars(ModelMap modelMap) {

    cars = carRepository.findAll();
    modelMap.addAttribute("cars", cars);
    return "car";
}

我的视图“汽车”显示有关汽车类型、型号等汽车的信息。到目前为止,everythink 工作正常,但我必须从“办公室”表中检索并打印每辆汽车所在的“城市”。我的问题是我该怎么做?如何加入表格?什么是最好的方法?

我应该使用注释@ManyToOne 吗?

标签: javamysqlspringhibernatejpa

解决方案


我找到了解决方案。如果有人会遇到这种问题,解决方案很简单。在 CarRepository 中,您可以编写:

public interface CarRepository extends JpaRepository<Car, Integer> {

@Query(value = "SELECT c.car_id, c.office_id, c.car_type, c.brand, c.model, 
c.production_year, c.production_year, c.horsepower, c.seats, c.price, o.city FROM 
Office o, Car c WHERE c.office_id = o.office_id")
List<Object[]> findCarOffice();
}

您可以在 Controller 中显示这些数据

@GetMapping(path = "/getcaroffice")
@ResponseBody
public Iterable<Object[]> getAllCars() {

    Iterable<Object[]> carOffice = carRepository.findCarOffice();
    return carOffice;
}

推荐阅读