java - 如何在 java/hibernate/mysql 中连接 2 个或更多表?

标签 java mysql spring hibernate jpa

在我的应用程序中,我有四个标签 -

  • '客户' | 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/

相关文章:

php - 使用 $_POST 插入带有 PDO 准备语句的 MySQL 数据库

mysql - 简单的 mysql 查询需要 16 秒以上

java - Spring批处理元数据表的问题

java - 在android中将数据从一个文件复制到另一个文件非常慢?

Java字符串匹配: € symbol is â¬

mysql - 在 Ubuntu 20.04 上安装 mysql2 gem 版本 '0.3.21' 时出错

java - Apache Tiles 和 Spring MVC 中的全局异常页面

java.lang.IllegalArgumentException : warning no match for this type name: ru. sbt.filial.cards.aspect.SomeBean [Xlint:invalidAbsoluteTypeName]

java - 在线程中进行 DAO 注入(inject)

java - native 镜像的 Spring Boot 构建镜像失败