在我的应用程序中,我有四个标签 -
- '客户' | customer_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 类
@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";
}
我的 View “汽车”显示有关汽车的信息,例如汽车类型、型号等。到目前为止,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;
}
关于java - 如何在 java/hibernate/mysql 中连接 2 个或更多表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61920021/