代码之家  ›  专栏  ›  技术社区  ›  Abhinav Tyagi

连接房间数据库中的表

  •  3
  • Abhinav Tyagi  · 技术社区  · 6 年前

    类的列表 作为它的成员变量之一。

    public class User {
        String id;
        String name;
        List<Pet> pets;
    }
    
    
    Public class Pets {
        String id;
        String type;
    }
    

    {  
      "users":[  
        {  
          "id":"as123",
          "name":"John",
          "pets":[  
            {  
              "id":"p123",
              "type":"dog"
            }
          ]
        },
        {  
          "id":"as343",
          "name":"Mark",
          "pets":[  
            {  
              "id":"p324",
              "type":"dog"
            },
            {  
              "id":"p254",
              "type":"cat"
            }
          ]
        }
      ]
    }
    

    我已经创建了以下内容,但不确定如何创建正确的列或联接这些表。

    @Entity(tableName = "user")
    public class User {
    
        @PrimaryKey
        @NonNull
        @ColumnInfo(name = "id")
        String id;
    
        @Nullable
        @ColumnInfo(name = "name")
        String name;
    
        List<Pets> pets; // how to set type for Pets
    }
    
    @Entity(tableName = "pets",
        foreignKeys = @ForeignKey(entity = User.class,
        parentColumns = "id",
        childColumns = "userId",
        onDelete = CASCADE))
    Public class Pets {
    
        @PrimaryKey
        @NonNull
        @ColumnInfo(name = "id")
        String id;
    
        @Nullable
        @ColumnInfo(name = "type")
        String type;
    
        @NonNull
        @ColumnInfo(name = "userId")
        String userId; // for accessing pets of a user
    } 
    

    @Dao
    public interface PetsDAO {
    
        @Insert
        void insert(Pets pets);
    
        @Update
        void update(Pets... pets);
    
        @Delete
        void delete(Pets... pets);
    
        @Query("SELECT * FROM pets WHERE id=:userId")
        List<Pets> getPetsForUser(final String userId);
    }
    
    @Dao
    public interface UserDAO {
    
        @Insert
        void insert(User pets);
    
        @Update
        void update(User... pets);
    
        @Delete
        void delete(User... pets);
    
        @Query("SELECT * FROM user)
        List<User> getAllUsers(); // should return list of users with all their pets
    }
    

    我怎样才能得到 List