<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(); }
}