1>查詢所有操作
<!--配置查詢所有--><selectid="fingetUser"resultType="cn.mybatis.domain.User">
select * from user;
</select>
2>添加信息操作
<!--保存用戶--><insertid="saveUser"parameterType="cn.mybatis.domain.User">
insert into user(username,address,sex,birthday)values (#{username},#{address},#{sex},#{birthday});
</insert>
3>更改信息操作
<!--更新用戶--><updateid="updateUser"parameterType="cn.mybatis.domain.User">
update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday}
where id=#{id};
</update>
4>刪除信息操作
<!--刪除用戶--><deleteid="deleteUser"parameterType="java.lang.Integer">
delete from user where id=#{userid};
</delete>
5>根據單個信息來查詢數據
<!--根據id查詢用戶--><!--同時需要返回結果集需要告訴返回值是什麼類型--><selectid="getUserByid"parameterType="java.lang.Integer"resultType="cn.mybatis.domain.User">
select * from user where id=#{userid};
</select>
6>模糊查詢的操作
注意:要在調用該方法的時候添加% %
<!--使用模糊查詢查詢到用戶的數據--><selectid="getUserbyname"parameterType="String"resultType="cn.mybatis.domain.User">
select * from user where username like #{name};
</select>
7>使用聚合函數查詢記錄的總數
<!--使用聚合函數count查詢user表中的用戶數據--><selectid="userCount"resultType="int">
select count(id)from user;
</select>
注意:
select * from user where username like '%${value}%';
執行的Sql語句是 select * from user where username like'%王%'(使用的是Statement的拼接S ql)
select *from user where username like #{name};
執行的Sql語句是 select * from user where username like ?;(使用的是prepateStatement的佔位符)
8>在插入操作之前的到添加數據的編號
<!--配置插入操作後獲取插入數據的返回值id--><!-- keyProperty:實體類名稱 order:執行順序 resultType:返回類型--><selectKeykeyProperty="id"order="AFTER"resultType="java.lang.Integer">
select last_insert_id();
</selectKey>
9>#{}和${}的區別
#{}表示一個佔位符號
通過#{}可以實現preparedStatement向佔位符中設置值,自動進行java類型和jdbc類型轉化#{}可以有效的防止Sql注入,#{}可以接收簡單類型值或pojo屬性值,如果paremeterType傳輸單個簡單類型值,#{}括號中可以是value或是其他值
${}表示拼接字符串
通過${}可以將paramererType傳入的內容拼接在Sql中且不進行jdbc類型轉換,${}可以接收簡單類型值或pojo屬性值,如果parameterType傳輸單個簡單類型值,${}括號中只能是value
注:源碼中指定了讀取的key的名字就是value所以我們就只能叫做value
在實體類名和數據名不同的時候怎麼操作
1>在配置數據庫文件的時候更改Sql語句(執行效率更快)
select * from user where username as userName;
2>在配置數據庫文件中添加對應關係(執行順序相對慢)
<!--配置查詢結果的列名和實體列屬性的對應關係--><resultMapid="userMap"type="cn.mybatis.domain.User"><!--主鍵字段的對應--><idproperty="userid"column="id"></id><!--非主鍵字段的對應--><resultproperty="userName"column="username"></result><resultproperty="userAddress"column="address"></result><resultproperty="userSex"column="sex"></result><resultproperty="userBirthday"column="birthday"></result></resultMap>
在需要調用的屬性添加resultMap="userMap";
1>
動態SQLMyBatis最強大的特性之一一直是它的動態SQL功能。如果您有使用JDBC或任何類似框架的經驗,就會理解有條件地將SQL字符串連接在一起是多麼痛苦,請確保不要忘記空格或忽略列列表末尾的omma。處理動態SQL可能非常困難。雖然使用動態SQL永遠不會有什麼好處,但是MyBatis使用了一種強大的動態SQL語言,可以2>2>
在任何映射的SQL語句中使用,這無疑改善了這種情況。
3>
使用過JSTL或任何類似的基於XML的文本處理器的人都應該熟悉動態SQL元素。在MyBatis的早期版本中,有很多需要了解和理解的元素。MyBatis大大改進了這一點,現在只有不到一半的元素。處理。MyBatis使用強大的基於OGNL的表達式來消除大部分其他元素:ifchoose(when,otherwise)trim(where,set)
foreach
4>動態Sql之<if>標籤
<select id="findByUser" resultType="user" parameterType="user">
select * from user where1=1<if test="username!=null and username!=''">
and username like #{username}<if test="address!=null">
and address like #{username}</select>
注意:<if>標籤的test屬性中寫的是對象的屬性名,如果包裝類的對象要使用OGNL表達式的寫法另外要注意where 1=1的作用(使條件爲真)5>動態標籤之<where>標籤
爲了簡便上面 where 1=1的操作我們可以使用where來簡便
擴展:抽取查詢語句中的重複語句:最終達到Sql可以重用的作用
<!--抽取重複的Sql語句--><sql id="defaultUser">
select * from user
</sql><select id="findByUser" resultType="user" parameterType="user"><include refid="defaultUser"></include><where><if test="username!=null and username!=''">
and username like #{username}<if test="address!=null">
and address like #{username}<where></select>
注意:在編寫Sql的時候儘量不要去加分號
/*The error may exist in com/itxu/Dao/IUserDao.xml
### The error may involve cn.mybatis.Dao.IUserDao.findUserInIds-Inline
### The error occurred while setting parameters
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ';*/6>動態標籤之<foreach>標籤
當需求發生改變:
傳入多個 id 查詢用戶信息,用下邊兩個 sql 實現:
SELECT * FROM USERS WHERE username LIKE '%張%' AND (id =10 OR id =89 OR id=16) SELECT * FROM USERS WHERE username LIKE '%張%' AND id IN (10,89,16)
這樣我們在進行範圍查詢時,就要將一個集合中的值,作爲參數動態添加進來。 這樣我們將如何進行參數的傳遞?
持久層Dao映射配置的編寫:<!--查詢所在用戶的id集合--><select id="findInids" resultType="user" parametrType="cn.mybatis.domian.QueryVo"><!--select * from user where id in(1,2,3,4)--><include refid="defaultUser"></include><where><if text="ids!=null and ids.size()>0"></if><foreach collection="ids" open="id in(" close=")" item="uid" separator=",">
#{uid}</foreach></where></select>
Sql語句:select * from user where id in(?);<foreach>標籤用於遍歷集合他們的屬性分別是:
collection:代表要遍歷的集合元素,注意編寫的時候不要寫${}
open:代表語句的開始部分
close:代表語句的結束部分
item:代表遍歷集合的每個元素生成的變量名
separator:代表分隔符
9.Mybatis中的多表查詢
1>表之間的關係有幾種
一對多
多對一
一對一
多對多
舉例:
用戶和訂單就是(一對多)
一個用戶可以下多個訂單/多個訂單屬於同一個用戶
人和身份證就是(一對一)
一個人只能有一個身份證號/一個身份證號只能有一個人
學生和老師就是(多對多)
一個學生可以被多個老師教過/一個老師可以教多個學生
特例:
如果拿出每一個訂單/他都只能屬於一個用戶所以Mybatis中就把多對一看成了一對一
mybatis中的多表查詢:
一個用戶可以有多個賬戶/一個賬戶只能屬於一個用戶(多個賬戶也可以屬於同一個用戶)
步驟:1.建立兩張表:用戶表和賬戶表
讓用戶表和賬戶表之間具備一對多的關係:需要使用外鍵在賬戶表中添加
2.建立兩個實體類:用戶實體類和賬戶實體類
讓用戶和賬戶的實體類能體現出一對多的關係
3.建立兩個配置文件
4.實現配置:
當我們查詢用戶時可以同時得到用戶下所包含的賬戶信息
當我們查詢賬戶時,可以同時得到賬戶的所屬用戶信息
實現多對多關係的案例:1.建立兩張表:用戶表,角色表
讓用戶和角色表具有多對多關係,需要使用中間表,中間表中包含各自的主鍵,在中間表是外鍵
2.建立兩個實體類:用戶實體類和角色實體類
讓用戶和角色的實體能體現出來多對多的關係
各自包含對方一個集合引用
3.建立兩個配置文件
用戶的配置文件
角色的配置文件
4.實現配置
當我們查詢用戶的時候,可以同時得到用戶所包含的角色信息
當我們查詢角色的時候,可以同時得到角色的所賦予的用戶信息
2>.一對一關係
//從表實體應該包含主表實體的對象引用private User user;
並且需要編寫配置文件
<resultMap id="accountUserMap" type="cn.mybatis.domain.Account"><id property="id" column="aid"></id><result property="uid" column="uid"></result><result property="money" column="money"></result><!--一對一的關係映射--><association property="user" column="uid" javaType="User"><id property="id" column="id"></id><result property="username" column="username"></result><result property="address" column="address"></result><result property="sex" column="sex"></result><result property="birthday" column="birthday"></result></association></resultMap>
SQL: select a.*,u.username,u.address from account a,user u where u.id=a.uid;3>.一對多關係
//主體表中應該包含從表的集合private List<Account> accounts;
並且需要編寫配置文件
<!--定義User的ResultMap--><resultMap id="userAccountMap" type="user"><id property="id" column="id"></id><result property="username" column="username"></result><result property="address" column="address"></result><result property="sex" column="sex"></result><result property="birthday" column="birthday"></result><!--配置User對象中account集合的映射--><collection property="accounts" ofType="Account"><id property="id" column="id"></id><result property="uid" column="uid"></result><result property="money" column="money"></result></collection></resultMap>
Sql: SELECT * from user u LEFT OUTER JOIN account a on u.id=a.uid;4>多對多關係
//通過中間表建立關係分別在主表和從表中添加相應的集合private List<User>users;private List<Role>roles;<!--在雙方的配置文件配置對應得ResultMap和collection-->
IUserDao.xml
<resultMap id="UserRoleMap" type="user"><id property="id" column="id"></id><result property="username" column="username"></result><result property="address" column="address"></result><result property="sex" column="sex"></result><result property="birthday" column="birthday"></result><collection property="roles" ofType="role">//定義集合<id property="roleid" column="id"></id><result column="role_name" property="rolename"></result><result column="role_desc" property="roledesc"></result></collection></resultMap>
IRoleDao.xml<和mapper同><resultMap id="RoleMap" type="role"><id property="roleid" column="id"></id><result property="rolename" column="role_name"></result><result property="roledesc" column="role_desc"></result><collection property="users" ofType="user"><id property="id" column="id"></id><result property="username" column="username"></result><result property="address" column="address"></result><result property="sex" column="sex"></result><result property="birthday" column="birthday"></result></collection></resultMap>
Sql: select u.*,r.ROLE_NAME,r.ROLE_DESC from role r LEFT OUTER JOIN user_role ur on r.ID=ur.RID
LEFT OUTER JOIN user u on u.id=ur.uid;
雙左聯雙查詢條件
>>M共有四種註解方式
@SELECT@UPDATE@INSERT@DELETE1>查詢所有
@Select("select * from user")2>添加數據
@INSERT("INSERT INTO USER(username,address,sex,birthday) VALUES(#{username},#{address},#{sex},#{birthday})")3>修改數據
@UPDATE("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}")4>刪除數據
@DELETE("delete from user where id=#{id}")5>查詢一個用戶
@Select("select * from user where id=#{id}")6>模糊查詢
@Select("select * from user where username like #{username}")@Select("select * from user where username like '%${value}%'")7>實體類名與數據庫名不相同的解決方案
@Results(id ="userMap",value ={@Result(id=true,column ="id",property ="userId"),@Result(column ="username",property ="userName"),@Result(column ="address",property ="userAddress"),@Result(column ="sex",property ="userSex"),@Result(column ="birthday",property ="userBirthday"),})@ResultMap(value={"userMap"})//引用上邊的註解8>Mybatis基於註解開發的一對多或者是多對一的註解配置
一:@Result(property ="user",column ="uid",one=@One(select="cn.mybatis.Dao.UserDao.findUserByid",fetchType= FetchType.EAGER))
多:@Result(property ="accounts",column ="id",
many =@Many(select ="cn.mybatis.Dao.AccountDao.findUserByuid",
fetchType = FetchType.LAZY))9>Mybatis基於註解開發配置二級緩存