java - 如何在 java/hibernate/mysql 中加入 2 个或更多表?
问题描述
在我的应用程序中,我有四个表格 -
- '客户' | 客户 ID PK,...
- '办公室' | office_id PK, ...
- '汽车' | car_id PK, office_id FK, ...
- '出租' | Rental_id PK, customer_id FK, car_id FK, ...
我为汽车和办公室写实体
@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 吗?
解决方案
我找到了解决方案。如果有人会遇到这种问题,解决方案很简单。在 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;
}
推荐阅读
- algorithm - 拓扑排序和汉密尔顿路径?
- vba - E_ACCESSDENIED "General Access denied error" /CreateObject("Vbscript") 在 office 365 VBA 环境下被阻止
- sql - 动态日期范围的 SQL 透视图
- python - 在 iPadOS 上的 Pyto 中使用 Rubicon
- sql - Rails Brakeman:Arel 的 SQL 注入
- python - 如何在 Pandas 中对同一列下的值求和
- javascript - 带有占位符的 JavaScript 字符串标记器正则表达式
- c - 无法理解 pid->tasks[] list 的用途
- xamarin - 如何将“安装”目标添加到 Xamarin.UWP .csproj 文件?
- google-sheets - 如何在 Google 表格中按类别求和并操纵结果?