mybatis 数组 添加_MyBatis动态SQL(认真看看, 以后写SQL就爽多了)

3.2 动态SQL接口方法/*** - 当 studen_id 有值时, 使用 studen_id 进行查询;* - 当 studen_id 没有值时, 使用 name 进行查询;* - 否则返回空*/Student selectByIdOrName(Student record);对应的SQL< selectid= "selectByIdOrName"resultMap= "BaseRes...
摘要由CSDN通过智能技术生成

3.2 动态SQL

接口方法

/**

* - 当 studen_id 有值时, 使用 studen_id 进行查询;

* - 当 studen_id 没有值时, 使用 name 进行查询;

* - 否则返回空

*/

Student selectByIdOrName(Student record);

对应的SQL

< selectid= "selectByIdOrName"resultMap= "BaseResultMap"parameterType= "com.homejim.mybatis.entity.Student">

select

fromstudent

where1= 1

< whentest= "studentId != null">

andstudent_id= #{studentId}

when>

< whentest= "name != null and name != ''">

andname= #{name}

when>

and1= 2

select>

3.3 测试

@ Test

publicvoidselectByIdOrName() {

SqlSession sqlSession = null;

sqlSession = sqlSessionFactory.openSession();

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

Student student = newStudent();

student.setName( "小飞机");

student.setStudentId( 1);

Student studentById = studentMapper.selectByIdOrName(student);

System. out.println( "有 ID 则根据 ID 获取");

System. out.println(ToStringBuilder.reflectionToString(studentById, ToStringStyle.MULTI_LINE_STYLE));

student.setStudentId( null);

Student studentByName = studentMapper.selectByIdOrName(student);

System. out.println( "没有 ID 则根据 name 获取");

System. out.println(ToStringBuilder.reflectionToString(studentByName, ToStringStyle.MULTI_LINE_STYLE));

student.setName( null);

Student studentNull = studentMapper.selectByIdOrName(student);

System. out.println( "没有 ID 和 name, 返回 null");

Assert.assertNull(studentNull);

sqlSession.commit();

sqlSession.close();

}

有 ID 则根据 ID 获取, 结果

没有 ID 则根据 name 获取

没有 ID 和 name, 返回 null

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值