播放框架:将外键添加到模型“@”?

play framework: add foreign key to a model '@'?

我正在尝试向模型添加外键,使用“@”符号是否可行....?

所以,我有这两个模型:

    @Entity
    public class NewEn extends Model{
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        public int Id;

        public String name;
        public String tags;

        public String user_id;
...
}

和:

@Entity
public class NewUser extends Model{


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int Id;

    public String username;
    public String first_name;
    public String last_name;
    public String email;
    public String password;

....
}

我希望:NewEn 中的 'user_id' 与 NewUser 模型中的主键 (Id) 相等。 我如何在模型中使用 @ 符号执行此操作?或者我如何绑定这些表...从我的代码,而不是从数据库?

@ 开头的单词 annotations. In this case those are JPA annotations 用于将 Java 中的对象映射到数据库中的 tables/rows。

假设您正在尝试在 NewUser 和 NewEn 之间创建一个 1-N 关系(即一个 NewUser 对象可以有多个 NewEn 对象),您需要像这样更改它:

@Entity
public class NewEn extends Model{
    // (...)
    public String tags;

    @ManyToOne
    public NewUser user;
    // (...)
}

然后使用 someNewEn.user 从给定的 NewEn 访问 NewUser。如果您还希望能够获取与给定 NewUser 关联的所有 NewEn 对象,您可以在 class 文件中指定:

@Entity
public class NewUser extends Model{

    // (...)
    public String password;

    // mappedBy is the name of the field in NewEn that contains the foreign key
    @OneToMany(mappedBy = "user")
    public List<NewEn> newEns;
    // (...)
}

请注意,现在,如果您想将 NewEn 关联到 NewUser,则必须使用对象而不是简单的 ID。如果你只需要使用 id,你将不得不做这样的事情:

int userId = 345;
User user = new User();
user.id = userId;

someNewEnObject.user = user;
someNewEnObject.save();