mybatis概念
概念:一個持久層框架
作用:ORM將sql語句映射成實體類
-
特點:
- 巧靈活
- 半自動化
- 使用與中小型項目的開發(fā)
mybatis入門
1、創(chuàng)建mybatis-config.xml文件
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/bank?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
2、創(chuàng)建映射文件UserMapper.xml
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="user"> <!--命名空間SqlSession調用時用-->
<select id="selectUser" resultType="com.hemi.mybatis.bean.User"> <!--id名稱標示一條sql語句 resultType 返回bean對象類型-->
select * from user where uid=1;
</select>
</mapper>
3、建立mybatis-config.xml與 UserMapper.xml連接 在mybatis-config.xml標簽configuration里加
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
4僵刮、獲取xml配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
5、創(chuàng)建SqlSessionFactory
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
6惨险、獲取SqlSession
SqlSession sqlSession = factory.openSession();
7、調用SqlSession的selectOne(命名空間.id名稱);
Object object = sqlSession.selectOne("user.selectUser");
8宰衙、關閉SqlSeesion
sqlSession.close();
增刪改
增
![Uploading 2_535075.png . . .]
<insert id="insertUser" parameterType="com.hemi.mybatis.bean.User">
<!-- 通過#{屬性名}來獲取對象的值 -->
insert into user (username,password) values(#{username},#{password});
</insert>
改
<update id="updateUser" parameterType="com.hemi.mybatis.bean.User">
update user set username=#{username},password=#{password} where uid=#{uid};
</update>
刪
![Uploading 3_546596.png . . .]
<delete id="deleteUser" parameterType="int">
delete from user where uid=#{value};
</delete>
Mapper接口開發(fā)
一平道、定義一個接口
public interface TypeMapper {
Type selectType(int typeid);
}
二、定義一個mapper.xml映射文件
mapper文件的要求:
- namespace的值就是對象接口的全類名供炼,并且類名和xml文件名保持一致
- id的值就是抽象方法
- resultType的值必須和抽象方法的返回值一致
- parameterType的值和抽象方法的參數(shù)類型一致
注意 mapper.xml文件的約束是mapper.dtd,不是config.dtd
三窘疮、使用
將mybatis入門步驟中的步驟六改為如下代碼:
TypeMapper mapper=sqlSession.getMapper(TypeMapper.class);
Type type=mapper.selectType(1);
動態(tài)sql
if
SELECT * FROM good INNER JOIN type ON good.type = type.typeid where 1=1
<if test="gname !=null and gname !=''">
and gname like concat('%',#{gname},'%');
</if>
注意:
1袋哼、字符串的拼接建議使用concat來代替$
{}
2、判斷條件中獲取數(shù)據(jù)不用加#{}闸衫,與el表達式不一樣
where
作用where可以自動去除第一個and
<where>
<if test="gname !=null and gname !=''">
and gname like concat('%',#{gname},'%')
</if>
<if test="typename !=null and typename!=''">
and typename like concat('%',#{typename},'%')
</if>
</where>
;
choose when otherwise
作用:組合使用涛贯,相當于if else if else
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = 'ACTIVE'
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
;
set
update good
<set>
<if test="gname!=null and gname!=''">
gname=#{gname},
</if>
<if test="gprice!=null and gprice!=''">
gprice=#{gprice}
</if>
</set>
where gid=#{gid};
trim
作用:去除多余字符串
兩種常見的用法
1、where and
prefix:字首 prefixOverrides:去除第一個指定的字符串
select * from good
<trim prefix="where" prefixOverrides="and|or">
<!--添加where在前面蔚出,并且去除第一個and-->
<if test="gname !=null and gname !=''">
and gname like concat('%',#{gname},'%')
</if>
<if test="typename !=null and typename!=''">
and typename like concat('%',#{typename},'%')
</if>
</trim>
;
2弟翘、set
prefix:字首 suffixOverrides:去除最后指定的字符串
update good
<trim prefix="set" suffixOverrides=",">
<!--添加set在前面虫腋,并且去除最后一個,-->
<if test="gname!=null and gname!=''">
gname=#{gname},
</if>
<if test="gprice!=null and gprice!=''">
gprice=#{gprice},
</if>
</trim>
;
foreach
作用:動態(tài)循環(huán)拼接sql部分內容
1、open代表在集合前面添加的字符串
2稀余、close代表在集合后面添加的字符串
3悦冀、separator代表集合分割使用的字符串
4、collection代表被循環(huán)的集合睛琳,值可以是list盒蟆、map、array
5师骗、常見用法历等,in的語句
<select id="selectGoodByGid" parameterType="list" resultType="Good">
select gid,gname,gprice,count,type typeid from good
<where>
gid in
<foreach item="item" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</where>
</select>
;
resultMap
作用:
1、可以將表字段與javabean對象屬性名進行映射 2辟癌、將映射抽取出來寒屯,可以給多個statement所使用
<!-- type:最終返回的數(shù)據(jù)類型 id:resultMap的名稱 -->
<resultMap type="Good" id="GoodResultMap">
<!-- 建議將主鍵設置為id -->
<id column="good_id" property="gid"/>
<!-- 通過result將數(shù)據(jù)庫字段與java對象的屬性進行一一映射 -->
<result column="good_name" property="gname"/>
<result column="good_price" property="gprice"/>
<!--
下面的映射可以不用寫,因為mybatis中默認設置autoMappingBehavior為PARTIAL黍少,局部自動映射浩螺,但是屬性名必須和字段名一致
-->
<!-- <result column="count" property="count"/> -->
</resultMap>
;
映射的原理
1、先拿到type指定的類的class
2仍侥、通過newInstance創(chuàng)建對象
3要出、獲取property中屬性名,通過反射的方式調用對應的set()方法
4农渊、調用方法的invoke()方法患蹂,將column的值賦值進去
5、返回封裝好的對象
關聯(lián)嵌套結果(resultMap與resultMap相互嵌套)
<resultMap type="Good" id="GoodResultMap">
<id column="good_id" property="gid"/>
<result column="good_name" property="gname"/>
<result column="good_price" property="gprice"/>
<!-- 一對一的映射關系砸紊,選擇association -->
<!-- 內部嵌套 -->
<association property="type" javaType="Type">
<id column="typeid" property="typeid"/>
<result column="typename" property="typename"/>
</association>
</resultMap>
;
上面的association部分可以改造為<association property="type" javaType="Type" resultMap="TypeResultMap">传于,然后使用外部嵌套
<!-- resultMap外部嵌套 -->
<resultMap type="Type" id="TypeResultMap">
<!-- 建議將主鍵設置為id -->
<id column="typeid" property="typeid"/>
<result column="typename" property="typename"/>
</resultMap>
;
關聯(lián)嵌套查詢
<resultMap type="Good" id="GoodResultMap1">
<id column="good_id" property="gid"/>
<result column="good_name" property="gname"/>
<result column="good_price" property="gprice"/>
<!--column:要傳遞給下面的statement的參數(shù)-->
<!--javaType:該association返回的數(shù)據(jù)類型-->
<!--select:另一個查詢語句的statementId-->
<association property="type" javaType="Type" select="selectTypeByTypeId" column="type"/>
</resultMap>
<select id="selectTypeByTypeId" resultType="Type">
select * from type where typeid=#{value}
</select>
;
集合嵌套結果
<colleciton property="javabean中的屬性名" javaType="List" ofType="list集合中的元素類型">
<id column="主鍵字段名" property="元素類型的屬性名"/>
<result column="字段名" property="元素類型的屬性名"/>
</colleciton>
;
集合嵌套查詢
<colleciton property="javabean中的屬性名" javaType="List" ofType="list集合中的元素類型" select="selectUser" column="uid"/>
<select id="selectUser" resultMap="User">
select * from user where uid=#{value}
</select>
;
在主配置文件中配置
<settings>
<!-- 雖然默認是 PARTIAL,但是建議寫上-->
<setting name="autoMappingBehavior" value="PARTIAL"/>
</settings>
;
緩存
一級緩存(同一個SqlSession中執(zhí)行同一個statement)
默認開啟
二級緩存(同一個namespace中醉顽,不同SqlSession執(zhí)行同一個statement)
配置 1沼溜、setting中設置cacheEnabled="true" 2、mapper中添加<cache> 3游添、statement中添加useCache="true" 4系草、調用session.close()時候才將數(shù)據(jù)寫入二級緩存 5、用到的實體類要實現(xiàn)Serializable接口