简体   繁体   English

使用Play Framework和Ebean进行复杂连接

[英]Complex joins using Play Framework and Ebean

I'm using the PlayFramework and I'm really liking it. 我正在使用PlayFramework,我真的很喜欢它。 When I want to grab data from a table, for example I have a user table, I use the following syntax: 当我想从表中获取数据时,例如我有一个user表,我使用以下语法:

List<User> users = User.find.where().eq("email", email).findList();

My question is that when I get the user object, I have an id column. 我的问题是,当我获得用户对象时,我有一个id列。 With that id value I can map to other tables and the id 's of those tables can be mapped to even more tables, so basic concept of joining across several tables. 使用该id值,我可以映射到其他表,并且这些表的id可以映射到更多表,因此跨多个表连接的基本概念。 Is there any example or place I can read where it describes how to implement that with the above-like syntax? 是否有任何示例或地方我可以阅读它描述如何使用上述语法实现它?

I tried to find myself and couldn't, only way I can think of it at this point is to use straight sql with prepared statements which I'd rather not do. 我试图找到自己而不能,只有这样我才能想到它是使用直接sql与准备好的语句,我宁愿不做。

ellou' kalvish ellou'kalvish

Relationships between models are set with common JPA annotations like @OneToMany , @ManyToOne , @OneToOne , etc. Relationships模型之间设置与普通JPA注释像@OneToMany@ManyToOne@OneToOne等。

So if you have User.java model for user table and Question.java model for user's Question you can join them with @OneToMany (One User has Many Question s) 因此,如果你有用户表的User.java模型和用户Question.java模型,你可以加入@OneToMany (一个User有很多Question

User 用户

@Entity
public class User extends Model {
    @Id
    public Long id;

    public String email;

    @OneToMany
    public List<Question> questions;
}

Question

@Entity
public class Question extends Model {
    @Id
    public Long id;

    public String question;
}

When you'll select a User in controller, Ebean will perform 'joins' by default and will fetch all user's questions as well: 当您在控制器中选择用户时,Ebean将默认执行“加入”,并且还将获取所有用户的问题:

User user = User.find.where().eq("email", email).findUnique();
List<Question> usersQuestion = user.questions;

By default Ebean fetches all object's properties and relations, so you don't need to create subqueries. 默认情况下,Ebean会获取所有对象的属性和关系,因此您无需创建子查询。 Of course you can or even should select/fetch only the data that is required at the moment. 当然,您甚至可以选择/获取当前所需的数据。

At the official Ebean documentation page you'll find quite good Reference guide (pdf) , general description of relationship is available in section 11.6.2 Relationships . 官方的Ebean文档页面上,你会发现很好的参考指南(pdf) ,关系的一般描述见11.6.2 Relationships

In section 4.1.2 Query there is example (second) which demonstrates how to get "partial" object with use of select() and fetch() 4.1.2 Query4.1.2 Query有一个示例(第二个)演示如何使用select()fetch()来获取“部分”对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM