好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

mybatis判断int是否为空的时候,需要注意的3点

mybatis判断int是否为空的注意点

1、int为空时会自动赋值0,所以必须用integer作为javaBean的属性值类型。

2、必须注意封装的get.set。也是Integer.不然也会报错。

3、注意好以上两个点,直接用null判断

例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

public class ExcelPutVo {

  private Integer startTime; // 开始时间

  private Integer endTime; // 截止时间

  private int sentId; // 下达者id

  private String onlyUuid; // 唯一标识

  public int getSentId() {

  return sentId;

  }

 

  public void setSentId( int sentId) {

  this .sentId = sentId;

  }

 

  public String getOnlyUuid() {

  return onlyUuid;

  }

 

  public void setOnlyUuid(String onlyUuid) {

  this .onlyUuid = onlyUuid;

  }

  public Integer getStartTime() {

  return startTime;

  }

 

  public void setStartTime(Integer startTime) {

  this .startTime = startTime;

  }

 

  public Integer getEndTime() {

  return endTime;

  }

 

  public void setEndTime(Integer endTime) {

  this .endTime = endTime;

  }

mybatis的xml

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<!-- 导出excel的数据查询 -->

  < select id = "selectByExcelPutVo" resultMap = "BaseResultMap"

  parameterType = "com.zeng.zhdj.wy.entity.vo.ExcelPutVo" >

  select *

  from count_use

  < where >

  1=1

  < if test = "sentId != null" >

  and sent_id=#{sentId,jdbcType=INTEGER}

  </ if >

  < if test = "endTime != null" >

  and count_end_month &lt;=#{endTime,jdbcType=INTEGER}

  </ if >

  < if test = "startTime!= null" >

  and count_start_month &gt;=#{startTime,jdbcType=INTEGER}

  </ if >

  < if test = "onlyUuid != null" >

  and only_type=#{onlyUuid,jdbcType=VARCHAR}

  </ if >

  </ where >

  </ select >

mybatis 映射 null 为 int 时报错

当 mybatis 试图把 null 字段映射到 java 中的 int 类型时,会报这个错。

Caused by: java.lang.RuntimeException: Error setting property 'setTotal_count' of 'com.webank.ccs.benefit.data.BenefitJobStatBOA@3973f34c'. Cause: java.lang.IllegalArgumentException

解决方法

如果这个字段不参与计算,则 java 中的数据类型可以设置为 String,这个 String 引用类型的变量就可以映射 null 了。

同样的情况还适应于数据库中的 Date 类型,若 java 中的映射字段不需要参与计算,则可以直接设置 java 中的类型为 String,这样做的好处是,mysql 中的类型为 Date 类型,查询条件可以直接使用如下格式的字符串去匹配: yyyy-MM-dd 或 yyyyMMdd 甚至是 yyMMdd,甚至是 yy-MM-dd 都可以匹配。

但是对于 mysql 中的金额,一般情况下要映射为 BigDecimal ,这样精确一些。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/m0_38089615/article/details/79379277

查看更多关于mybatis判断int是否为空的时候,需要注意的3点的详细内容...

  阅读:15次