MyBatis动态SQL,写SQL更爽,springmvc实战pdf

where student_id = #{studentId,jdbcType=INTEGER}

2.2.3 测试

@Test

public void updateByStudentSelective() {

SqlSession sqlSession = null;

sqlSession = sqlSessionFactory.openSession();

StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

Student student = new Student();

student.setStudentId(1);

student.setName(“明明”);

student.setPhone(“13838438888”);

System.out.println(studentMapper.updateByPrimaryKeySelective(student));

sqlSession.commit();

sqlSession.close();

}

结果如下

2.3 在 INSERT 动态插入中使用 if 标签

我们插入数据库中的一条记录, 不是每一个字段都有值的, 而是动态变化的。在这时候使用 if 标签, 可帮我们解决这个问题。

2.3.1 插入条件

只有非空属性才插入。

2.3.2 动态SQL

接口方法

/**

* 非空字段才进行插入

*/

int insertSelective(Student record);

对应的SQL

insert into student

student_id,

name,

phone,

email,

sex,

locked,

gmt_created,

gmt_modified,

#{studentId,jdbcType=INTEGER},

#{name,jdbcType=VARCHAR},

#{phone,jdbcType=VARCHAR},

#{email,jdbcType=VARCHAR},

#{sex,jdbcType=TINYINT},

#{locked,jdbcType=TINYINT},

#{gmtCreated,jdbcType=TIMESTAMP},

#{gmtModified,jdbcType=TIMESTAMP},

这个 SQL 大家应该很熟悉, 毕竟是自动生成的。

2.3.3 测试

@Test

public void insertByStudentSelective() {

SqlSession sqlSession = null;

sqlSession = sqlSessionFactory.openSession();

StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

Student student = new Student();

student.setName(“小飞机”);

student.setPhone(“13838438899”);

student.setEmail(“xiaofeiji@qq.com”);

student.setLocked((byte) 0);

System.out.println(studentMapper.insertSelective(student));

sqlSession.commit();

sqlSession.close();

}

对应的结果

SQL 中, 只有非空的字段才进行了插入。

3 choose 标签

choose when otherwise 标签可以帮我们实现 if else 的逻辑。一个 choose 标签至少有一个 when, 最多一个otherwise。

下面是一个查询的例子。

3.1 查询条件

假设 name 具有唯一性, 查询一

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值