Mybatis-Mapper.xml輸入輸出對映
在Mybatis中,Mapper.xml主要負責對資料庫的具體操作,即增、刪、改、查等相關操作,
對於mapper.xml,我們需要掌握一些常用的標籤,下面做出介紹。
首先,先對此次講解資料庫表做一個說明,資料庫表字段為id、username、sex、birthday、address
使用JavaBean物件實現對映類如下:
package com.sw.po; import java.util.Date; /* *@Author swxctx *@time 2016年11月30日 *@Explain:屬性名與表的欄位對應 */ public class User { private int id; private String username;// 使用者姓名 private String sex;// 性別 private Date birthday;// 生日 private String address;// 地址 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]"; } }
parameterType-輸入對映
parameterType即為輸入型別,在Mybatis中,我們對資料庫進行相關操作時,則會對sql傳入一些值,那麼這些值都有其相應的資料型別。
佔位符#{}、${}
#{}與${}在開發中比較常用,在sql具有變數時俊輝使用到#{}與${}
#{}實現的是向prepareStatement中的預處理語句中設定引數值,sql語句中#{}表示一個佔位符,即類似於Hibnernate的PareStatement中的?。
<!-- 根據id查詢使用者資訊 --> <select id="findUserById" parameterType="int" resultType="user"> select * from user where id = #{id} </select>
使用佔位符#{}可以防止sql注入,在使用時不需要關心引數值的型別,mybatis會自動進行java型別和jdbc型別的轉換。
#{}可以接收簡單型別值或pojo屬性值,如果parameterType傳輸單個簡單型別值,#{}括號中可以是value或其它名稱。
${}和#{}不同,通過${}可以將parameterType傳入的內容拼接在sql中且不進行jdbc型別轉換, ${}可以接收簡單型別值或pojo屬性值,如果parameterType傳輸單個簡單型別值,${}括號中只能是value。使用${}不能防止sql注入,但是有時用${}會非常方便,如下的例子:
<!-- 根據名稱模糊查詢使用者資訊 --> <select id="selectUserByName" parameterType="string" resultType="user"> select * from user where username like '%${value}%' </select>
如果本例子使用#{}則傳入的字串中必須有%號,而%是人為拼接在引數中,顯然有點麻煩,如果採用${}在sql中拼接為%的方式則在呼叫mapper介面傳遞引數就方便很多。
//如果使用佔位符號則必須人為在傳引數中加%
List<User> list = userMapper.selectUserByName("%解%");
//如果使用${}原始符號則不用人為在引數中加%
List<User>list = userMapper.selectUserByName("解");
比如order by排序,如果將列名通過引數傳入sql,根據傳的列名進行排序,應該寫為:
ORDER BY${columnName}
如果使用#{}將無法實現此功能。
傳遞pojo物件
在Mybatis中,可使用ognl表示式解析物件欄位的值,如下配置所示:
<!—傳遞pojo物件綜合查詢使用者資訊 -->
<select id="findUserByUser" parameterType="user" resultType="user">
select * from user where id=#{id} and username like '%${username}%'
</select>
#{id}與{username},這裡的id與username表示的是user物件中的屬性名稱。
其中paramwterType=“user”則表示其輸入型別為User物件,即使用User物件中的相關屬性。
傳遞pojo包裝物件
開發中通過pojo傳遞查詢條件 ,查詢條件是綜合的查詢條件,不僅包括使用者查詢條件還包括其它的查詢條件(比如將使用者購買商品資訊也作為查詢條件),
這時可以使用包裝物件傳遞輸入引數。
package com.sw.po;
import java.util.List;
/*
*@Author swxctx
*@time 2016年12月2日
*@Explain:包裝所需要的查詢條件(亦可包裝其他物件的查詢資訊)-包裝型別
*/
public class UserQueryVo {
//傳入多個id
private List<Integer> ids;
//使用者查詢條件
private UserCustom userCustom;
public UserCustom getUserCustom() {
return userCustom;
}
public void setUserCustom(UserCustom userCustom) {
this.userCustom = userCustom;
}
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
對映物件的擴充套件類如下:
package com.sw.po;
/*
*@Author swxctx
*@time 2016年12月2日
*@Explain:User類的擴充套件類
*/
public class UserCustom extends User{
//可以擴充套件使用者的資訊
}
包裝物件定義完成後,我們就可以在mapper.xml檔案中進行相關的配置:
<select id="findUserList" parameterType="com.sw.po.UserQueryVo" resultType="com.sw.po.UserCustom">
select *from user where username=#{username}
</select>
傳遞HashMap
在Mybatis中,亦可通過HashMap輸入值,其mapper.xml配置如下:
<!-- 傳遞hashmap綜合查詢使用者資訊 -->
<select id="findUserByHashmap" parameterType="hashmap" resultType="user">
select * from user where id=#{id} and username like '%${username}%'
</select>
如上,#{id}與{username}則表示hashmap中的對應key值,經過配置後,配置檔案會自動到程式碼中尋找key為id的欄位,如果沒有,則會出現異常。測試程式碼如下:
Public void testFindUserByHashmap()throws Exception{
//獲取session
SqlSession session = sqlSessionFactory.openSession();
//獲限mapper介面例項
UserMapper userMapper = session.getMapper(UserMapper.class);
//構造查詢條件Hashmap物件
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("id", 1);
map.put("username", "Swxctx");
//傳遞Hashmap物件查詢使用者列表
List<User>list = userMapper.findUserByHashmap(map);
//關閉session
session.close();
}
ResultType-輸出對映
輸出型別即為Mybatis執行sql之後結果的輸出型別。
簡單輸出型別
簡單輸出型別即為常見的資料型別,我們從下面的例子進行理解。
Mapper.xml配置檔案:
<!-- 獲取使用者列表總數 -->
<select id="findUserCount" parameterType="user" resultType="int">
select count(1) from user
</select>
如上所示,resultType=“int”,即表示sql執行輸出結果為int型的,從sql不難看出,該sql的作用是查詢出資料庫表的資料總條數,自然其應該為
int型下符合需求。
在這裡,不只是int型的資料可用,在實際開發中,我們還會用到例如String、Date、Boolean等資料型別,此類即為常用簡單輸出型別。
輸出poio物件
輸出poio物件,顯然,在執行sql之後,我們輸出的是一個物件;那麼如何理解呢,其實結合poio物件來進行理解,也就不難。
例如:現在需要根據使用者id查詢出一個使用者,並且顯示該使用者所有資料
在前面我們已經介紹過類似JavaBean與資料庫表的對映,即為poio物件,poio物件的屬性對應了資料庫表的欄位,要想輸出所有資料,那嚒
我們輸出poio物件,是否就將資料全部輸出了呢?答案是肯定的,輸出poio物件,即輸出了所有的屬性資訊。(注:只能輸出一條資訊,類似於selectOne())
為了加深理解,我們可以通過下面例子進行理解:
mapper.xml檔案:
<!-- 根據id查詢使用者資訊 -->
<select id="findUserById" parameterType="int" resultType="user">
select * from user where id = #{id}
</select>
mapper介面:
public User findUserById(int id) throws Exception;
測試類:
Public void testFindUserById() throws Exception {
//獲取session
SqlSession session = sqlSessionFactory.openSession();
//獲限mapper介面例項
UserMapper userMapper = session.getMapper(UserMapper.class);
//通過mapper介面呼叫statement
User user = userMapper.findUserById(1);
System.out.println(user);
//關閉session
session.close();
}
輸出pojo列表
輸出pojo列表與上面的輸出pojo差別並不大,唯一的差別就是:輸出物件輸出的是一個物件,而輸出物件列表則可以輸出多條資料。
例如:查詢所有使用者名稱有‘解’的使用者,顯然可能會有很多使用者。因此,我們需要使用輸出poio列表的方式進行輸出。
例項:mapper.xml
<!-- 根據名稱模糊查詢使用者資訊 -->
<select id="findUserByUsername" parameterType="string" resultType="user">
select * from user where username like '%${value}%'
</select>
mapper介面
public List<User> findUserByUsername(String username) throws Exception;
測試類:
Public void testFindUserByUsername()throws Exception{
//獲取session
SqlSession session = sqlSessionFactory.openSession();
//獲限mapper介面例項
UserMapper userMapper = session.getMapper(UserMapper.class);
//如果使用佔位符號則必須人為在傳引數中加%
//List<User> list = userMapper.selectUserByName("%管理員%");
//如果使用${}原始符號則不用人為在引數中加%
List<User> list = userMapper.findUserByUsername("管理員");
//關閉session
session.close();
}
輸出HashMap
輸出pojo物件可以改用hashmap輸出型別,將輸出的欄位名稱作為map的key,value為欄位值。
resultMap-高階輸出對映
resultType可以指定pojo將查詢結果對映為pojo,但需要pojo的屬性名和sql查詢的列名一致方可對映成功。
如果sql查詢欄位名和pojo的屬性名不一致,可以通過resultMap將欄位名和屬性名作一個對應關係 ,resultMap實質上還需要將查詢結果對映到pojo物件中。
resultMap可以實現將查詢結果對映為複雜型別的pojo,比如在查詢結果對映物件中包括pojo和list實現一對一查詢和一對多查詢。
resultMap的定義:
<!-- 定義ResultMap
將select id id_,username username_ from user where id=#{id}查詢出來的列與
pojo(User)類中的屬性做對映(對應關係)
type:ResultMap最終所對映的Java物件型別(可使用別名)
id:對ResultType於ResultMap的唯一標識
-->
<resultMap type="user" id="userResultMap">
<!-- 查詢結果集中的唯一標識(對應於資料庫表中欄位的唯一標識)
colum:查詢出的列名
property:pojo的屬性名字(Type指定的pojo物件
最終resultMap對column和property進行對映(做對映關係)
-->
<id column="id_" property="id"/>
<!-- 對普通列的對映定義 -->
<result column="username_" property="username"/>
</resultMap>
定義好之後,我們就可以在mapper.xml檔案中進行使用了,如下:
<!-- 使用ResultMap進行輸出的對映
ResultMap:指定已定義的ResultMap的id(該ResultMap在其他的Mapper檔案中,需要在前面加上namespace進行指定)
-->
<select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
select id id_,username username_ from user where id=#{id}
</select>
到這裡呢,mapper.xml的常用的標籤就完成了,但是還有一個重要的東西,即動態sql,動態sql在Mybatis的開發中十分重要,
那麼打算分開進行介紹,在編寫完成後會在此處打上鍊接。
動態Sql文章連結如下(2017-3)