From getting started to giving up MyBatis 2: Passing parameters, mybatis getting up
Preface
We write SQL statements in mapper. xml. If they are all one parameter, we directly configure parameterType. How can we deal with multiple parameters in the actual business development process?
From the MyBatis API, we find that the selectOne and selectquota Methods reload the first statement and the second Object. Then we use Map to transmit multiple parameters.
Preparations
The development environment, pom. xml, mapper. xml, and log4j. properties are the same as above.
Mapper. xml SQL implementation
<select id="queryUserByAddress" resultType="com.autohome.model.User"> select * from t_userinfo where name=#{name,javaType=String,jdbcType=VARCHAR} and address=#{address} </select>
Unit Test
Create a Map parameter. The map key value corresponds to the mapper SQL parameter name.
@Test public void queryUserByNameAddress(){ SqlSession sqlSession=null; try{ sqlSession=sqlSessionFactory.openSession(); Map<String,Object> map =new HashMap<String,Object>(); map.put("name","kobe"); map.put("address","usa"); User user = sqlSession.selectOne("com.autohome.mapper.User.queryUserByAddress",map); System.out.println("id:"+user.getId()+",name:"+user.getName()+","+user.getAddress()); }catch(Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
Use RowBounds for paging
When reading the mybatis API, we found the rowbounds parameter, which can be used to implement paging. However, it is not directly implemented in SQL, but data paging is implemented based on the query result set, which is available in a small quantity, large data volumes are not recommended, and the right is to make a demo.
@Test public void queryPagedUsers(){ SqlSession sqlSession=null; try { sqlSession=sqlSessionFactory.openSession(); RowBounds row=new RowBounds(10, 10); List<User> list = sqlSession.selectList("com.autohome.mapper.User.queryUsers",null,row); System.out.println("size:"+list.size()); for (User user:list){ System.out.println("id:"+user.getId()+",name:"+user.getName()+","+user.getAddress()); } } catch (Exception e) { e.printStackTrace(); }finally { sqlSession.close(); } }
Attached DEBUG
Summary
When I first learned java, I always did not know where to start learning it. I finally fell into the door and concluded that there are no shortcuts to learning java, only the demo can be used to read documents, the demo can be used to read documents, and the demo can be used to read documents.