MyBatis知識點複習-07resultType與resultMap講解
上一篇:MyBatis知識點複習-06parameter傳入包裝類查詢條件與map的講解
下一篇:MyBatis知識點複習-08動態SQL
在前面章節中我們已經使用過了resultType,相信你已經和熟練了,但是他其實存在一個弊端,而這個弊端可以用resultMap來解決,那麼具體是什麼呢?下面的學習將爲您講解!
在正式講解前我們做個resultType的返回類型的總結:
簡單類型:double,long,int,String等
POJO單個對象,比如前面文章的User
POJO列表:比如前面文章用的List<User>
本章內容正式講解:
我們來看一下我們的User類(是一個javaBean類)的屬性內容:
private int id;
private String username;// 用戶姓名
private String sex;// 性別
private Date birthday;// 生日
private String address;// 地址
再來看一下我們的user表的字段名字:
會發現他們對應的名字是一模一樣的,但是如果我的user表裏面的username不叫username而是叫name,那麼這個時候如果你還在用resultType就會返回空(當然這裏你大可在sql語句去修改來修正,比如select id,name username , birthday,sex,address from user但這不是通用的好方法),這個時候我們的解決辦法是使用resultMap
下面我來爲大家演示:
先把user表的username屬性名字改爲name
在UserMapper接口裏面添加下面這個方法
public List<User> findUsersByResultMap(User user);
接下來我們需要手動的將對應的名字映射起來,在mapper/UserMapper.xml的mapper標籤下面添加下面內容:
<resultMap id="abcdef" type="user">
<id property="id" column="id"></id>
<result property="username" column="name"></result>
</resultMap>
在mapper/UserMapper.xml文件裏面添加下面內容:
<select id="findUsersByResultMap" resultMap="abcedef" parameterType="user">
select * from user where name = #{username} and sex = #{sex}
</select>
那麼上面添加的兩段內容中,第一個的id與第二個的resultMap爲abcdef,這是要將兩者對應起來,然後
在<resultMap>標籤下我們<id>標籤是寫主鍵的,<result>標籤寫其他的
Test方法內容如下:
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setSex("1");
user.setUsername("張三丰");
List<User> usersByResultMap = mapper.findUsersByResultMap(user);
System.out.println(usersByResultMap);
sqlSession.commit();//提交事務,否則會事務回滾
結果:
上一篇:MyBatis知識點複習-06parameter傳入包裝類查詢條件與map的講解
下一篇:MyBatis知識點複習-08動態SQL