在使用mybatis框架時,大多時候自動生成的mapper.xml文件能知足咱們所需的數據庫操做,但一些狀況下仍是須要咱們本身寫sql;爲了加深印象,總結了下參數傳遞的方式以及各個關鍵字的含義以下:java
語句中接收參數的方式有兩種:
一、 #{}預編譯 (可防止sql注入)
二、${}非預編譯(直接的sql拼接,不能防止sql注入)sql
參數類型有三種:
一、 基本數據類型
二、 HashMap(使用方式和pojo相似 )
三、 Pojo自定義包裝類型數據庫
基本數據類型使用方式api
List<Bean> selectIdBySortTime(@Param(value="id")Long id); <sql id="Base_Column_List" > id, car_dept_name, car_maker_name, icon,car_maker_py,hot_type </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" > select <include refid="Base_Column_List" /> from common_car_make where id = #{id,jdbcType=BIGINT} (jdbcType可省略) </select>
基本類型多參傳遞時候的方式,sql中不指定接收參數類型,直接對應便可:mybatis
User login(@Param(value="name")String name,@Param(value="password")String password ); <select id="login" resultType="com.pojo.User"> select * from us where name=#{name} and password=#{password} </select>
複雜類型–map類型app
Service層 Map<String, Object> paramMap=new hashMap(); paramMap.put(「id」, value); paramMap.put(「carDeptName」,value); paramMap.put(「carMakerName」,value); paramMap.put(「hotType」,value); Dao層 (若是不使用@Param註解,則sql中也能夠省略屬性前綴cm.) List<Bean> queryCarMakerList(@Param(value="cm")Map paramMap); <select id="queryCarMakerList" resultMap="BaseResultMap" parameterType="java.util.Map"> select <include refid="Base_Column_List" /> from common_car_make cm where 1=1 <if test="id != null"> and id = #{cm.id,jdbcType=DECIMAL} </if> <if test="carDeptName != null"> and car_dept_name = #{cm.carDeptName,jdbcType=VARCHAR} </if> <if test="carMakerName != null"> and car_maker_name = #{cm.carMakerName,jdbcType=VARCHAR} </if> <if test="hotType != null" > and hot_type = #{cm.hotType,jdbcType=BIGINT} </if> ORDER BY id </select>
複雜類型–類類型
與Map傳參的使用方式基本相同,不一樣的地方在於不一樣本身再填充map數據,直接使用已定義的bean類便可。框架
<update id="updateByPrimaryKeySelective" parameterType="com.epeit.api.model.CommonCarMake" > update common_car_make <set > <if test="carDeptName != null" > car_dept_name = #{carDeptName,jdbcType=VARCHAR}, </if> <if test="carMakerName != null" > car_maker_name = #{carMakerName,jdbcType=VARCHAR}, </if> <if test="icon != null" > icon = #{icon,jdbcType=VARCHAR}, </if> <if test="carMakerPy != null" > car_maker_py = #{carMakerPy,jdbcType=VARCHAR}, </if> <if test="hotType != null" > hot_type = #{hotType,jdbcType=BIGINT}, </if> </set> where id = #{id,jdbcType=BIGINT} </update>
返回類型與接收類型關鍵字的區別:xml
resultType 和 resultType的區別對象
二者都是表示查詢結果集與java對象之間的一種關係,處理查詢結果集,映射到java對象。blog
resultMap表示將查詢結果集中的列一一映射到bean對象的各個屬性,映射的查詢結果集中的列標籤能夠根據須要靈活變化。
resultType 表示的是bean中的對象類,此時能夠省略掉resultMap標籤的映射,可是必須保證查詢結果集中的屬性 和 bean對象類中的屬性是一一對應的,此時大小寫不敏感,可是有限制。
parameterMap(不推薦) & parameterTypeparameterMap和resultMap相似,表示將查詢結果集中列值的類型一一映射到java對象屬性的類型上,在開發過程當中不推薦這種方式。通常使用parameterType直接將查詢結果列值類型自動對應到java對象屬性類型上,再也不配置映射關係一一對應,例如上述代碼中下劃線部分表示將查詢結果類型自動對應到Bean對象的屬性類型