foreign key query play! framework 2.+ ebean

倾然丶 夕夏残阳落幕 提交于 2019-12-24 04:47:07

问题


I'm new to play framework and the Ebean ORM.

Basically, I have two models one is a RegUsers the other is RegIds. In my registration Ids I put a many to one relationship on the Field RegUsers. Stating, if I'm not mistaken that one user can have many registration ids.

RegId model:

@Entity 
public class RegId extends Model{
    public static Finder<Long,RegId> finder = new Finder<Long,RegId>(Long.class, RegId.class);

    @Id
    public Long id;

    @ManyToOne
    public RegUsers regUsers;

    public String regId;
}

RegUser model:

@Entity 
public class RegUsers extends Model{

    public static Finder<Long,RegUsers> find = new Finder<Long,RegUsers>(Long.class, RegUsers.class);

    @Id
    public Long id;

    public String email;
    public String name;
}

A RegId must have a RegUser, but a RegUser does not need to have a RegId. For one of my views I'm trying to show all RegUsers who do have an RegId only once, but cannot figure out how to do this.

I got close with querying the RegId table like so:

List<RegId> reg = RegId.finder.where().findList();

And then querying the RegUser.name by:

@(regs: List[RegId])

@for(reg <- regs){
    <p>@reg.regUsers.email</p>
}

But I can't figure out how to only show distinct records. Is there a way to do this using Ebean or will I need to writ raw sql? I would appreciate any help.


回答1:


if you add a regIds field to your RegUsers definition like this:

@Entity 
public class RegUsers extends Model{

    public static Finder<Long,RegUsers> find = new Finder<Long,RegUsers>(Long.class, RegUsers.class);

    @Id
    public Long id;

    public String email;
    public String name;

    @OneToMany(mappedBy="regUsers")
    public Set<RegId> regIds;
}

you can query for RegUsers that have at least one RegId like this:

RegUsers.find.where().isNotNull("regIds.id").findList()

if you want to find RegUsers with exactly one RegId then you need to write custom sql indeed.



来源:https://stackoverflow.com/questions/17981766/foreign-key-query-play-framework-2-ebean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!