gpt4 book ai didi

mysql - jparepository 接口(interface)上的自定义方法

转载 作者:行者123 更新时间:2023-11-29 15:40:19 25 4
gpt4 key购买 nike

我有两个实体:人和汽车。我想使用 JpaRepository 按人员 ID 列出汽车。我创建了双向关系,如以下代码

public class Person {
.
.
.
@OneToMany(mapped = "person")
@JsonManagedReference
private List<Car> cars;
.
.
.
}

以及汽车的实体

public class Car {
.
.
.
@ManyToOne
@JoinColumn(name = "person_id")
@JsonBackReference
private Person person;
}

所以,我通过以下方式实现了 JpaRepository 到 CarRepository

public interface CarRepository extends JpaRepository<Car, Long> {
@Query("SELECT c FROM Car c WHERE c.person_id = :person_id")
public List<Car> getCarsByidPerson(@Param("person_id")long idPerson);
}

字段 person_id 存在于数据库的汽车表中,但我在 spring-boot 启动时收到以下错误消息

org.hibernate.QueryException: could not resolve property: person_id of: com.jpa_study.Car [SELECT c FROM com.jpa_study.Car c WHERE c.person_id = :person_id]

我需要在选择时使用 join 吗?或者这是可能的?

最佳答案

我明白了!

确实需要 JOIN on QUERY。按照代码修复

public interface CarRepository extends JpaRepository<Car, Long> {
@Query("SELECT c FROM Car c INNER JOIN Person p ON (Car.person.id = Person.id) WHERE p.id = :person_id")
public List<Car> getCarsByidPerson(@Param("person_id")long idPerson);
}

关于mysql - jparepository 接口(interface)上的自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57742345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com