mybatis中的where多条件查询 sql动态查询

<select id="dongtaiSelect" resultMap="BaseResultMap" parameterType="com.hp.bean.Person">
  select * from person p
    <where>
      <if test="id != null and id != '' ">
          p.id=#{id}
      </if>

      <if test="name != null and name != '' ">
          and p.name=#{name}
      </if>

      <if test="gender != null and gender != '' ">
          and p.gender=#{gender}
      </if>

      <if test="birthday != null and birthday != '' ">
          and p.birthday=#{birthday}
      </if>

      <if test="address != null and address != '' ">
          and p.address=#{address}
      </if>

      <if test="score != null and score != '' ">
          and p.score>#{score}
      </if>
    </where>
</select>

测试类

public class MybatisTest {
    //让你讲一下 mybatis的执行流程
    //导包-配置sqlmapconfig链接数据库-用sqlSessionFactory读取xml文件-建立一个工厂类
    private SqlSession sqlSession;
    @Before//在@Test之前 执行的方法 提取重复的代码
    public void before() throws IOException {
        //加载并读取xml
        String path = "SqlMapConfig.xml";
        InputStream is = Resources.getResourceAsStream(path);
        //sql链接的工厂类
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        sqlSession = sqlSessionFactory.openSession();
        System.out.println("sqlSession = " + sqlSession);
        //sqlSession.close();
    }
        @Test
        public void test15(){
            Person person = new Person();
            //person.setId(14);//select * from person where p.id=? 不传参数就是全查
            person.setGender(2);
            person.setScore(100);
//如果传一个null或者不传默认就是全查   传值就是根据条件查
//List<Person> list = sqlSession.selectList("com.hp.dao.PersonDao.dongtaiSelect",null);
            List<Person> list =         sqlSession.selectList("com.hp.dao.PersonDao.dongtaiSelect", person);
            for (Person person1 : list) {
                System.out.println("person1 = " + person1);
            }
            sqlSession.close();
        }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值