列出一对多关系中的JPA where子句

时间:2017-11-01 21:21:19

标签: java angularjs repository spring-data-jpa one-to-many

实验室包含一些服务器。我要做的是列出属于实验室的服务器。例如,获取属于“abc”lab的服务器,其id为1。

以下代码获取所有服务器:

@RequestMapping(value = "servers", method = RequestMethod.GET)
public List<Server> list() {
    return serverRepository.findAll();
}

Entitiy:

public class Server {

    @Id
    @GeneratedValue
    @Column(name = "ID")
    private Long id;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="LAB_ID", referencedColumnName = "ID")
    private Lab lab;
}

Entitiy;

public class Lab {

    @Id
    @GeneratedValue
    @Column(name = "ID")
    private Long id;

    @NotNull
    @Column(name = "LAB_NAME")
    private String labName;

    @OneToMany
    private Set<Server> servers;
}

角:

$scope.getServers= function () {
    $http.get('services/servers').then(function (response) {
        $scope.servers= response.data;
    });
};

存储库:

public interface ServerRepository extends JpaRepository<Server, Long>{

}

1 个答案:

答案 0 :(得分:1)

像这样编辑你的映射

Lab实体

@OneToMany(mappedBy="lab")
private Set<Server> servers;

Server实体

@ManyToOne
private Lab lab;

现在您可以像这样编写 JPQL

public interface ServerRepository extends JpaRepository<Server, Long>{

    @Query("Select s from Server s where s.lab.labName = :name and s.lab.id = :id")
    List<Server> getServers(@Param("name") String name, @Param("id") Long id);

}