/** * 根据条件更新,自行set更新内容 * * @param entity 实体类 * @param setter update * @param predicate 条件 * @return 更新条数 */ default long update(@Nonnull T entity, Consumer<SQLUpdateClause> setter, @Nullable Predicate... predicate) { Assert.ok("更新时条件不能为空", null != predicate && predicate.length > 0); // 强制不更新ID entity.setId(null); SQLUpdateClause update = sql().update(root()).populate(entity); setter.accept(update); return update.where(predicate).execute(); }
/** * 根据条件更新实体,完全根据条件更新,忽略ID * * @param entity 要更新的内容 * @param predicate 条件 * @return 变更条数 */ default long update(@Nonnull T entity, @Nullable Predicate... predicate) { Assert.ok("更新时条件不能为空", null != predicate && predicate.length > 0); // 强制不更新ID entity.setId(null); validRegular(entity); return sql().update(root()).populate(entity).where(predicate).execute(); }
/** * 根据条件更新,自行set更新内容 * * @param entity 实体类 * @param setter update * @return 更新条数 */ default long update(@Nonnull T entity, Consumer<SQLUpdateClause> setter) { Assert.notNull(HuiCheError.UPDATE_MUST_HAVE_ID, entity.getId()); SQLUpdateClause update = sql().update(root()).populate(entity); setter.accept(update); return update.where(pk().eq(entity.getId())).execute(); }
/** * 根据ID更新实体 * * @param entity 实体 * @param ignoreNull 是否忽略空属性,忽略时仅对有值的字段进行更新,否则全部进行更新 * @return 变更条数 */ default long update(@Nonnull T entity, boolean ignoreNull) { Assert.notNull(HuiCheError.UPDATE_MUST_HAVE_ID, entity.getId()); beforeUpdate(entity); validRegular(entity); SQLUpdateClause update = sql().update(root()); if (ignoreNull) { return update.populate(entity).where(pk().eq(entity.getId())).execute(); } else { return update.populate(entity, DefaultMapper.WITH_NULL_BINDINGS).where(pk().eq(entity.getId())).execute(); } }
/** * 根据ID更新实体列表,实体类必须设置ID,不设置ID将跳过 * * @param entityList 实体列表 * @return 变动条数 */ default long update(@Nonnull Collection<T> entityList) { SQLUpdateClause update = sql().update(root()); for (T entity : entityList) { Long id = entity.getId(); if (null != id) { beforeUpdate(entity); validRegular(entity); update.populate(entity.setId(null)).where(pk().eq(id)).addBatch(); } } if (!update.isEmpty()) { return update.execute(); } else { update.clear(); return 0; } } }
@Test public void insert_update_query_and_delete() { // Insert Employee employee = new Employee(); employee.setFirstname("John"); Integer id = insert(e).populate(employee).executeWithKey(e.id); assertNotNull(id); employee.setId(id); // Update employee.setLastname("S"); assertEquals(1L, update(e).populate(employee).where(e.id.eq(employee.getId())).execute()); // Query Employee smith = query().from(e).where(e.lastname.eq("S")).limit(1).select(e).fetchFirst(); assertEquals("John", smith.getFirstname()); // Delete (no changes needed) assertEquals(1L, delete(e).where(e.id.eq(employee.getId())).execute()); }
assertEquals(1L, update(e).populate(employee).where(e.id.eq(employee.getId())).execute());