When mybatis judges whether int is empty three points should be paid attention to

  • 2021-11-01 03:34:10
  • OfStack

Attention point for mybatis to judge whether int is empty or not

1. When int is empty, it will automatically assign a value of 0, so integer must be used as the attribute value type of javaBean.

2. Attention must be paid to the encapsulated get. set. It's also Integer. Otherwise, an error will be reported.

3. Pay attention to the above two points and judge directly with null

Examples:


public class ExcelPutVo {
 private Integer startTime;//  Start time 
 private Integer endTime;//  Deadline 
 private int sentId;//  Issuer id
 private String onlyUuid;//  Only 1 Identification 
 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;
 }

xml of mybatis


<!--  Export excel Data query of  -->
 <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 maps null to int

This error is reported when mybatis attempts to map an null field to an int type in java.

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

Solution

If this field does not participate in the calculation, the data type in java can be set to String, and the variable of this String reference type can map null.

The same situation is also applicable to the Date type in the database. If the mapping field in java does not need to participate in the calculation, the type in java can be directly set to String. The advantage of this is that the type in mysql is Date, and the query conditions can be directly matched with strings in the following format: yyyy-MM-dd or yyyyMMdd or even yyMMdd, even yy-MM-dd can be matched.

However, for the amount in mysql, 1 should be mapped to BigDecimal in general, which is more accurate.


Related articles: