【Java后端】当数据库中存储的时间为timestamp时的应用

postgreSQL + mybatis + springboot

1 数据库存储类型
postgreSQL数据库

表中时间字段:

名称类型
time_low_limittimestamp
time_up_limittimestamp

因为时间在数据库表中存储的是timestamp类型,因此在java的model类中,与数据库对应的字段类型采用的Date类型。

2 model 类

@Table(name = "class_info")
public class ClassInfo {
    ……
    /**
     * 时间上限
     */
    @Column(name = "time_up_limit")
    private Date timeUpLimit;

    /**
     * 时间下限
     */
    @Column(name = "time_low_limit")
    private Date timeLowLimit;
	……
}

往表内插入数据时,传入时间为时间戳格式的Long型,故而转换成了Date类型。

classInfo.setTimeUpLimit(new Date(reqDTO.getTimeUpLimit()));
classInfo.setTimeLowLimit(new Date(reqDTO.getTimeLowLimit()));
classInfoService.save(caseInfo);

3 通过时间段进行筛选查询
此时传入的时间为字符串类型的时间戳数字,同样最终需要转换成Date类型

// 字符串先转Long类型,Long类型再转Date类型
queryCondition.setTimeUpLimit(new Date(Long.parseLong(value))); // 这里value为字符串类型的时间戳数字

4 mapper.xml文件中关于时间筛查的条件查询sql

  <select id="listByCondition" resultMap="BaseResultMap">
    select * from class_info
    where 1=1
    <if test="timeUpLimit != null">
      and #{timeUpLimit} > time_up_limit
    </if>
    <if test="timeLowLimit != null">
      and time_low_limit > #{timeLowLimit}
    </if>
    <choose>
      <when test="orderField != null">
        order by #{orderField}
      </when>
      <otherwise>
        order by update_time
      </otherwise>
    </choose>
    <choose>
      <when test="orderRule != null">
        #{orderRule}
      </when>
      <otherwise>
        desc
      </otherwise>
    </choose>
  </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值