天天看点

updateByExample与updateByExampleSelective&updateByPrimaryKey与updateByPrimaryKeySelective的区别1和使用

在使用MyBatis时,使用逆向工程工具生成一套接口和xml映射文件用于简单的单表操作,而其中有四个比较类似的接口方法,一套是 updateByExample与updateByExampleSelective

另一套updateByPrimaryKey与updateByPrimaryKeySelective

updateByExample与updateByExampleSelective&updateByPrimaryKey与updateByPrimaryKeySelective的区别1和使用

它们的作用是对数据库进行更新操作。

1、updateByExample()按主键更新

更新所有的字段,包括字段为null的也更新

2、updateByExampleSelective()按主键更新值不为null的字段

会对字段进行判断再更新,实体类的属性为null时,mybatis会使用动态sql过滤掉

3、updateByPrimaryKey()按条件更新

对你注入的字段全部更新

4、updateByPrimaryKeySelective()按条件更新值不为null的字段

会对字段进行判断再更新,实体类的属性为null时,mybatis会使用动态sql过滤掉

int updateByPrimaryKey(User record) thorws SQLException 按主键更新

int updateByPrimaryKeySelective(User record) thorws SQLException 按主键更新值不为null的字段

int updateByExample(User record, UserExample example) thorws SQLException 按条件更新

int updateByExampleSelective(User record, UserExample example) thorws SQLException 按条件更新值不为null的字段

建议使用: updateByExampleSelective()

updateByPrimaryKeySelective()

更新想更新的字段

通过逆向工程生成的mapper中的方法如下:

/**
     * 选择性更新数据库记录
     *
     * @param record
     * @param example
     */
    int updateByExampleSelective(@Param("record") SysMenu record, @Param("example") SysMenuExample example);

           

下面是自定义的方法,其中sysMenu 是我们的修改页面中传过来的对象

@Override
    public int updateById(SysMenu sysMenu) {
        SysMenuExample example = new SysMenuExample();
        SysMenuExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(sysMenu.getId());
        return sysMenuMapper.updateByExampleSelective(sysMenu, example);
    }
    
           

updateByExampleSelective方法中 record对象则是我们需要修改的数据,example则是我们需要修改的对象

①updateByPrimaryKey()

//相当于:update user set username='rose', password='5678', 
//email='[email protected]' where id='a01'
User user =new User();
user.setId("a01");
user.setUsername("rose");
user.setPassword("5678");
user.setEmail("[email protected]");
XxxMapper.updateByPrimaryKey(user);
②updateByPrimaryKeySelective()

//相当于:update user set password='7890' where id='a01'
User user = new User();
user.setId("a01");
user.setPassword("7890");
XxxMapper.updateByPrimaryKey(user);
③ updateByExample() 和 updateByExampleSelective()

//相当于:update user set password='6666' where username='jack'
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("jack");
User user = new User();
user.setPassword("6666");
XxxMapper.updateByPrimaryKeySelective(user,example);
updateByExample()更新所有的字段,包括字段为null的也更新
建议使用 updateByExampleSelective()更新想更新的字段