在这里没有找到答案。我有 3 个对象(仅显示相关部分):
@Entity
class Module {
}
@Entity
class FeaturedModule {
@OneToOne(optional = false)
public Module playModule;
public static final Finder<Long, FeaturedModule> FIND = new Finder<Long, FeaturedModule>(Long.class, FeaturedModule.class);
}
@Entity
class ModuleVersion {
@ManyToOne
public Module playModule
public static final Finder<Long, ModuleVersion> FIND = new Finder<Long, ModuleVersion>(Long.class, ModuleVersion.class);
}
rels 是单向的,即 Module 没有引用其他 2 个实体。
问题:
- 如何(从 ModuleVersion)查找不在与 FeaturedModules 相关的模块内的模块
- 如何(从FeaturedModules)查找具有给定ModuleVersion的一系列FeaturedModules
最佳答案
一般来说:向 Module
模型添加 boolean 标志是个好主意,因此,您无需编写复杂的查询来查找包含关系的模块,只需检查该标志即可:
public static List<Module> findAllFeatured() {
return find.select("id,name").where().eq("isFeatured", true).findList();
}
public static List<Module> findAllNotFeatured() {
// give here list of field to select WITHOUT featured, otherwise it will
// create a JOIN to featured which will result that you will be not able
// to get records without associations
return find.select("id, name").where().eq("isFeatured", false).findList();
}
使用 isFeatured
标志,您还可以轻松过滤 ModuleVersion
:
public static List<ModuleVersion> findAll(String version) {
return find.fetch("module").where().like("version", version).findList();
}
public static List<ModuleVersion> findFeatured(String version) {
return find.fetch("module")
.where().like("version", version).eq("module.isFeatured", true).findList();
}
public static List<ModuleVersion> findNotFeatured(String version) {
return find.fetch("module")
.where().like("version", version).eq("module.isFeatured", false).findList();
}
当然,对于“自动”设置标志,您应该重写 Module
模型中的 save()
和 update(Object o)
方法,如果您需要此示例,请告诉我。
关于java - 如何遍历 2 个单向 Ebean rels @ManyToOne 和 @OneToOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12991310/