Spring Repository接口:使用外键查找记录

时间:2018-03-20 01:35:34

标签: java spring-boot spring-data-jpa

我想使用两个外键来获取现有记录。

基本上我所拥有的是一条具有起点和目的地的路线(两者都是终端实体)。

我的目标是创建一个函数来使用我的origin和destination作为查询中的条件来获取Route记录。我目前不知道如何使用Spring Data JPA。

以下是我的实体和关系映射。

@Entity
@Table(name = "ROUTE")
public class Route implements Serializable {

    public Route() {}

    public Route(Terminal origin, Terminal destination, int totalKM) {
        this.origin = origin;
        this.destination = destination;
        this.totalKM = totalKM;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "ROUTE_ID")
    private long id;

    @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.REMOVE})
    @JoinColumn(name = "TERMINAL_ORIGIN_ID")
    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="id")
    private Terminal origin;

    @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.REMOVE})
    @JoinColumn(name = "TERMINAL_DESTINATION_ID")
    private Terminal destination;

    //...Getters and Setters
}

@Entity
@Table(name = "TERMINAL")
public class Terminal implements Serializable {

    public Terminal() {}

    public Terminal(String name, Town town, List<Route> routes) {
        this.name = name;
        this.town = town;
        this.routes = routes;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "TERMINAL_ID")
    private long id;

    private String name;

    @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.REMOVE})
    @JoinColumn(name = "TOWN_ID")
    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="id")
    private Town town;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Route> routes;

    //...Getters and Setters
}

现在我想在Route Repository中找到类似findbyOriginAndDestination的内容。我想尽可能避免在DB中取两次,所以我想在我的存储库层创建一个函数来使用我的origin和destination来获取现有记录(如果有的话)

@Repository
public interface RouteRepository extends JpaRepository<Route, Long> {

    Route findByOriginAndDestination(long originId, long destinationId);

}

1 个答案:

答案 0 :(得分:1)

您可以通过Query Property expressions

指定相关实体的列作为查询条件

所以它可能是工作

@Repository
public interface RouteRepository extends JpaRepository<Route, Long> {

    Route findByOrigin_IdAndDestination_Id(long originId, long destinationId);

}