實體起別名
1.給實體類的權限定名取別名 (mybatis-config配置文件) com.lhl.demo1.Person 別名="Person" <typeAliase> <typeAlias type="實體的全類名" alia="別名"></typeAlias> </typeAliase> 2.Mapper使用實體類名 resultType="Person"
MyBatis參數綁定的底層原理
1.默認mapper文件綁定 #{xxx}
底層使用的PreparedStatement對象
使用的是SQL的?站位綁定,預編譯
優點:
預編譯,防止sql注入、相對效率高一點
缺點:
只能綁定數據值 sql關鍵字、列、非數據無法綁定
2.使用sql字符串拼接綁定參數 ${xxx}
優點:可以綁定任何內容
缺點:sql注入
將對象插入數據庫后,綁定id
目的: 將insert插入的user對象,id賦值添加的id 思路: 1.發送select 序列 from dual的sql 2.通過結果集獲得id 3.將id綁定在參數的urer對象的id屬性中 MyBatis插入數據綁定id <insert id="insert" parameterType="實體類型"> <!--在insert語句之前,執行select序列的sql,為了給參數的id屬性綁定值--> <selectKey order="BEFORE" resultType="java.lang.String" keyProperty="sql的執行結果綁定給參數的實體的那個屬性 id"> select seq_user.nextval from dual
</selectKey> insert into t_user values(?,?,?) </insert>
查詢關系映射
一、resultType 二、使用resultMap定義映射關系 <!-- 1.列 屬性 2.最終封裝的對象類型 --> <resultMap id="PersonMap" type="實體對象"> <!--id:主屬性--> <id property="屬性" column="列"></id> <!--其他列屬性--> <result property="屬性" column="列"/> <result property="name" column="name"*> </resultMap> <!--查詢功能--> <select id="selectById" parameterType="java.lang.Integer" resultMap="PersonMap"> </select>