项目开发问题总结

目录

跨域问题使用的响应头设置(目前没有使用效果)

在插入数据的同时,如何取出数据的主键

shiro配置文件的位置

分页功能的实现

vue表单提交问题

定义和用法

语法

属性值

activiti数据库表结构详细说明

表中的字段不能重复

数据库中的字段类型

缓存和数据库之间如何保持一致性

事务配置问题

数据转换报错

springboot项目mybatis配置文件与@Mapper注解问题

调用接口,对返回的数据进行处理



跨域问题使用的响应头设置(目前没有使用效果)

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse)response;
        // 指定允许其他域名访问
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        // 响应类型
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");
        // 响应头设置
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, token");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        String method = ((HttpServletRequest) request).getMethod();
        if (method.equals("OPTIONS")){
            resp.setStatus(204);
        }

 

在插入数据的同时,如何取出数据的主键

使用 keyProperty="jobId" useGeneratedKeys="true"获取主键,实体类中要有对应的字段,此数据库中jobId为自增的

<insert id="insertSelective" parameterType="com.zhipu.model.base.entity.ZpScheduleJob" keyProperty="jobId" useGeneratedKeys="true">
    insert into zp_schedule_job
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="jobId != null">
        job_id,
      </if>
      <if test="beanName != null">
        bean_name,
      </if>
      <if test="methodName != null">
        method_name,
      </if>
      <if test="params != null">
        params,
      </if>
      <if test="cronExpression != null">
        cron_expression,
      </if>
      <if test="status != null">
        `status`,
      </if>
      <if test="remark != null">
        remark,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
      <if test="updateTime != null">
        update_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="jobId != null">
        #{jobId,jdbcType=BIGINT},
      </if>
      <if test="beanName != null">
        #{beanName,jdbcType=VARCHAR},
      </if>
      <if test="methodName != null">
        #{methodName,jdbcType=VARCHAR},
      </if>
      <if test="params != null">
        #{params,jdbcType=VARCHAR},
      </if>
      <if test="cronExpression != null">
        #{cronExpression,jdbcType=VARCHAR},
      </if>
      <if test="status != null">
        #{status,jdbcType=TINYINT},
      </if>
      <if test="remark != null">
        #{remark,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null">
        #{updateTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>

在service层通过getJobId获取插入数据的主键,insertSelective方法返回的是影响的行数而不是主键jobId,这点要注意

@Override
    @Transactional(rollbackFor = Exception.class)
    public void saveJob(ZpScheduleJob scheduleJob) {
        scheduleJob.setCreateTime(new Date());
        scheduleJob.setStatus((byte)Constant.ScheduleStatus.NORMAL.getValue());
        zpScheduleJobMapper.insertSelective(scheduleJob);
        System.out.println("jobId:"+scheduleJob.getJobId());
        ZpScheduleJob zpScheduleJob = zpScheduleJobMapper.selectByPrimaryKey(scheduleJob.getJobId());
        System.out.println("scheduleJob:"+zpScheduleJob);
        ScheduleUtils.createScheduleJob(scheduler, zpScheduleJob);
    }

shiro配置文件的位置

shiro配置文件需要和启动类放在同模块中,否则不能自动装配

image.png

分页功能的实现

package com.zhipu.result;

import com.baomidou.mybatisplus.core.metadata.IPage;

import java.io.Serializable;
import java.util.List;

/**
 * 分页工具类
 */
public class PageResult implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 总记录数
     */
    private int totalCount;
    /**
     * 每页记录数
     */
    private int pageSize;
    /**
     * 总页数
     */
    private int totalPage;
    /**
     * 当前页数
     */
    private int currPage;
    /**
     * 列表数据
     */
    private List<?> list;

    /**
     * 分页
     * @param list        列表数据
     * @param totalCount  总记录数
     * @param pageSize    每页记录数
     * @param currPage    当前页数
     */
    public PageResult(List<?> list, int totalCount, int pageSize, int currPage) {
        this.list = list;
        this.totalCount = totalCount;
        this.pageSize = pageSize;
        this.currPage = currPage;
        this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
    }

    /**
     * 分页
     */
    public PageResult(IPage<?> page) {
        this.list = page.getRecords();
        this.totalCount = (int)page.getTotal();
        this.pageSize = (int)page.getSize();
        this.currPage = (int)page.getCurrent();
        this.totalPage = (int)page.getPages();
    }

    public PageResult() {

    }


    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getCurrPage() {
        return currPage;
    }

    public void setCurrPage(int currPage) {
        this.currPage = currPage;
    }

    public List<?> getList() {
        return list;
    }

    public void setList(List<?> list) {
        this.list = list;
    }

}

serviceImpl中的实现方法

@Override
    public PageResult queryPage(ZpSysAccountPo zpSysAccountPo) {
        PageResult pageResult =new PageResult();
        ZpSysAccountExample example = new ZpSysAccountExample();
        example.setLimitStart((zpSysAccountPo.getCurrentPage()-1)*zpSysAccountPo.getPageSize());       //每页显示的起始行数
        example.setLimitEnd(zpSysAccountPo.getPageSize());  //每页显示的记录数

        if(!zpSysAccountPo.getAccountName().equals("")){
            //example.createCriteria().andAccountNameLike("%" + zpSysAccountPo.getAccountName() + "%");
            example.or().andAccountNameLike("%" + zpSysAccountPo.getAccountName() + "%");
        }

        pageResult.setCurrPage(zpSysAccountPo.getCurrentPage());
        pageResult.setPageSize(zpSysAccountPo.getPageSize());

        pageResult.setTotalCount(zpSysAccountMapper.countByExample(example));
        pageResult.setList(zpSysAccountMapper.selectByExample(example));
        return pageResult;
    }

xml文件

<select id="selectByExample" parameterType="com.zhipu.model.base.entity.ZpSysAccountExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    'false' as QUERYID,
    <include refid="Base_Column_List" />
    from zp_sys_account
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
    <if test="limitStart != null and limitStart>=0" >
      limit #{limitStart} , #{limitEnd}
    </if>
  </select>

另一种分页的思路

@Override
    public PageResult queryPage(ZpSysRolePo zpSysRolePo) {
        PageResult pageResult =new PageResult();
        /*ZpSysAccountRoleExample example = new ZpSysAccountRoleExample();
        example.setLimitStart((zpSysRolePo.getCurrentPage()-1)*zpSysRolePo.getPageSize());       //每页显示的起始行数
        example.setLimitEnd(zpSysRolePo.getPageSize()); //每页显示的记录数
        example.setAccountId(zpSysRolePo.getAccountId());
        pageResult.setCurrPage(zpSysRolePo.getCurrentPage());
        pageResult.setPageSize(zpSysRolePo.getPageSize());

        pageResult.setTotalCount(zpSysAccountRoleMapper.countByExample(example));
        pageResult.setList(zpSysAccountRoleMapper.selectByExample(example));*/

        zpSysRolePo.setLimitStart((zpSysRolePo.getCurrentPage()-1)*zpSysRolePo.getPageSize());       //每页显示的起始行数
        zpSysRolePo.setLimitEnd(zpSysRolePo.getPageSize()); //每页显示的记录数
        pageResult.setCurrPage(zpSysRolePo.getCurrentPage());
        pageResult.setPageSize(zpSysRolePo.getPageSize());
        pageResult.setTotalCount(zpSysRoleMapper.selectCountRolePage(zpSysRolePo));
        System.out.println("selectCountRolePage"+zpSysRoleMapper.selectCountRolePage(zpSysRolePo));
        pageResult.setList(zpSysRoleMapper.selectPageRoleById(zpSysRolePo));
        System.out.println("selectPageRoleById:"+zpSysRoleMapper.selectPageRoleById(zpSysRolePo));

        return pageResult;
    }
 <select id="selectCountRolePage" parameterType="com.zhipu.model.base.po.request.ZpSysRolePo" resultType="java.lang.Integer">
    select count(distinct zr.role_id)
    from zp_sys_role zr left join zp_sys_account_role ar on zr.role_id = ar.role_id
    where ar.account_id = #{accountId,jdbcType=BIGINT}
  </select>

  <select id="selectPageRoleById" parameterType="com.zhipu.model.base.po.request.ZpSysRolePo" resultMap="BaseResultMap">
    select distinct zr.role_id,role_name,remark,update_time,create_time
    from zp_sys_role zr left join zp_sys_account_role ar on zr.role_id = ar.role_id
    where ar.account_id = #{accountId,jdbcType=BIGINT}
    order by zr.role_id
    limit #{limitStart,jdbcType=BIGINT},#{limitEnd,jdbcType=BIGINT}
  </select>

vue表单提交问题

image.png

image.png

@RequestMapping(value = "/task/hrcomplete/{taskid}", method = RequestMethod.POST)
    @ResponseBody
    public ResultData hrcomplete(HttpSession session, @PathVariable("taskid") String taskid, HttpServletRequest req) {
        String userid = (String) session.getAttribute("accountName");
        Map<String, Object> variables = new HashMap<String, Object>();
        String approve = req.getParameter("hrapprove");
        variables.put("hrapprove", approve);
        taskservice.claim(taskid, userid);
        taskservice.complete(taskid, variables);
        return ResultData.createResult(StatusCode.ROCK_CODE_SUCC);
    }

后端接收不到hrapprove的值,所以req.getParameter("hrapprove")为null

image.png

这里的问题是因为enctype属性的问题

<form action="${pageContext.request.contextPath}/fileUpload" enctype="multipart/form-data" method="post">
        用户名:<input type="text" name = "username">
        用户头像:<input type="file" name="filename">
        <input type="submit" value="提交"/>
</form>

解决:如果去掉enctype属性会发现可以获取到值了,所以问题出在enctype这个属性上;

定义和用法

enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。

默认地,表单数据会编码为 "application/x-www-form-urlencoded"。就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值)。

语法

<form enctype="value">

属性值

描述
application/x-www-form-urlencoded在发送前编码所有字符(默认)
multipart/form-data

不对字符编码。

在使用包含文件上传控件的表单时,必须使用该值。

text/plain空格转换为 "+" 加号,但不对特殊字符编码。

 

项目中可以改成通过实体类对象传递数据

@RequestMapping(value = "/task/deptcomplete", method = RequestMethod.POST)
    @ResponseBody
    public ResultData deptcomplete(@RequestBody ZpDeptLeaderAuditPo zpDeptLeaderAuditPo) {
        String userid = getAccount().getAccountName();
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("deptleaderapprove", zpDeptLeaderAuditPo.getDeptleaderapprove());
        System.out.println(variables);
        String taskid = zpDeptLeaderAuditPo.getTaskid();
        //根据任务id和用户领取任务
        taskservice.claim(taskid, userid);
        //根据任务id完成自己节点的任务
        taskservice.complete(taskid, variables);
        return ResultData.createResult(StatusCode.ROCK_CODE_SUCC);
    }

    @RequestMapping(value = "/task/hrcomplete", method = RequestMethod.POST)
    @ResponseBody
    public ResultData hrcomplete(@RequestBody ZpHrLeaderAuditPo zpHrLeaderAuditPo) {
        String userid = getAccount().getAccountName();
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("hrapprove", zpHrLeaderAuditPo.getHrapprove());
        String taskid = zpHrLeaderAuditPo.getTaskid();
        taskservice.claim(taskid, userid);
        taskservice.complete(taskid, variables);
        return ResultData.createResult(StatusCode.ROCK_CODE_SUCC);
    }

activiti数据库表结构详细说明

https://www.cnblogs.com/telwanggs/p/7491564.html

https://www.devdoc.cn/activiti-table-act_ru_identitylink.html

 

表中的字段不能重复

给表中的字段添加唯一索引,这样修改的时候重复的话会抛出异常

@Override
    public ResultData update(ZpSysAccount account) {
        if(StringUtils.isBlank(account.getAccountPwd())){
            account.setAccountPwd(null);
        }else{
            account.setAccountPwd(new Sha256Hash(account.getAccountPwd(), account.getSalt()).toHex());
        }
        account.setUpdateTime(new Date());
        try{
            //修改用户信息
            zpSysAccountMapper.updateByPrimaryKeySelective(account);
            //修改用户与角色关系
            zpSysAccountRoleService.saveOrUpdate(account.getAccountId(), account.getRoleIdList());
            //修改用户与机构关系
            String orgCode = account.getOrgCode();
            ZpSysDepartment zpSysDepartment = zpSysDepartmentMapper.selectByName(orgCode);
            System.out.println("account:"+account);
            System.out.println("zpSysDepartment:"+zpSysDepartment);
            zpSysAccountDepartmentService.saveOrUpdate(account.getAccountId(),zpSysDepartment.getDepartmentId());
            return ResultData.createResult(StatusCode.ROCK_CODE_SUCC);
        }catch (Exception e){
            //System.out.println(e);代码上线时不能打印出异常信息
            return ResultData.createResult(StatusCode.ROCK_CODE_9039);
        }

    }

数据库中的字段类型

数据库中的字段类型为bigint时,前端可能会出现数据与数据库中不一致的情况,这是因为数据大于17位时数据精度问题,这个时候数据库字段应该使用varchar类型

 

缓存和数据库之间如何保持一致性

缓存只做失效,不做更新

原因:数据的安全性,如果说使用缓存来控制比较难,而且缓存性能也会受到很大的限制

基本操作:   

  • 删缓存失败,不去执行update数据库操作
  • 删除缓存成功,更新数据库失败,读的操作会重新更新的缓存中。
  • 删除缓存成功,更新数据库也成功,读的动作也会将新的数据更新到缓存

 

事务配置问题

事物的配置未生效,可以通过在TransactionInterceptor类下的invokeWithinTransaction方法中设置断点debug查看

image.png

解决办法:重新创建了一个mapper, shiroservice不能调用其他service的方法 否的就会使事务失效

image.png

具体原因:https://blog.csdn.net/finalcola/article/details/81197584

 

数据转换报错

java.math.BigDecimal cannot be cast to java.lang.String

解决方法:使用Object类

BigDecimal表示一个大整数,一般情况下很多整型都有个最大值的,但是有时候我们需要处理一些超过这个最大值的值,这个时候就出现了BigDecimal这样的类用于表达大数值,这个错误应该是类型转换过程中出现了问题.

数据从数据库中取出的,把数据库中的整数转成了BigDecimal 类型,不管是什么类型,它们不能强制转换成String类型的,强制转换会报错,强制转换符在引用类型用于父类转子类。而这些类都实现了toString方法可以通过这个方法转成String类型。

数据库字段  LATITUDE 对应的整数:

Object lat = mapparamfirst.get("LATITUDE");

System.out.println(lat.toString());

 

springboot项目mybatis配置文件与@Mapper注解问题

虽然使用了@Mapper注解,而且使用了@MapperScan但是仍然报错Invalid bound statement (not found): com.mapper.UserDao.userInfo

原因:注解未生效,需要在application.yaml中配置

mybatis:
  mapper-locations: classpath*:com/mapper/*.xml

调用接口,对返回的数据进行处理

public Map<String, Object> getColumnData(String loginId, String tenantId, String mIds) {
        Map<String,Object> result = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        try {
            String currentUrl =eventCenterServerUrl + "/v2/api/event/findModelParamsByModelId"
                    + "?mIds=" + mIds + "&tenantId=" + tenantId + "&loginId=" + loginId + "&appCode=" + appId;
            ResponseEntity<Map> response = loadBalance.getForEntity(currentUrl,Map.class);
            logger.info("getColumnData方法中调用的currentUrl:"+currentUrl+"返回结果response:"+response);
            Map responseBody = response.getBody();
            if (responseBody != null) {
                if ((Boolean) responseBody.get("success") && null != responseBody.get("result")) {
//                    List<Map> list = JSONArray.parseArray(responseBody.get("result").toString(), Map.class);
                    Map<String, Object> resultMap = (Map<String, Object>) responseBody.get("result");
                    List<Map<String, Object>> list = (List<Map<String, Object>>) resultMap.get("successData");
                    logger.info("捕获数据: {}", list.size());
                    for (Map<String, Object> map : list) {
                        Object ob = map.get("RSB");
                        if (ob != null) {
                            List<Map<String,Object>> RSBList = (List<Map<String, Object>>) map.get("RSB");
                            if (RSBList.size() > 0) {
                                for (Map<String, Object> rsbMap : RSBList) {
                                    Map<String, Object> resultTmp = new HashMap<>();
                                    resultTmp.put("eventChName",rsbMap.get("RS004"));
                                    resultTmp.put("eventEnName",rsbMap.get("RS003"));
                                    resultList.add(resultTmp);

                                }

                            }
                        }

                    }
                    result.put("result", resultList);
                    logger.info("getColumnData方法返回前端的数据result"+result);
                    return result;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return result;
    }
{
    "success": true,
    "result": {
        "successData": [{
            "RSB": [{
                "RS009": "[]",
                "RS011": "enabled",
                "RS010": 0,
                "RS002": "4bf66e3ff4f34fada456670c89b781cc",
                "RS001": "839d84009cc247e28cfa91a7517b1322",
                "RS012": "tenant_system",
                "RS004": "数值",
                "RS003": "number",
                "RS006": null,
                "RS005": "number",
                "RS008": "",
                "RS007": "second"
            }],
            "RSA": "4bf66e3ff4f34fada456670c89b781cc"
        }],
        "errorData": [{
            "RSA": "4bf66e3ff4f34fada456670c89b781dd",
            "RSC": "[4bf66e3ff4f34fada456670c89b781dd]未查询到对应的事件模型参数信息"
        }]
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值