Android机房SELECT * WHERE返回所有记录

时间:2019-02-27 06:06:48

标签: java android

我已经安装了Android Room数据库,并遵循了一些教程,以尝试扩展所做的工作。我有一些查询可以使用,但是当我尝试使用SELECT * WHERE查询时,它将返回表中的所有记录,而不仅仅是具有期望ID的记录。

DAO中的查询

@Query("SELECT * FROM weapon_table WHERE fighter_id = :fighter_id" )
LiveData<List<Weapon>> getFighterWeapons(long fighter_id);

记录对象

@Entity(tableName = "weapon_table",
        foreignKeys = {
                @ForeignKey(entity = com.Database.Fighter.class,
                        parentColumns = "fighter_id",
                        childColumns = "fighter_id"),
        })
public class Weapon
{
    @NonNull
    String weapon_name;
    @NonNull
    @PrimaryKey(autoGenerate = true)
    long weapon_id;
    @NonNull
    long fighter_id;


    public Weapon(String weapon_name, long fighter_id)
    {
        this.weapon_name = weapon_name;
        this.fighter_id = fighter_id;
    }

    public long getWeapon_id()
    {
        return weapon_id;
    }

    public void setWeapon_id(long weapon_id)
    {
        this.weapon_id = weapon_id;
    }

    public String getWeapon_name()
    {
        return weapon_name;
    }

    public void setWeapon_name(String weapon_name)
    {
        this.weapon_name = weapon_name;
    }

    public long getFighter_id()
    {
        return fighter_id;
    }

    public void setFighter_id(long fighter_id)
    {
        this.fighter_id = fighter_id;
    }
}

当我调用以下代码时,所有记录都被打印到调试控制台,但是当前ID也被打印出来,并且在所有情况下都保持不变。

   public void onClickAddWeapon(View view)
{
    List<Weapon> weapons = mWeaponViewModel.getFighterWeapons(fighter.getFighter_id()).getValue();
    for(Weapon weapon: weapons )
    {
        Log.d("WEAPONDEBUG", "WEAPONNAME/ID: " +weapon.getWeapon_name() +'/'+ weapon.getFighter_id() );
        Log.d("WEAPONDEBUG", "FIGHTERID: "+ fighter.getFighter_id() );

    }
}

3 个答案:

答案 0 :(得分:1)

修复非常简单,我遵循了这个google code labs tutorial,当我尝试扩展它时,我忘记了将查询结果实际分配给存储库文件中保存的列表。感谢您的建议,他们使我朝着正确的方向前进。

  LiveData<List<Weapon>> getFighterWeapons(long fighter_id)
    {
        mWeaponDao.getFighterWeapons(fighter_id);
        return mAllWeapons;
    }

替换为

LiveData<List<Weapon>> getFighterWeapons(long fighter_id)
{
    mAllWeapons = mWeaponDao.getFighterWeapons(fighter_id);
    return mAllWeapons;
}

答案 1 :(得分:0)

您的代码应该可以工作,但是我认为问题在于使用外键定义。

parentColumns = "fighter_id",

childColumns = "fighter_id"

您可以删除它并尝试吗?

                    `

答案 2 :(得分:-1)

尝试一下

@Query("SELECT * FROM weapon_table WHERE fighter_id IN (:fighter_id)" )
LiveData<List<Weapon>> getFighterWeapons(long fighter_id);