Class 自身集合 ORMLite

Class with collection of itself ORMLite

如何在 ormlite 中创建与 table 本身的一对多关系?我有一个 class 保存自己的集合。我不知道如何映射这个 class.

@DatabaseTable(tableName = "USER")
public class User {

    @DatabaseField(generatedId = true)
    private long id;
    @DatabaseField
    private String username;
    @ForeignCollectionField
    private ForeignCollection<User> friends;
    ...

提前致谢。

I have a class that holds collection of itself. I don't know how to map this class.

我认为最好的方法是定义一个 UserFriend 实体,该实体具有对所有者 User、朋友 User 和 ID 的引用。类似于:

@DatabaseTable(tableName = "USERFRIEND")
public class UserFriend {

    @DatabaseField(generatedId = true)
    private long id;
    // corresponds to the user who has the friend
    @DatabaseField(foreign = true)
    private User user;
    // corresponds to the friend of the user
    @DatabaseField(foreign = true)
    private User friend;
    ...

那么你的外国collection就变成了:

@ForeignCollectionField(foreignFieldName = 'user')
private ForeignCollection<UserFriend> friends;

注意 foreignFieldName 必须指向 user 以便可以找到用户的朋友。