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 具有唯一性, 查询一