Jpa / Hibernate - 是否可以使用查询参数多次获取同一实体的树

时间:2015-10-27 09:01:05

标签: java spring hibernate jpa spring-boot

我的表service可以多次引用自己的实体。要获取服务树,我需要使用查询参数。

如果可行的话,我想只根据配置/注释来做。最后,我想要一个服务,其中包含另一个包含其他服务的服务。

每项服务之间的连接如下:

服务包含name, location, region.

Service1有一个location。此位置应与name of service2匹配。 Service2region,此区域应与name of service3匹配。

这里只是查询的前两部分:

@Transactional
public interface ServiceRepository extends CrudRepository<Service, Long>{

    @Query("SELECT s1, s2 FROM Service s1, Service s2"
            + " WHERE"
            + " s1.name = :serviceLocationName"
            + " AND s1.serviceType = :location"
            + " AND s1.area = s2.name"
            + " AND s2.serviceType = :region")
    public List<Service> testLocationRegion(
            @Param("serviceLocationName")String serviceLocationName,
            @Param("location")String location,
            @Param("region")String region);
}

这是我的实体:

@Entity
@Table(name = "SERVICE")
public class Service {

    public Service(){
        super();
    }

    //should be the mapping
    @OneToOne(mappedBy="service", fetch = FetchType.EAGER)
    private Service serviceRegion;

    @ManyToOne(fetch = FetchType.EAGER)
    private Service service;

    @Id
    @Column(name = "ID", nullable = false)
    private long id;

    @Column(name = "TITLE", insertable = false)
    private String title;

    @Column(name = "NAME")
    private String name;

    @Column(name = "LOCATION", insertable = false)
    private String location;

    @Column(name = "REGION", insertable = false)
    private String region;

//...

是否有办法实现此配置/注释,如果没有,我如何使用jpqlhibernate criteria实现此功能。

我的预期结果应该是服务树。

service 
|
 -> serviceLocation
    |
     ->serviceRegion

感谢任何建议

我也和@JoinColumn一起尝试过。但这不是一个有效的例子。

0 个答案:

没有答案