ormlite update not null字段

时间:2013-09-02 07:12:54

标签: java android ormlite

我想只更新not null字段。我有一些类如下

@DatabaseTable
public class ClickCount implements Serializable {

    private static final long serialVersionUID = -6582623980712135028L;

    public static final String DATE_FIELD_NAME = "lastClickDate";

    @DatabaseField(generatedId = true)
    private Integer id;

    @DatabaseField(columnName = DATE_FIELD_NAME)
    private Date lastClickDate;

    @DatabaseField(index = true)
    private String name;

    @DatabaseField
    private String description;

    @DatabaseField
    private int value;

    @DatabaseField(canBeNull = true, foreign = true)
    private ClickGroup group;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public ClickGroup getGroup() {
        return group;
    }

    public void setGroup(ClickGroup group) {
        this.group = group;
    }

    public Date getLastClickDate() {
        return lastClickDate;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    /**
     * This updates the value and adjusts the date.
     */
    public void changeValue(int value) {
        this.value = value;
        this.lastClickDate = new Date();
    }

    @Override
    public String toString() {
        return name + " " + value;
    }
}

我得到一些json并使用ClickCount类解析,但某些字段可能为null。当我将DB空字段中的数据写入DB时更新。如何只写空字段?

更新

以下的数据
Dao<ClickCount, Integer> dao = getHelper().getClickDao();
ClickCount clickCountInDb = dao.queryForAll().get(0);
ClickCount clickCountFromServer = getFromServer();
clickCountFromServer.setId(clickCountInDb.getId());
dao.update(clickCountFromServer);

1 个答案:

答案 0 :(得分:0)

您在检查其是否为null后手动更新每个字段。之后,只需更新您获取的实体:

Dao<ClickCount, Integer> dao = getHelper().getClickDao();
ClickCount clickCountFromServer = getFromServer();
ClickCount clickCountInDb = dao.queryForId(clickCountInDb.getId());  // query for specific item. After this you should check if the query was succesful.
if (clickCountFromServer.getLastClickDate() != null)
{
     clickCountInDb.setLastClickDate(clickCountFromServer.getLastClickDate());
}
if (clickCountFromServer.getName() != null)
{
     clickCountInDb.setName(clickCountFromServer.getName());
}
// and so on for all fields

// after you set not null properties on the object clickCountInDb you have to propagate changes back to the database:
dao.update(clickCountInDb);