在使用mybatis框架時,大多時候自動生成的mapper.xml文件能滿足我們所需的數據庫操作,但一些情況下還是需要我們自己寫sql;為了加深印象,總結了下參數傳遞的方式以及各個關鍵字的含義如下:
語句中接收參數的方式有兩種:
1、 #{}預編譯 (可防止sql注入)
2、${}非預編譯(直接的sql拼接,不能防止sql注入)
參數類型有三種:
1、 基本數據類型
2、 HashMap(使用方式和pojo類似 )
3、 Pojo自定義包裝類型
基本數據類型使用方式
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中不指定接收參數類型,直接對應即可:
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類型
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>
返回類型與接收類型關鍵字的區別:
resultType 和 resultType的區別
兩者都是表示查詢結果集與java對象之間的一種關系,處理查詢結果集,映射到java對象。
resultMap表示將查詢結果集中的列一一映射到bean對象的各個屬性,映射的查詢結果集中的列標簽可以根據需要靈活變化。
resultType 表示的是bean中的對象類,此時可以省略掉resultMap標簽的映射,但是必須保證查詢結果集中的屬性 和 bean對象類中的屬性是一一對應的,此時大小寫不敏感,但是有限制。
parameterMap(不推薦) & parameterType
parameterMap和resultMap類似,表示將查詢結果集中列值的類型一一映射到java對象屬性的類型上,在開發過程中不推薦這種方式。
一般使用parameterType直接將查詢結果列值類型自動對應到java對象屬性類型上,不再配置映射關系一一對應,例如上述代碼中下划線部分表示將查詢結果類型自動對應到Bean對象的屬性類型