0

我只想更新不是空字段。我有一些像下面这样的课程

@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 类进行解析,但某些字段可能为空。当我更新数据库空字段中的数据写入数据库时​​。如何只写非空字段?

下面更新数据

Dao<ClickCount, Integer> dao = getHelper().getClickDao();
ClickCount clickCountInDb = dao.queryForAll().get(0);
ClickCount clickCountFromServer = getFromServer();
clickCountFromServer.setId(clickCountInDb.getId());
dao.update(clickCountFromServer);
4

1 回答 1

0

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

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);
于 2013-09-03T01:30:55.750 回答