mybatis 使用說明

MyBatis是一個用來操作數據的ORM持久層框架。

一.mybatis環境搭建。

1、導入mybatis核心jar包

2、書寫核心配置文件(mybatis-config.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
    <configuration>
<!-- 設置參數 -->
<settings><setting name="logImpl" value="LOG4J"/></settings>
<!-- 設置別名 -->
<typeAliases><package name="cn.com.pojo"/></typeAliases>
<!-- 環境變量 -->
<!-- 
    dev 開發模式
    work 生產模式
-->
<environments default="dev">
    <environment id="dev">
        <!-- 事務管理 JDBC 使用簡單JDBC 完成事務的提交和回滾-->
        <transactionManager type="JDBC"></transactionManager>
        <!-- 配置數據源 POOLED表示開啓連接池、mybatis自帶的dbcp連接池 -->
        <dataSource type="POOLED">
    <property name="driver" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/books"/>
    <property name="username" value="root"/>
    <property name="password" value="123"/>
        </dataSource>
    </environment>
</environments>

    </configuration>

3、 在覈心配置文件中配置數據庫的鏈接信息(數據庫驅動、url、username、password等)、上邊已經配置、不在說明。

注意:也可以在src下寫properties文件,裏邊配置數據庫連接信息、然後再mybatis-donfig.xml核心配置文件中引用。

* I. db.properties文件內容如下:

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/books
username=root

password=root

* II.在mybatis-donfig.xml引用:

<properties resource="db.properties"/>
    <dataSource type="POOLED">
<property name="driver" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>

    </dataSource>

4、創建實體對象、編寫mapper映射文件、文件名稱與Pojo類的名稱一致、用來保存你將要寫的sql語句。

* mapper映射文件如下(實現mybatis的CRUD):

    * 在mapper映射文件中可以使用select insert delete update 標籤做CRUD操作
    * 每個標籤必須有唯一的id來標識。
    * parameterType 代表操作時傳入的參數類型 
1. 基本數據類型,int string, double  delete
2. 實體對象類型 常用於insert
3. map數據類型 常用複雜查詢 map的key就是相當於pojo的屬性
    * resultMap 是做返回結構映射的。type是說明要映射哪個類型、id標識、爲後面的返回結果引用。

    <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- namespace 是區分 我們不同操作的包名 -->
<mapper namespace="cn.com.pojo.Usertbl">
    <!-- parameterType 代表操作時傳入的參數類型 -->
    <!-- # {uName} 是查找的參數user.uName 屬性的值 -->

    <insert id="save" parameterType="Usertbl">
INSERT INTO usertbl(uName,uSex,uAge) VALUES(#{uName},#{uSex},#{uAge});
    </insert>

    <update id="update" parameterType="cn.com.pojo.Usertbl">
UPDATE usertbl set uName=#{uName},uSex=#{uSex} where uId=#{uId};
    </update>

    <delete id="delete" parameterType="int">
delete from usertbl where uId=#{uId};
    </delete>

    <select id="findbyid" parameterType="int" resultType="cn.com.pojo.Usertbl">
select * from usertbl where uId=#{uId};
    </select>

    <select id="findall" resultType="cn.com.pojo.Usertbl">
select * from usertbl;
    </select>
    </mapper>

5、在覈心配置文件中配置mapper映射文件

* I.單個文件隱射

<mappers>
    <mapper resource="cn/com/mapper/UsertblMapper.xml"/>

</mappers>

* II.映射文件非常多的時候、可以採用目錄映射(目錄映射,如果要起效,那麼mapper接口類文件要射映射文件放到同一目錄下)

<mappers>
    <package name="cn.com.pojo"/>

</mappers>

6、編寫測試類。

public class Test(){
    public static void main(String[] args) throw  IOException {
//1、加載mybatis核心配置文件(同時加載關聯的mapper映射文件)
InputStream  is = Resources.getResourceAsStream("mybatis-Config.xml");
//2、構建sqlSessionFactory 工廠
SessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
//創建能夠執行映射文件中sql語句的sqlSession
SqlSession session = sessionFactory.openSession();
//執行sql語句並返回一個user對象
User user = session.selectOne("cn.com.pojo.Usertbl.findbyid",1);
System.out.println(user);
    }

}

二,解決數據庫表中字段名與實體類中屬性名不相同的衝突。

* I.通過在sql語句中定義別名
<select id="getOrder" parameterType="int" resultType="Order">
    select order_id id,order_no orderno,order_price price from ordertbl where order_id=#{id}

</select>

* II.通過設置resultMap

三 ,接口註解方式

說明:接口註解方式適合相對比較簡單的sql,如果較複雜的sql,還需要寫配置文件,更方便清晰。

public interface UserMapper{
    @Insert("insert into users(name,age) values(#{name},#{age})")
    public int add(User user);

    @Delete("delete from users where id = #{id}")
    public int DeleteById(int uid);

    @Update("update users set name=#{name},age=#{age} where id=#{id}")
    public int update(User user);

    @Select("select * from users")
    public List<User> findAll();

四,mybatis關聯查詢-映射文件。

1、多對一關聯查詢

<resultMap type="Emptbl" id="empResultMap">
    <id column="empid" property="empid"/>
    <result column="empname" property="empname"/>
    <result column="empage" property="empage"/>
    <!-- 
表達多對一關聯 
property : 對象屬性的名稱
javaType : 對象屬性的類型
    -->
    <association property="dept" javaType="Depttbl">
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
    </association>

</resultMap>

<select id="findall" resultMap="empResultMap">
    <![CDATA[
SELECT e.*,d.dept_name from emptbl e,depttbl d
WHERE e.did = d.dept_id
    ]]>

</select>

2、一對多關聯查詢

<resultMap type="Studenttbl" id="stuResultMap">
    <id column="sid" property="sid"/>
    <result column="sname" property="sname"/>
    <!-- 
一對多關聯
javaType : 返回的容器
ofType : 容器中的數據類型(實體類型)
    -->
    <collection property="courseTbls" javaType="List" ofType="Coursetbl"> 
<id column="cid" property="cid"/>
<result column="cname" property="cname"/>
    </collection>
</resultMap>

<!-- 一對多關聯查詢 -->
<select id="findStudentWithCoursesbyid" resultMap="stuResultMap" parameterType="int">
    <![CDATA[
SELECT st.*,ct.* from 
studenttbl st,coursetbl ct,stucoutbl sc
WHERE 
st.sid=sc.sid and ct.cid=sc.cid and st.sid=#{id};
    ]]>

</select>

五,mybatis 動態sql(增刪查改)

<!-- 動態sql查詢  map.put('sid',2); map.put('sname','徐磊')-->
<select id="findbyCondition" parameterType="map" resultMap="stuResultMap">
select * from studenttbl s where 1=1 
    <if test="sid != null and sid != ''">
        and s.sid>#{sid} 
    </if>
    <if test="sname != null and sname != ''">
        and s.sname=#{sname} 
    </if>

</select>

<!-- 動態sql查詢  map.put('sid',2); map.put('sname','徐磊')-->
<select id="findbyWhere" parameterType="map" resultMap="stuResultMap">
    select * from studenttbl s 
    <where>
<if test="sid != null and sid != ''">
    and s.sid>#{sid}
</if>
<if test="sname != null and sname != ''">
    and s.sname=#{sname}
</if>
    </where>

</select>

<!-- shose語句 -->

<select id="findbyChoose" parameterType="Emptbl" resultMap="empResultMap">

    <!-- choose的動態sql 
多選一 類似於 switch case使用
    -->
    select * from emptbl where 1=1 
    <choose>
<when test="empid!=null and empid>0">
    and empid=#{empid} 
</when>
<when test="empname!=null"><!-- empname是表列名, #{empname}是對象的屬性-->
    and empname=#{empname}
</when>
<otherwise></otherwise>
    </choose>  

</select>

<!-- 動態更新,set子句 -->
<update id="updatebyset" parameterType="Emptbl">
    update emptbl 
    <set>
<if test="empname!=null">empname=#{empname},</if>
<if test="empage>0">empage=#{empage},</if>
<!-- 關聯使用,先判斷關聯對象本身非空,在判斷關聯對象的屬性非空或(針對原始類型)>0 --> 
<if test="dept!=null and dept.deptId>0">did=#{dept.deptId}</if> 
    </set> 
    where empid=#{empid}

 </update>

<!-- foreach 動態sql -->
<select id="findbyin" parameterType="List" resultMap="empResultMap">
    select * from emptbl where empid in
    <!--類似於jstl中循環標籤 <c:foreach items="${lists}" var="it"> -->
    <foreach collection="list" item="it" open="(" close=")" separator=",">
#{it}
    </foreach>

</select>

<!-- 模糊查詢 -->
<select id="findbylike" parameterType="Emptbl" resultMap="empResultMap">
    select * from emptbl where empname LIKE '%${empname}%'

</select>

<!-- bind模糊查詢  emp.setEmpname(‘zhangs’) emp.getEmpname() ==zhangs -->
<select id="findbybind" parameterType="string" resultMap="empResultMap">
<!-- _parameter是固定的 表示傳入的參數對象 _parameter.getEmpname()表示調用傳入對象的方法getEmpname() -->
    <bind name="pattern" value="'%'+_parameter+'%'"/>
    select * from emptbl where empname LIKE #{pattern}

</select>


發佈了75 篇原創文章 · 獲贊 8 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章