在编写对数据库差异化处理的时候,差异化就是把请求的json对象存入数据库时,当数据库有相同的数据时不更新,否则更新或插入。这里需要取出数据库的数据封装成对象。
对于内容的比较,这里使用重写类的equal()和hashCoad()方法。使用eclipse或AndroidStudio可以帮助自动生成。由于项目中请求的json拼装的对象的内容并不全部存入数据库,这就需要我们在自动生成的时候选择适当的字段。例如:
package bean;
public class Program {
public String programId = "";
public String subitem_pk = "";
public String item_url = "";
public String title = "";
public long timestamp = 0l;
public long endtimeStamp = 0l;
public String subitem_url = "";
public boolean is_complex = true;
public String poster_url = "";
public String item_pk = "";
public String model_name = "";
public Program() {
}
public Program(String title, long timestamp, String poster_url,
String item_pk) {
super();
this.title = title;
this.timestamp = timestamp;
this.poster_url = poster_url;
this.item_pk = item_pk;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Program program = (Program) o;
if (timestamp != program.timestamp) return false;
if (title != null ? !title.equals(program.title) : program.title != null) return false;
if (poster_url != null ? !poster_url.equals(program.poster_url) : program.poster_url != null)
return false;
return !(item_pk != null ? !item_pk.equals(program.item_pk) : program.item_pk != null);
}
@Override
public int hashCode() {
int result = title != null ? title.hashCode() : 0;
result = 31 * result + (int) (timestamp ^ (timestamp >>> 32));
result = 31 * result + (poster_url != null ? poster_url.hashCode() : 0);
result = 31 * result + (item_pk != null ? item_pk.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Program{" +
"title='" + title + '\'' +
", timestamp=" + timestamp +
", poster_url='" + poster_url + '\'' +
", item_pk='" + item_pk + '\'' +
'}';
}
}
测试的代码如下:
package main;
import bean.Animal;
import bean.Program;
public class Equal {
public static void main(String[] args) {
Program p1 = new Program("title", 100l, "poster_url", "item_pk");
Program p2 = new Program("title", 100l, "poster_url", "item_pk");
System.out.println(p1.equals(p2));
Program p3 = new Program("title", 100l, "poster_url", "item_pk");
p3.programId = "1";
Program p4 = new Program("title", 100l, "poster_url", "item_pk");
p4.programId = "2";
System.out.println(p3.equals(p4));
}
}
选择的方式如下: