条件:首先存储的列表字段有 id(String 类型) 和 status(只有 1 和 -1 两个状态,且状态只能从 1 修改为 -1,反之不行) 只有 id 和 status 都相同才算是同一个对象 如何保证三个数据库的数据一样呢?因为数据库一个是手机日历,一个是手机 SQLite,一个是服务器 Mysql,所以也没有办法在数据库上想办法想问下大伙儿,有更好的方法吗?我感觉我这个就是一个最基础的笨方法我是这样做的,先拿 A 和 B 同步,保证 A\B 数据是一致的 再拿 A 和 C 做同步,当需要修改 A 的时候,同时也修改 B大致代码是这样的:
public class Test {
public static void main(String[] args) {
HashMap<String, Bean> mapA = new HashMap<>(16);
HashMap<String, Bean> mapB = new HashMap<>(16);
HashMap<String, Bean> mapC = new HashMap<>(16);
// A、B 两个数据库同步
for (String key : mapA.keySet()) {
if (mapB.containsKey(key)) {
if (mapA.get(key).getStatus() != mapB.get(key).getStatus()) {
if (mapB.get(key).getStatus() == 1) {
// 将 B 数据库当中的 status 修改为 -1
}
}
} else {
// 将 mapA 中 key 对应的 value 插入到 数据库 B 当中
}
}
for (String key : mapB.keySet()) {
if (mapA.containsKey(key)) {
if (mapB.get(key).getStatus() != mapA.get(key).getStatus()) {
if (mapA.get(key).getStatus() == 1) {
// 将 A 数据库当中的 status 修改为 -1
}
}
} else {
// 将 mapB 中 key 对应的 value 插入到 数据库 A 当中
}
}
//以上操作保证了 A、B 两个数据库是同步的
//然后再拿 A 和 C 两个数据库做同步
//还是同样的逻辑,但是当需要修改 A 的数据的时候,同时也修改 B 数据库
for (String key : mapA.keySet()) {
if (mapC.containsKey(key)) {
if (mapA.get(key).getStatus() != mapC.get(key).getStatus()) {
if (mapC.get(key).getStatus() == 1) {
// 将 C 数据库当中的 status 修改为 -1
}
}
} else {
// 将 mapA 中 key 对应的 value 插入到 数据库 C 当中
}
}
for (String key : mapC.keySet()) {
if (mapA.containsKey(key)) {
if (mapC.get(key).getStatus() != mapA.get(key).getStatus()) {
if (mapA.get(key).getStatus() == 1) {
// 将 A 数据库当中的 status 修改为 -1
// 将 B 数据库当中的 status 修改为 -1
}
}
} else {
// 将 mapC 中 key 对应的 value 插入到 数据库 A 当中
// 将 mapC 中 key 对应的 value 插入到 数据库 B 当中
}
}
}
}class Bean {
private String key;
private int status; public String getKey() {
return key;
} public void setKey(String key) {
this.key = key;
} public int getStatus() {
return status;
} public void setStatus(int status) {
this.status = status;
}
}

解决方案 »

  1.   

     for (String key : mapA.keySet()) {
                if (mapB.containsKey(key)) {
                    if (mapA.get(key).getStatus() != mapB.get(key).getStatus()) {
                        if (mapB.get(key).getStatus() == 1) {
                            // 将 B 数据库当中的 status 修改为 -1
                        }
                    }
                } else {
                    // 将 mapA 中 key 对应的 value 插入到 数据库 B 当中
                }
            }
    若A、B中B为-1,A为1,你这个算法就错了。
    所以应该是A、B只要不相同,二个都改为-1.其他的代码并没有问题
    不知道你具体的需要跟使用场景,你这种做法也不符合多线程的要求。还是会出现异步问题
      

  2.   


    还有一个将 MapA 和 MapB 反过来的操作的。
    另外也没有多线程参与,所以没有异步的问题使用场景是,手机App,需要结合本机日历做一些功能,所以需要使用本地日历的数据库,同事还有一些新添加的功能,需要用到本地 SQLite,另外还考虑到了用户更换手机,所以会将这些数据再保存到云端,所以用到了 Mysql,
    三个数据库中的字段是相同的,需要做的就是,保证三个数据库的数据内容是同步的