Myatis的使用執(zhí)行流程:
1.創(chuàng)建SqlMapConfig.xml配置文件件舵,配置連接數(shù)據(jù)庫(kù)的參數(shù)信息和mapper的映射對(duì)象
2.SqlSessionFactoryBuilder讀取SqlMapConfig.xml文件流漂辐,構(gòu)建出SqlSessionFactory對(duì)象
3.SqlSessionFactory讀取SqlMapConfig.xml中的信息產(chǎn)生真正操作數(shù)據(jù)庫(kù)的SqlSession對(duì)象
4.SqlSession利用getMapper(ClassType)用來(lái)生成代理接口對(duì)象凉唐,定義通用的增刪改查方法,還可以對(duì)事務(wù)進(jìn)行提交,回滾,關(guān)閉資源等操作
5.注解和xml的開(kāi)發(fā)方式示例:
注解:
@Select("select * from user")
public List<User> findAll();
xml:
<mapper namespace="com.haha.dao.UserDao">
<select id="findAll" resultType="user">
select * from user
</select>
<select id="findById" parameterType="java.lang.Integer" resultType="com.haha.domain.User">
select * from user where id=#{uid};
</select>
</mapper>
1.基于代理 Dao 實(shí)現(xiàn) CRUD 操作
查詢操作:
<!-- 根據(jù) id 查詢 -->
<select id="findById" resultType="com.haha.domain.User" parameterType="int">
select * from user where id = #{uid}
</select>
細(xì)節(jié):
resultType 屬性:用于指定結(jié)果集的類(lèi)型博个。
parameterType 屬性:用于指定傳入?yún)?shù)的類(lèi)型镰官。
sql 語(yǔ)句中使用#{}字符:它代表占位符癣朗, 相當(dāng)于原來(lái) jdbc 部分所學(xué)的'?',都是用于執(zhí)行語(yǔ)句時(shí)替換實(shí)際的數(shù)據(jù),具體的數(shù)據(jù)是由#{}里面的內(nèi)容決定的捏萍。
保存操作:
<!-- 保存用戶-->
<insert id="saveUser" parameterType="com.haha.domain.User">
insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})
</insert>
<!-- 保存用戶并返回用戶的id-->
<insert id="saveUser" parameterType="USER">
<!-- 配置保存時(shí)獲取插入的 id -->
<selectKey keyColumn="id" keyProperty="id" resultType="int">
select last_insert_id();
</selectKey>
insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address})
</insert>
更新操作:
<update id="updateUser" parameterType="com.haha.domain.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},
address=#{address} where id=#{id}
</update>
刪除操作:
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id = #{uid}
</delete>
模糊查詢:
使用concat()進(jìn)行字符拼接法:
List<User> findUser(@Param("name") String name);
<select id="findUser" resultType="com.haha.domain.User" parameterType="String">
select * from user where name like concat('%',#{name},'%')
</select>
事先在代碼中將各個(gè)參數(shù)拼接好"%",然后在dao層指定各個(gè)參數(shù)的別名方法:
List<USer> findUser(@Param("name") String name,@Param("address") String address);
<select id="findUser" resultType="com.haha.domain.User" parameterType="String">
select * from user where name like #{name} or address like #{address}
</select>
聚合函數(shù)查詢:
<select id="findTotal" resultType="int">
select count(*) from user;
</select>
resultMap 結(jié)果類(lèi)型:
resultMap 標(biāo)簽可以建立查詢的列名和實(shí)體類(lèi)的屬性名稱不一致時(shí)建立對(duì)應(yīng)關(guān)系。從而實(shí)現(xiàn)封裝空闲。在 select 標(biāo)簽中使用 resultMap 屬性指定引用即可令杈。同時(shí) resultMap 可以實(shí)現(xiàn)將查詢結(jié)果映射為復(fù)雜類(lèi) 型的 pojo,比如在查詢結(jié)果映射對(duì)象中包括 pojo 和 list 實(shí)現(xiàn)一對(duì)一查詢和一對(duì)多查詢碴倾。
1.定義resultMap:
<resultMap type="com.haha.domain.User" id="userMap">
<id column="id" property="userId"/>
<result column="username" property="userName"/>
<result column="sex" property="userSex"/>
<result column="address" property="userAddress"/>
<result column="birthday" property="userBirthday"/>
</resultMap>
屬性介紹:
type 屬性:指定實(shí)體類(lèi)的全限定類(lèi)名
id 屬性:給定一個(gè)唯一標(biāo)識(shí)逗噩,是給查詢 select 標(biāo)簽引用用的
column 屬性:用于指定數(shù)據(jù)庫(kù)列名
property 屬性:用于指定實(shí)體類(lèi)屬性名稱
標(biāo)簽介紹:
id標(biāo)簽:用于指定主鍵字段
result 標(biāo)簽:用于指定非主鍵字段
2.引用resultMap:
<select id="findAll" resultMap="userMap">
select * from user
</select>
動(dòng)態(tài)sql
1.<if>標(biāo)簽:
<select id="findByUser" resultType="user" parameterType="user">
select * from user where 1=1
<if test="username!=null and username != '' ">
and username like concat('%',#{username},'%')
</if>
<if test="address != null">
and address like concat('%',#{address},'%')
</if>
</select>
<if>標(biāo)簽的 test 屬性中寫(xiě)的是對(duì)象的屬性名,如果是包裝類(lèi)的對(duì)象要使用 OGNL(寫(xiě)法樣式:user.username,user.address等) 表達(dá)式的寫(xiě)法跌榔。
2.<include>標(biāo)簽:引用創(chuàng)建好的sql語(yǔ)句
創(chuàng)建sql語(yǔ)句:
<sql id="defaultUser">
select * from user
</sql>
引用:
<select id="findByName" resultMap="userMap">
<include refid="defaultUser"></include>
</select>
3.<foreach>標(biāo)簽:
<select id="findInIds" resultType="com.haha.domain.User" parameterType="List">
<!--引用 select * from user 語(yǔ)句-->
<include refid="defaultUser"></include>
<where>
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" open="id in ( " close=")" item="uid" separator="," >
#{uid}
</foreach>
</if>
</where>
</select>
SQL 語(yǔ)句:select 字段 from user where id in (?)
<foreach>標(biāo)簽用于遍歷集合异雁,它的屬性:
collection:代表要遍歷的集合元素,注意編寫(xiě)時(shí)不要寫(xiě)#{}
open:代表語(yǔ)句的開(kāi)始部分
close:代表結(jié)束部分
item:代表遍歷集合的每個(gè)元素僧须,生成的變量名
sperator:代表分隔符
多表查詢
one對(duì)many:
例如一個(gè)用戶有多個(gè)賬戶纲刀,一個(gè)賬戶只能對(duì)應(yīng)一個(gè)用戶,
則user實(shí)體類(lèi)中含有private List<Account> accounts屬性,
account實(shí)體類(lèi)中含有private User user屬性
1.多對(duì)一:查詢賬戶中的信息包含該賬戶的的用戶信息操作
調(diào)用user的findById方法查詢:
<resultMap type="account" id="accountMap">
<id column="aid" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
<!-- 它是用于指定從表方的引用實(shí)體屬性的 -->
<association property="user" column="uid" javaType="user" select="com.haha.dao.UserDao.findById">
<id property="ID" column="aid"></id>
<result property="UID" column="uid"></result>
<result property="MONEY" column="money"></result>
</association>
</resultMap>
<select id="findAll" resultMap="accountMap">
select * from account
</select>
前提是接口UserDao中有findById(uid)這個(gè)方法
select: 填寫(xiě)我們要調(diào)用的 select 映射的 id
column : 填寫(xiě)我們要傳遞給 select 映射的參數(shù)
不調(diào)用方法,使用外聯(lián)查詢:
<resultMap id="accountUserMap" type="com.haha.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="com.haha.domain.User">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
</association>
</resultMap>
<!--引用映射-->
<select id="findAll" resultMap="accountMap">
select u.*,a.id as aid,a.uid,a.money from account a,user u where a.uid =u.id;
</select>
association:用于many對(duì)one時(shí),關(guān)聯(lián)"one"的結(jié)果集
column:用于指定根據(jù)對(duì)象的哪個(gè)屬性來(lái)查找結(jié)果集担平。
javaType:封裝的類(lèi)型
2.一對(duì)多:查詢所有用戶信息及用戶關(guān)聯(lián)的賬戶信息
調(diào)用account的findById方法查詢封裝accounts:
<resultMap id="userAccount" type="com.haha.domain.User">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
<collection property="accounts" column="id" ofType="com.haha.domain.Account" select="com.haha.dao.IAccountDao.findById">
<id property="ID" column="aid"></id>
<result property="UID" column="uid"></result>
<result property="MONEY" column="money"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="userAccount">
select * from user
</select>
ofType 用于指定集合元素的數(shù)據(jù)類(lèi)型
select 是用于指定查詢賬戶的唯一標(biāo)識(shí)(賬戶的 dao 全限定類(lèi)名加上方法名稱)
column 是用于指定使用哪個(gè)字段的值作為條件查詢
不調(diào)用方法:
<!--建立對(duì)應(yīng)關(guān)系-->
<resultMap id="userAccount" type="com.haha.domain.User">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
<collection property="accounts" ofType="com.haha.domain.Account">
<id property="ID" column="aid"></id>
<result property="UID" column="uid"></result>
<result property="MONEY" column="money"></result>
</collection>
</resultMap>
<!--引用映射-->
<select id="findAll" resultMap="userAccount">
select u.*,a.id as aid ,a.uid,a.money from user u left outer join account a on u.id =a.uid
</select>
collection:用于one對(duì)many時(shí),關(guān)聯(lián)"many"的結(jié)果集
結(jié)果集中的屬性:
property:關(guān)聯(lián)查詢的結(jié)果集存儲(chǔ)在對(duì)象中的哪個(gè)屬性上示绊。
ofType:指定關(guān)聯(lián)查詢的結(jié)果集中的對(duì)象類(lèi)型即 List中的對(duì)象類(lèi)型。此處可以使用別名暂论,也可以使用全限定名面褐。
many對(duì)many:
例如一個(gè)用戶對(duì)應(yīng)多個(gè)角色,一個(gè)角色對(duì)應(yīng)多個(gè)用戶,
則user實(shí)體類(lèi)中含有private List<Role> Roles屬性,
role實(shí)體類(lèi)中含有private List<User> Users屬性
查詢角色信息,并且展示角色中的用戶信息:
<resultMap id="roleMap" type="role">
<id property="roleId" column="rid"></id>
<result property="roleName" column="role_name"></result>
<result property="roleDesc" column="role_desc"></result>
<collection property="users" ofType="user">
<id column="id" property="id"></id>
<result column="username" property="username"></result>
<result column="address" property="address"></result>
<result column="sex" property="sex"></result>
<result column="birthday" property="birthday"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="roleMap">
select u.*,r.id as rid,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
</select>
MyBatis的注解開(kāi)發(fā)
常用注解:
@Insert:實(shí)現(xiàn)新增
@Update:實(shí)現(xiàn)更新
@Delete:實(shí)現(xiàn)刪除
@Select:實(shí)現(xiàn)查詢
@Result:實(shí)現(xiàn)結(jié)果集封裝
@Results:可以與@Result 一起使用取胎,封裝多個(gè)結(jié)果集
@ResultMap:實(shí)現(xiàn)引用@Results 定義的封裝
@One:實(shí)現(xiàn)一對(duì)一結(jié)果集封裝
@Many:實(shí)現(xiàn)一對(duì)多結(jié)果集封裝
@SelectProvider: 實(shí)現(xiàn)動(dòng)態(tài) SQL 映射
@CacheNamespace:實(shí)現(xiàn)注解二級(jí)緩存的使用
查詢所有用戶:
@Select("select * from user")
@Results(id="userMap",value= {
@Result(id=true,column="id",property="userId"),
@Result(column="username",property="userName"),
@Result(column="sex",property="userSex"),
@Result(column="address",property="userAddress"),
@Result(column="birthday",property="userBirthday")
})
List<User> findAll();
如果實(shí)體類(lèi)中的屬性名和數(shù)據(jù)庫(kù)中的列名一一對(duì)應(yīng)展哭,可以省略@Results注解
根據(jù)id查詢用戶:
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
保存(添加)用戶:
@Insert("insert into user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address})")
void saveUser(User user);
保存(添加)用戶并返回新增用戶的id值:
@Insert("insert into user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address})")
@SelectKey(keyColumn="id",keyProperty="id",resultType=Integer.class,before =false, statement = { "select last_insert_id()" })
int saveUser(User user);
更改用戶數(shù)據(jù):
@Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id} ")
void updateUser(User user);
根據(jù)用戶id刪除用戶:
@Delete("delete from user where id = #{uid} ")
void deleteUser(Integer userId);
使用聚合函數(shù):
@Select("select count(*) from user ")
void findTotal();
模糊查詢:
@Select("select * from user where username like concat('%',#{username},'%') ")
List<User> findByName(String name);
使用注解實(shí)現(xiàn)復(fù)雜關(guān)系映射開(kāi)發(fā)
在使用注解開(kāi)發(fā)時(shí)我們需要借助 @Results 注解, @Result 注解闻蛀, @One 注解匪傍, @Many 注解。
@Resutl 注解代替了 <id>標(biāo)簽和<result>標(biāo)簽
屬性介紹:
id 是否是主鍵字段
column 數(shù)據(jù)庫(kù)的列名
property 需要裝配的屬性名
one 需要使用的@One 注解(@Result(one=@One)()))
many 需要使用的@Many 注解(@Result(many=@many)()))
@One 注解(一對(duì)一)
代替了<assocation>標(biāo)簽觉痛,是多表查詢的關(guān)鍵析恢,在注解中用來(lái)指定子查詢返回單一對(duì)象。
使用格式:
@Result(column=" ",property="",one=@One(select=""))
select 指定用來(lái)多表查詢的 sqlmapper
fetchType 會(huì)覆蓋全局的配置參數(shù) lazyLoadingEnabled秧饮。映挂。
@Many 注解(多對(duì)一)
代替了<Collection>標(biāo)簽,是是多表查詢的關(guān)鍵,在注解中用來(lái)指定子查詢返回對(duì)象集合盗尸。
注意:聚集元素用來(lái)處理“一對(duì)多”的關(guān)系柑船。需要指定映射的 Java 實(shí)體類(lèi)的屬性,
屬性的 javaType(一般為 ArrayList)但是注解中可以不定義泼各;
使用格式:
@Result(property="",column="",many=@Many(select=""))
查詢所有賬戶信息包括賬戶中的user信息并使用延遲加載:
@Select("select * from account")
@Results({
@Result(id=true,column="id",property="id"),
@Result(column="uid",property="uid"),
@Result(column="money",property="money"),
@Result(column="uid",property="user",one=@One(select="com.haha.dao.IUserDao.findById",fetchType=FetchType.LAZY))
})
List<Account> findAll();
如果將來(lái)要對(duì)@Results進(jìn)行引用應(yīng)用鞍时,@Results中的需要添加id和value標(biāo)簽:
@Select("select * from account")
@Results(id="accountMap",
value= {
@Result(id=true,column="id",property="id"),
@Result(column="uid",property="uid"),
@Result(column="money",property="money"),
@Result(column="uid",property="user",one=@One(select="com.haha.dao.IUserDao.findById",fetchType=FetchType.LAZY))
})
List<Account> findAll();
@Select("select * from account where aid = #{aid} ")
@ResultMap("accountMap")
Account findById(Integer accountId);
查詢所有用戶信息包括用戶中的賬戶信息并使用延遲加載:
@Select("select * from user")
@Results({
@Result(id=true,column="id",property="userId"),
@Result(column="username",property="userName"),
@Result(column="sex",property="userSex"),
@Result(column="address",property="userAddress"),
@Result(column="birthday",property="userBirthday"),
@Result(column="id",property="accounts",many=@Many(select="com.haha.dao.IAccountDao.findByUid",fetchType=FetchType.LAZY))
})
List<User> findAll();
MyBatis的緩存:
一級(jí)緩存
一級(jí)緩存是 SqlSession 級(jí)別的緩存,只要 SqlSession 沒(méi)有 flush 或 close,它就存在逆巍。當(dāng)調(diào)用 SqlSession 的修改及塘,添加,刪除锐极, commit()笙僚,
close()等方法時(shí),就會(huì)清空一級(jí)緩存灵再。
二級(jí)緩存
二級(jí)緩存是 mapper 映射級(jí)別的緩存肋层,多個(gè) SqlSession 去操作同一個(gè) Mapper 映射的 sql 語(yǔ)句,
多個(gè)SqlSession 可以共用二級(jí)緩存翎迁,二級(jí)緩存是跨 SqlSession 的栋猖。
在 SqlMapConfig 中開(kāi)啟二級(jí)緩存支持:
<settings>
<!-- 開(kāi)啟二級(jí)緩存的支持 -->
<setting name="cacheEnabled" value="true"/>
</settings>
使用二級(jí)緩存
@CacheNamespace(blocking=true)//mybatis 基于注解方式實(shí)現(xiàn)配置二級(jí)緩存
public interface IUserDao {}
因?yàn)?cacheEnabled 的取值默認(rèn)就為 true,所以這一步可以省略不配置汪榔。為 true 代表開(kāi)啟二級(jí)緩存蒲拉;為
false 代表不開(kāi)啟二級(jí)緩存。
當(dāng)我們?cè)谑褂枚?jí)緩存時(shí)痴腌,所緩存的類(lèi)一定要實(shí)現(xiàn) java.io.Serializable 接口雌团,這種就可以使用序列化
方式來(lái)保存對(duì)象。