計算機網路常見面試題
動態SQL
if 標籤用來判斷傳遞引數是否滿足條件,效果和java中的 if 不同,下面舉例子
<select id="getBlogListIF" parameterType="map" resultType="com.zhang.pojo.Blog"> select * from mybatis.blog <where> <if test="id!=null"> and id=#{id} </if> <iftest="title!=null"> and title=#{title} </if> <if test="author!=null"> and author=#{author} </if> </where> </select>
這個裡面如果 id 和 title 都不為空,看id and title 這個並集是否滿足資料庫條件 if都可以判斷
=====================================================================================================================================================
choose when標籤類似java的 switch case 標籤
<select id="getBlogListChoose" parameterType="map" resultType="com.zhang.pojo.Blog"> select * from mybatis.blog <where> <choose> <when test="id!=null"> id=#{id}</when> <when test="title!=null"> and title=#{title} </when> <when test="author!=null"> and author=#{author} </when> <otherwise> and views=#{views} </otherwise> </choose> </where> </select>
這個標籤有判斷順序,id title author 如果這三個都為空就會執行otherview語句;如果成立只用判斷一次
Test方法
public void getBlogListChoose() { SqlSession sqlSession = mybatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap<String, Object> map = new HashMap<>(); map.put("id", "bf2b862e164a4626adf75e7f04e0ff4a"); map.put("author", "作者2"); List<Blog> blogList = mapper.getBlogListChoose(map); for (Blog blog : blogList) { System.out.println(blog); } }
只會執行id語句
=====================================================================================================================================================
set if 標籤 用於給資料庫賦值
<update id="UpdateBlog" parameterType="map"> update mybatis.blog <set> <if test="title!=null"> title=#{title}, </if> <if test="author!=null"> author=#{author}, </if> </set> where id=#{id} </update>
=====================================================================================================================================================
for each標籤
<select id="getBlogByForEach" resultType="com.zhang.pojo.Blog"> select * from mybatis.blog <where> <foreach collection="list" item="id" open="and (" close=")" separator="or"> id=#{id} </foreach> </where> </select>
這個比較複雜,首先傳入的引數為List,然後result中不用寫 paramType了,在foreache標籤中傳入 item必須寫 separator是分隔 open 和 close分別是開始和結束
下面看Test方法
@Test public void getBlogByForEacher() { SqlSession sqlSession = mybatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("fc1a7137c65b4944b0e750e0b260b1b4"); arrayList.add("3f90882df7824a0b9565e5b8a5d36ae9"); arrayList.add("a8a6024880274acb8b525b187570c759"); List<Blog> blogByForEach = mapper.getBlogByForEach(arrayList); for (Blog byForEach : blogByForEach) { System.out.println(byForEach); } }
這個可以輸出id分別為三個情況的資料
資料庫表