如何使用复杂查询获取Ebean项目列表

时间:2015-01-07 09:03:56

标签: java playframework ebean

我有3个模型,城镇模型,有一个regionId字段,region为model,有一个stateId字段。

城镇模型:

@Entity
@Table(name = "town")
public class Town extends Model {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "town_id_seq")
    private Integer id;

    @Column(name = "region_id")
    private Integer regionId;
    ...

区域模型:

@Entity
@Table(name = "region")
public class Region extends Model {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "region_id_seq")
    private Long id;

    @Column(name = "state_id", nullable = false)
    private Long stateId;
    ...

州的模型:

@Entity
@Table(name = "state")
public class State extends Model {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "state_id_seq")
    private Integer id;
    ...

我需要获得特定州的城镇名单。在SQL中我会做这样的事情:

select * from town join region on town.region_id = region.id 
where region.state_id=15666

我取了两张桌子

public static List<Town> findAllInState(Integer stateId) {
    return Ebean.find(Town.class).fetch("region").findList();
}

但是当我尝试添加.where().eq("region.stateId", stateId)时,会显示BeanList size[0] hasMoreRows[false] list[]

如何使用Ebean获取它?

1 个答案:

答案 0 :(得分:1)

可以通过在@ManyToOneTown而不是Region字段中添加@Column关系来完成此操作。

所以在Town类中删除:

@Column(name = "state_id", nullable = false)
private Long stateId;

并添加:

@ManyToOne
public Region region;

Region班级中删除:

@Column(name = "state_id", nullable = false)
private Long stateId;

并添加:

@ManyToOne
public State state;

然后,您将能够通过以下查询找到给定州的城镇:

Ebean.find(Town.class).where().eq("region.state.id", stateId).findList();