Java Code Examples for com.jfinal.plugin.activerecord.Db#tx()

The following examples show how to use com.jfinal.plugin.activerecord.Db#tx() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RoleServiceProvider.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
@CachesEvict({
        @CacheEvict(name = "user_role", key = "*"),
        @CacheEvict(name = "user_permission", key = "*")
})
public boolean doResetUserRoles(long userId, Long... RoleIds) {
    if (RoleIds == null || RoleIds.length == 0) {
        return Db.delete("delete from user_role_mapping where user_id = ? ", userId) > 0;
    }

    return Db.tx(() -> {
        Db.delete("delete from user_role_mapping where user_id = ? ", userId);

        List<Record> records = new ArrayList<>();
        for (Long roleId : RoleIds) {
            Record record = new Record();
            record.set("user_id", userId);
            record.set("role_id", roleId);
            records.add(record);
        }

        Db.batchSave("user_role_mapping", records, records.size());

        return true;
    });
}
 
Example 2
Source File: DbTxInterceptor.java    From jfinal-ext3 with Apache License 2.0 6 votes vote down vote up
@Override
public void intercept(final Invocation inv) {
	Db.tx(new IAtom() {
		@Override
		public boolean run() throws SQLException {
			try {
				inv.invoke();
			} catch (Exception e) {
				if (inv.getTarget() instanceof ControllerExt) {
					ControllerExt controller = inv.getTarget();
					controller.onExceptionError(e);
				}
				return false;
			}
			return true;
		}
	});
}
 
Example 3
Source File: ProductServiceProvider.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
@CachesEvict({
        @CacheEvict(name = "products", key = "*"),
        @CacheEvict(name = "product-category", key = "#(productId)"),
})
public void doUpdateCategorys(long productId, Long[] categoryIds) {
    Db.tx(() -> {
        Db.update("delete from product_category_mapping where product_id = ?", productId);

        if (categoryIds != null && categoryIds.length > 0) {
            List<Record> records = new ArrayList<>();
            for (long categoryId : categoryIds) {
                Record record = new Record();
                record.set("product_id", productId);
                record.set("category_id", categoryId);
                records.add(record);
            }
            Db.batchSave("product_category_mapping", records, records.size());
        }

        return true;
    });
}
 
Example 4
Source File: ArticleServiceProvider.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override

    @CachesEvict({
            @CacheEvict(name = "articles", key = "*"),
            @CacheEvict(name = "article-category", key = "#(articleId)"),
    })
    public void doUpdateCategorys(long articleId, Long[] categoryIds) {

        Db.tx(() -> {
            Db.update("delete from article_category_mapping where article_id = ?", articleId);

            if (categoryIds != null && categoryIds.length > 0) {
                List<Record> records = new ArrayList<>();
                for (long categoryId : categoryIds) {
                    Record record = new Record();
                    record.set("article_id", articleId);
                    record.set("category_id", categoryId);
                    records.add(record);
                }
                Db.batchSave("article_category_mapping", records, records.size());
            }

            return true;
        });
    }
 
Example 5
Source File: SysRoleController.java    From my_curd with Apache License 2.0 6 votes vote down vote up
/**
 * 删除 action
 */
@Before(IdsRequired.class)
public void deleteAction() {
    String ids = getPara("ids").replaceAll(",", "','");
    Db.tx(() -> {
        // 删除角色数据
        String sql = "delete from sys_role where id in ('" + ids + "')";
        Db.update(sql);
        // 删除 角色用户 中间表
        sql = "delete from sys_user_role where sysRoleId in ('" + ids + "')";
        Db.update(sql);
        // 删除角色菜单中间表
        sql = "delete from sys_role_menu where sysRoleId in ('" + ids + "')";
        Db.update(sql);
        // 通知类型 角色 中间表
        sql = "delete from sys_notice_type_sys_role where sysRoleId in ('" + ids + "')";
        Db.update(sql);
        return true;
    });
    renderSuccess(DELETE_SUCCESS);
}
 
Example 6
Source File: SysNoticeTypeController.java    From my_curd with Apache License 2.0 6 votes vote down vote up
@Before(IdsRequired.class)
public void deleteAction() {
    String ids = getPara("ids").replaceAll(",", "','");
    Db.tx(() -> {
        String sql = "delete from sys_notice_type where id in ('" + ids + "')";
        Db.update(sql);
        sql = "delete from sys_notice_type_sys_role where sysNoticeTypeId in ('" + ids + "')";
        Db.update(sql);
        // 删除通知消息表
        sql = "delete from sys_notice_detail where sysNoticeId in (select id from sys_notice where typeCode in (select typeCode from sys_notice_type where id in ('" + ids + "')))";
        Db.update(sql);
        sql = "delete from sys_notice where typeCode in (select typeCode from sys_notice_type where id in ('" + ids + "'))";
        Db.update(sql);
        return true;
    });
    renderSuccess(DELETE_SUCCESS);
}
 
Example 7
Source File: SysOrgController.java    From my_curd with Apache License 2.0 6 votes vote down vote up
/**
 * 删除 action
 */
@Before(IdRequired.class)
public void deleteAction() {
    String id = getPara("id");
    Db.tx(() -> {
        // 子孙id,包括自身
        String sonIds = TreeTableUtils.getSonTreeIds(id, "sys_org", "id", "pid");
        if (StringUtils.isEmpty(sonIds)) {
            return true;
        }
        sonIds = sonIds.replaceAll(",", "','");
        // 删除机构
        String sql = "delete from sys_org where id in ('" + sonIds + "')";
        Db.update(sql);
        // 相关 人员 机构字段 置空
        sql = "update sys_user set orgId = null where orgId  in ('" + sonIds + "')";
        Db.update(sql);
        return true;
    });
    renderSuccess(DELETE_SUCCESS);
}
 
Example 8
Source File: UserOrderServiceProvider.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean updateOrderAndItems(UserOrder order, List<UserOrderItem> items) {
    return Db.tx(() -> {
        if (!update(order)) {
            return false;
        }

        for (UserOrderItem item : items) {
            if (!itemService.update(item)) {
                return false;
            }
        }

        return true;
    });
}
 
Example 9
Source File: UserTagServiceProvider.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void doUpdateTags(long userId, Long[] tagIds) {
    Db.tx(() -> {
        Db.update("delete from user_tag_mapping where user_id = ?", userId);

        if (tagIds != null && tagIds.length > 0) {
            List<Record> records = new ArrayList<>();
            for (long tagId : tagIds) {
                Record record = new Record();
                record.set("user_id", userId);
                record.set("tag_id", tagId);
                records.add(record);
            }
            Db.batchSave("user_tag_mapping", records, records.size());
        }

        return true;
    });
}
 
Example 10
Source File: SysDictController.java    From my_curd with Apache License 2.0 5 votes vote down vote up
/**
 * 修改 sysDictGroup
 */
public void updateGroupAction() {
    // 已存数据
    SysDictGroup sysDictGroupOld = SysDictGroup.dao.findById(get("id"));
    if (sysDictGroupOld == null) {
        renderSuccess(UPDATE_FAIL);
        return;
    }
    // 修改后的数据
    SysDictGroup sysDictGroup = getBean(SysDictGroup.class, "");
    sysDictGroup.setUpdater(WebUtils.getSessionUsername(this))
            .setUpdateTime(new Date());

    if (!Objects.equal(sysDictGroup.getGroupCode(), sysDictGroupOld.getGroupCode())) {
        // 编码不一致
        List<SysDict> sysDictList = SysDict.dao.findAllByGroupCode(sysDictGroupOld.getGroupCode());
        if (sysDictList.size() > 0) {
            // 子表存在记录
            Db.tx(() -> {
                String sql = "update sys_dict set groupCode = ? where groupCode = ?";
                Db.update(sql, sysDictGroup.getGroupCode(), sysDictGroupOld.getGroupCode());
                sysDictGroup.update();
                return true;
            });
        } else {
            // 子表 不存在记录
            sysDictGroup.update();
        }
    } else {
        sysDictGroup.update();
    }
    renderSuccess(UPDATE_SUCCESS);
}
 
Example 11
Source File: RechargePaymentSuccessListener.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onSuccess(PaymentRecord payment) {

    if (PaymentRecord.TRX_TYPE_RECHARGE.equals(payment.getTrxType())) {

        boolean updateSucess = Db.tx(() -> {

            BigDecimal userAmount = userService.queryUserAmount(payment.getPayerUserId());
            userService.updateUserAmount(payment.getPayerUserId(), userAmount, payment.getPayAmount());

            UserAmountStatement statement = new UserAmountStatement();
            statement.setUserId(payment.getPayerUserId());
            statement.setAction(payment.getTrxType());
            statement.setActionDesc(payment.getTrxTypeStr());
            statement.setActionName("充值");
            statement.setActionRelativeType("payment_record");
            statement.setActionRelativeId(payment.getId());

            statement.setOldAmount(userAmount);
            statement.setChangeAmount(payment.getPayAmount());
            statement.setNewAmount(userAmount.add(payment.getPayAmount()));

            if (userService.updateUserAmount(payment.getPayerUserId(), userAmount, payment.getPayAmount())) {
                return false;
            }

            if (statementService.save(statement) == null) {
                return false;
            }

            return true;
        });

        if (!updateSucess) {
            LOG.error("error!!!  update user amount fail in recharge success. ");
        }

    }

}
 
Example 12
Source File: RoleServiceProvider.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
@CacheEvict(name = "user_role", key = "*")
public boolean deleteByIds(Object... ids) {
    return Db.tx(() -> {
        Db.update("delete from user_role_mapping where role_id in  " + SqlUtils.buildInSqlPara(ids));
        Db.update("delete from role_permission_mapping where role_id in  " + SqlUtils.buildInSqlPara(ids));
        return Db.update("delete from role where id in " + SqlUtils.buildInSqlPara(ids)) > 0;
    });
}
 
Example 13
Source File: RoleServiceProvider.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
@CacheEvict(name = "user_role", key = "*")
public boolean deleteById(Object id) {
    return Db.tx(() -> {
        Db.update("delete from user_role_mapping where role_id = ? ", id);
        Db.update("delete from role_permission_mapping where role_id = ? ", id);
        return RoleServiceProvider.super.deleteById(id);
    });
}
 
Example 14
Source File: SysDictController.java    From my_curd with Apache License 2.0 5 votes vote down vote up
/**
 * 删除 sysDictGroup
 */
@Before(IdsRequired.class)
public void deleteGroupAction() {
    // 设置删除标志
    String ids = getPara("ids").replaceAll(",", "','");
    Db.tx(() -> {
        String sql = "update sys_dict set delFlag = 'X' where groupCode in (select groupCode from sys_dict_group where id in ('" + ids + "'))";
        Db.update(sql);
        sql = "update sys_dict_group set delFlag = 'X' where id in ('" + ids + "')";
        Db.update(sql);
        return true;
    });
    renderSuccess(DELETE_SUCCESS);
}
 
Example 15
Source File: SysUserController.java    From my_curd with Apache License 2.0 5 votes vote down vote up
/**
 * delete
 */
@Before(IdsRequired.class)
public void deleteAction() {
    String ids = get("ids").replaceAll(",", "','");
    Db.tx(() -> {
        // 修改删除标志
        String sql = "update sys_user set delFlag = 'X' where id in ('" + ids + "')";
        Db.update(sql);
        return true;
    });
    renderSuccess(DELETE_SUCCESS);
}
 
Example 16
Source File: OrderPaymentSuccessListener.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onSuccess(PaymentRecord payment) {

    if (PaymentRecord.TRX_TYPE_ORDER.equals(payment.getTrxType())) {

        boolean updateSucess = Db.tx(() -> {

            UserOrder userOrder = orderService.findByPaymentId(payment.getId());

            userOrder.setPayStatus(PayStatus.getSuccessIntStatusByType(payment.getPayType()));
            userOrder.setTradeStatus(UserOrder.TRADE_STATUS_COMPLETED);

            if (!orderService.update(userOrder)) {
                return false;
            }


            List<UserOrderItem> userOrderItems = itemService.findListByOrderId(userOrder.getId());
            for (UserOrderItem item : userOrderItems) {
                if (item.isVirtualProduct()) {
                    item.setStatus(UserOrderItem.STATUS_FINISHED);//交易结束
                } else {
                    item.setStatus(UserOrderItem.STATUS_COMPLETED);//交易完成
                }
                if (!itemService.update(item)) {
                    return false;
                }
                OrderManager.me().notifyItemStatusChanged(item);
            }

            OrderManager.me().notifyOrderStatusChanged(userOrder);
            return true;
        });

        if (!updateSucess) {
            LOG.error("update order fail or update orderItem fail in pay success。");
        }
    }
}
 
Example 17
Source File: DelSysNoticeTask.java    From my_curd with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    // 样板 代码
    SysTaskLog sysTaskLog = new SysTaskLog();
    sysTaskLog.setId(IdUtils.id());
    sysTaskLog.setClassName(this.getClass().getName());
    sysTaskLog.setStartTime(new Date());
    String errMsg = null;

    // 业务
    Date today = new Date();
    LOG.debug(" 定时任务执行。 (删除 “过期未读” 和 “必死” 的 系统通知数据表 数据)");
    try {
        Db.tx(() -> {
            // 删除 “必死期” 的 主从表记录
            String selectSql = "select group_concat(id) as ids from sys_notice  where deadTime <= ? ";
            String deleteSql;
            String ids;
            Record record = Db.findFirst(selectSql, today);
            if (StringUtils.notEmpty(record.getStr("ids"))) {
                ids = record.getStr("ids").replaceAll(",", "','");
                deleteSql = " delete from  sys_notice where id in ('" + ids + "')";
                Db.update(deleteSql);
                deleteSql = " delete from  sys_notice_detail where sysNoticeId in ('" + ids + "')";
                Db.update(deleteSql);
            }

            // 删除 过期 未读的从表记录
            selectSql = " select group_concat(id) as ids from sys_notice where expiryTime <= ? ";
            record = Db.findFirst(selectSql, today);
            if (StringUtils.notEmpty(record.getStr("ids"))) {
                ids = record.getStr("ids").replaceAll(",", "','");
                deleteSql = " delete from  sys_notice_detail where sysNoticeId in ('" + ids + "') and hasRead='N' ";
                Db.update(deleteSql);
            }
            return true;
        });
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        errMsg = e.getMessage();

    }


    // 样板 代码
    sysTaskLog.setEndTime(new Date());
    if (StringUtils.isEmpty(errMsg)) {
        sysTaskLog.setResult("success");
    } else {
        sysTaskLog.setResult("fail");
        sysTaskLog.setError(errMsg);
    }
    sysTaskLog.save();
}
 
Example 18
Source File: UserServiceImpl.java    From jboot-admin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean saveUser(User user, Long[] roles) {
    String pwd = user.getPwd();

    if (StrKit.notBlank(pwd)) {
        String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
        SimpleHash hash = new SimpleHash("md5", pwd, salt2, 2);
        pwd = hash.toHex();
        user.setPwd(pwd);
        user.setSalt2(salt2);
    }

    user.setOnlineStatus(UserOnlineStatus.OFFLINE);
    user.setCreatedate(new Date());
    user.setLastUpdTime(new Date());
    user.setNote("保存系统用户");

    return Db.tx(new IAtom() {
        @Override
        public boolean run() throws SQLException {
            if (!user.save()) {
                return false;
            }

            if (roles != null) {
                List<UserRole> list = new ArrayList<UserRole>();
                for (Long roleId : roles) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(roleId);
                    list.add(userRole);
                }
                int[] rets = userRoleService.batchSave(list);

                for (int ret : rets) {
                    if (ret < 1) {
                        return false;
                    }
                }
            }
            return true;
        }
    });
}
 
Example 19
Source File: _FinanceController.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
@EmptyValidate({
        @Form(name = "amount", message = "打款金额不能为空")
})
public void doPayoutProcess() {
    UserAmountPayout payout = payoutService.findById(getPara("id"));

    //modified by jializheng 20200218 取提现申请人的余额信息,而非当前登录用户(管理员)
    BigDecimal userAmount = userService.queryUserAmount(payout.getUserId());
    if (userAmount == null || userAmount.compareTo(payout.getAmount()) < 0) {
        renderFailJson("用户余额不足,无法提现。");
        return;
    }

    BigDecimal amount = new BigDecimal(getPara("amount"));
    BigDecimal shouldPayAmount = payout.getAmount().subtract(payout.getFee());
    if (amount == null || amount.compareTo(shouldPayAmount) != 0) {
        renderFailJson("打款金额输入错误,实际应该给客户打款金额为:" + new DecimalFormat("0.00").format(shouldPayAmount) + " 元");
        return;
    }

    Db.tx(() -> {
        payout.setStatus(UserAmountPayout.STATUS_SUCCESS);
        payout.setPaySuccessProof(getPara("proof"));
        if (!payoutService.update(payout)) {
            return false;
        }

        //生成提现用户的流水信息
        UserAmountStatement statement = new UserAmountStatement();
        statement.setUserId(payout.getUserId());
        statement.setAction(UserAmountStatement.ACTION_PAYOUT);
        statement.setActionDesc("用户提现");
        statement.setActionName("用户提现");
        statement.setActionRelativeType("user_amount_payout");
        statement.setActionRelativeId(payout.getId());
        statement.setOldAmount(userAmount);
        statement.setChangeAmount(BigDecimal.ZERO.subtract(payout.getAmount()));
        statement.setNewAmount(userAmount.subtract(payout.getAmount()));

        if (statementService.save(statement) == null) {
            return false;
        }

        if (userService.updateUserAmount(payout.getUserId()
                , userAmount
                , BigDecimal.ZERO.subtract(payout.getAmount()))) {
            return false;
        }

        return true;
    });
    renderOkJson();
}
 
Example 20
Source File: UserServiceImpl.java    From jboot-admin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean updateUser(User user, Long[] roles) {
    String pwd = user.getPwd();
    if (StrKit.notBlank(pwd)) {
        String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
        SimpleHash hash = new SimpleHash("md5", pwd, salt2, 2);
        pwd = hash.toHex();
        user.setPwd(pwd);
        user.setSalt2(salt2);
    } else {
        user.remove("pwd");
    }

    user.setLastUpdTime(new Date());
    user.setNote("修改系统用户");

    return Db.tx(new IAtom() {
        @Override
        public boolean run() throws SQLException {
            if (!user.update()) {
                return false;
            }

            userRoleService.deleteByUserId(user.getId());

            if (roles != null) {
                List<UserRole> list = new ArrayList<UserRole>();
                for (Long roleId : roles) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(roleId);
                    list.add(userRole);
                }

                int[] rets = userRoleService.batchSave(list);
                for (int ret : rets) {
                    if (ret < 1) {
                        return false;
                    }
                }
            }
            return true;
        }
    });
}