39

springboot~Integer和int如何选择,Integer的意义何在

 5 years ago
source link: http://www.cnblogs.com/lori/p/9948305.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

今天说一下自己在项目中遇到的问题,然后总结一下Integer引用类型和int值类型

关于默认值

  1. Integer默认为null
  2. int默认为0

为什么把数据实体设计成Integer或者不是int

大叔认识,这样设计有助于我们区分这个字段是否被设置过,或者说是否被set过,而对于Integer来说,如果没有被set过,它一定是null(当然你把它强制改为null除外),而对于int来说,你无法区别0和默认值,因为它默认就是0,我觉得这是最重要的一点。

  1. 可以区分属性是否被设置过值

QueryWrapper里更加适合Integer

QueryWrapper是一个mybatis里的查询构造器,你可以为实体属性赋值,然后以它为一个依据,去查询与它匹配的结果集,当你没有为属性赋值时,它是null,(而对于int来说,它是0,0往往是有意义的,在QueryWrapper里,你无法忽略int的属性,这是十分尴尬的)。

例子,两个实体

public class UserInfo extends BaseEntity {

  private String name;
  private String email;
  private Integer age;
}

public class UserInfo extends BaseEntity {

  private String name;
  private String email;
  private int age;
}

在QueryWrapper里进行条件的构造

UserInfo query = new UserInfo();
    query.setName("lind");
    query.setEmail("[email protected]"); //当没有设置Age属性时,它是null,在QueryWrapper里将被忽略,即查询所有Age
    UserInfo dbUser = userInfoMapper.selectOne(new QueryWrapper<>(query));
    System.out.println(dbUser);
    Assert.assertEquals("lind", dbUser.getName());

上面的代码中,如果把Age改成int类型,那它只能查询出Age=0的数据,这不是我们所希望的!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK