1. 程式人生 > >Mybatis 和Spring整合之mapper代理開發

Mybatis 和Spring整合之mapper代理開發

dtd des mes factor ssi fig 隔離 代理 location

F:\1ziliao\mybatis\代碼

技術分享圖片

1.1 SqlMapConfig.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>

<!-- 通過setting配置mybatis的運行參數
註意,設置運行參數會影響 mybatis的運行,一定要註意!
-->
<settings>
<!-- 延遲加載的總開關 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 設置為false實現按需求加載 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 開啟二級緩存 -->
<setting name="cacheEnabled" value="true"/>
</settings>

<!-- 定義別名 -->

<typeAliases>
<!-- 單個別名定義
type:類路徑
alias:別名
-->
<!-- <typeAlias type="cn.itcast.mybatis.po.User" alias="user"/> -->
<!-- 批量配置
指定pojo所在包路徑,自動掃描包下的pojo定義別名,別名為類名(首字母小寫或大寫都可以)
-->
<package name="cn.itcast.mybatis.po"/>
<!-- 如果掃描多個包中的pojo,就寫多個 package-->
<!-- <package name=""/> -->
</typeAliases>

</configuration>

1.2 spring容器中配置sqlSessionFactory applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop
="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 配置數據源dataSource --> <!-- 加載配置文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 數據庫連接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxActive" value="10"/> <property name="maxIdle" value="5"/> </bean> <!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 配置數據源 --> <property name="dataSource" ref="dataSource"/> <!-- 加載mybatis的配置文件 --> <property name="configLocation" value="classpath:SqlMapConfig.xml"/> </bean> <!-- 原始dao --> <!-- <bean id="userDao" class="cn.itcast.mybatis.dao.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> --> <!-- mapper代理配置 --> <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 指定mapper接口 <property name="mapperInterface" value="cn.itcast.mybatis.mapper.UserMapper"/> 註入SqlSessionFactory <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> --> <!-- 使用mapper掃描器創建mapper代理對象 掃描器把自動將包下邊的mapper掃描出來創建代理對象在spring容器註冊,bean的id為類名(首字母小寫) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定要掃描的包路徑,如果要掃描多個包,中間使用半角逗號分隔 註意:如果使用掃描器,不需要在sqlMapConfig.xml中加載mapper,要將mapper.xml和mapper.java放在同一個目錄且同名 --> <property name="basePackage" value="cn.itcast.mybatis.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> </beans>

1.3 接口mapper.java和mapper.xml

public interface UserMapper {
    
    //根據用戶id查詢用戶信息
    public User findUserById(int id)throws Exception;
    
    //查詢用戶使用resultMap
    public User findUserByIdResultMap(int id)throws Exception;
    
    //根據用戶名稱模糊查詢
    public List<User> findUserByName(String username)throws Exception;
    
    //插入用戶
    public void insertUser(User user)throws Exception;
    
    //更新用戶
    public void updateUser(User user)throws Exception;


}
<?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">

<!-- 
一個mapper映射文件是以sql語句為單位進行配置,最終將sql語句封裝到MappedStatement對象中
namespace命名空間作用是更好對sql語句進行隔離,方便管理sql

註意:後期講mybatis的mapper代理開發方式時namespace有特殊的作用,如下:
namespace等於mapper接口類路徑,這樣實現通過映射文件找到對應的mapper接口是哪個

 -->
<mapper namespace="cn.itcast.mybatis.mapper.UserMapper">

<!-- 打開二級緩存 -->
<!-- <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> -->

<!-- 根據用戶id查詢一個用戶信息 
select:用於查詢,主要配置sql語句、輸入參數類型、輸出結果類型
最終該 select 標簽 中所配置的內容會封裝到MappedStatement對象,可以將該 select稱為是一個Statement
id:唯 一標識 namespace下的一個sql語句,將id稱為Statement的id

parameterType:指定輸入參數的類型(簡單類型、自定義pojo)
#{}:表示一個占位符號,占位符號可以防止sql註入
#{value}:value表示接收輸入參數的值,如果接收的輸入參數是簡單類型,#{}裏邊可以寫value或其它的名稱
resultType:將sql查詢結果集映射成java對象
將多個列的值映射到一個對象中,需要定義的pojo,resultType映射規則是sql查詢列名和pojo的屬性名必須一致方可完成映射
resultType 指定單條記錄所映射的java對象

-->
<select id="findUserById" parameterType="int" resultType="user">
    SELECT id,username,birthday,sex,address  FROM USER WHERE id = #{id}
</select>

<!-- 使用resultMap將列名和pojo的屬性值作一個對應關系,完成映射
id:唯一標識 一個元素
type:最終映射的pojo類型
-->
<resultMap type="user" id="queryUserResultMap">
    <!-- id標識 查詢結果集中唯一標識列
    column:結果集中唯 一標識 的列名
    property:將唯一標識 的列所映射到的type指定的pojo的屬性名
     -->
    <id column="id_" property="id"/>
    <!-- 如果結果集有多個列組合成一個唯 一標識,定義兩個id標簽 -->
    <!-- result表示:普通列 -->
    <result column="username_" property="username"/>
    <result column="birthday_" property="birthday"/>
    <result column="sex_" property="sex"/>
    <result column="address_" property="address"/>
</resultMap>


<!-- 查詢用戶,使用resultMap完成結果映射 -->
<select id="findUserByIdResultMap" parameterType="int" resultMap="queryUserResultMap">
    SELECT id id_,username username_,birthday birthday_,sex sex_,address address_  FROM USER WHERE id = #{id}
</select>

<!-- 
根據用戶名稱模糊查詢用戶信息列表
resultType:不管結果集記錄的數量有多少,resutType指定單條記錄所映射的java對象
resultType映射規則是sql查詢列名和pojo的屬性名必須一致方可完成映射
${}:表示一個sql拼接符號,相當於字符串的拼接:
“SELECT * FROM USER WHERE username LIKE ‘%” + ${}表示的串 + “%‘”
${}:如果接收輸入參數是一個簡單類型,${} 中只能寫value

${}實現sql拼接是無法防止sql註入的。

 -->
 <select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User">
     SELECT * FROM USER WHERE username LIKE ‘%${value}%‘
 </select>

<!-- 添加用戶 
需要輸入參數是多個值,如果傳入簡單類型是無法滿足要求。
輸入參數類型可以定義為pojo(cn.itcast.mybatis.po.User包括多個屬性)
#{}如何獲取對象的值?
#{}是通過OGNL讀取對象的值,OGNL的表達式方式:屬性.屬性.屬性。。。。直到把對象中的屬性值讀取過來 過止
mysql數據庫通過select LAST_INSERT_ID();獲取自增主鍵的值,在insert語句執行之後去執行LAST_INSERT_ID()獲取新記錄的主鍵
-->
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
    <!-- 
    keyProperty:將主鍵值設置到輸入參數的哪個屬性,設置到user的id屬性中
    order:selectkey中的sql語句在insert語句執行的前或後,這裏要設置成"AFTER"
    resultType:select LAST_INSERT_ID()查詢出的值
     -->
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
        select LAST_INSERT_ID()
    </selectKey>
    insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address});
</insert>

<!-- 使用mysql的uuid生成主鍵 -->
<!-- <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
    
    keyProperty:將主鍵值設置到輸入參數的哪個屬性,設置到user的id屬性中
    order:select uuid()在insert執行之前去執行得到uuid作為主鍵,將主鍵值設置到user的屬性中
    resultType:select uuid()查詢出的值
    
    <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
        select uuid()
    </selectKey>
    insert into user(id,username,birthday,sex,address) values(#{id},#{username},#{birthday},#{sex},#{address});
</insert> -->

<!-- 修改用戶-->
<update id="updateUser" parameterType="cn.itcast.mybatis.po.User">
 update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
</update>

<!-- 刪除用戶 -->
<delete id="deleteUser" parameterType="int">
    delete from user where id = #{id}
</delete>

</mapper>

1.4 springmybatis整合生成代理對象方法2 掃描器

技術分享圖片

Mybatis 和Spring整合之mapper代理開發