public Long getID(String collName) { // 跟据表名查询 Query<Sequence> q = ds.find(Sequence.class, "id", collName); UpdateOperations<Sequence> uOps = ds.createUpdateOperations(Sequence.class); uOps.inc("currentIdValue"); Sequence sequence = ds.findAndModify(q, uOps); // 执行查询并更新,该操作椐有原子性 if (sequence == null) { sequence = new Sequence(collName, 1l); ds.save(sequence); } return sequence.getCurrentIdValue(); }
public <T> UpdateResults<T> update(T ent, UpdateOperations<T> ops) { MappedClass mc = mapr.getMappedClass(ent); Query<T> q = (Query<T>) createQuery(mc.getClazz()); q.disableValidation().filter(Mapper.ID_KEY, getId(ent)); if (mc.getFieldsAnnotatedWith(Version.class).size() > 0) { MappedField versionMF = mc.getFieldsAnnotatedWith(Version.class).get(0); Long oldVer = (Long) versionMF.getFieldValue(ent); q.filter(versionMF.getNameToStore(), oldVer); ops.set(versionMF.getNameToStore(), VersionHelper.nextValue(oldVer)); } return update(q, ops); }
@Override public void saveOrUpdate(User user) { Query<User> q = createQuery().filter("uid", user.getUid()); User pUser = q.get(); if (pUser == null) save(user); else { UpdateOperations<User> uo = createUpdateOperations(); uo.set("screenName", user.getScreenName()); uo.set("name", user.getName()); uo.set("profileImageUrl", user.getProfileImageUrl()); uo.set("followersSize", user.getFollowersSize()); uo.set("tweetsSize", user.getTweetsSize()); uo.set("detail", user.getDetail()); update(q, uo); user.setId(pUser.getId()); } }
@Override public void incPrefSize(long userId) { UpdateOperations<User> uo = createUpdateOperations(); uo.inc("prefSize", 1); update(createQuery().filter("id", userId), uo); }