1.Mapper接口方法名和mapper.xml中定義的每個sql的id相同;
2.Mapper接口方法的輸入參數類型和mapper.xml中定義的每個sql的parameterType的類型相同;
3.Mapper接口方法的輸出參數類型和mapper.xml中定義的每個sql的resultType的類型相同;
4.Mapper.xml文件中的namespace即是mapper接口的類路徑;
第一種:通過定義select語句中字段名的別名,讓字段明的別名和實體類的屬性名一致
第二種:通過ResutlMap來映射字段名和實體類屬性名的一一對應的關系。
<select id="selectlike">
? select * from foo where bar like #{value}
</select>
第 2 種:在 sql 語句中拼接通配符,會引起 sql 注入
<select id="selectlike">
? select * from foo where bar like "%"#{value}"%"
</select>
1)MyBatis動態sql可以讓我們在Xml映射文件內,以標簽的形式編寫動態sql,完成邏輯判斷和動態拼接sql的功能,MyBatis提供了9種動態sql標簽 trim | where | set | foreach | if | choose | when | otherwise | bind。
2)其執行原理為,使用OGNL從sql參數對象中計算表達式的值,根據表達式的值動態拼接sql,以此來完成動態sql的功能。
Dao接口的工作原理是JDK動態代理,Mybatis運行時會使用JDK動態代理為Dao接口生成代理proxy對象,代理對象proxy會攔 截接口方法,轉而執行MappedStatement所代表的sql,然后將sql執行結果返回。
Dao接口里的方法,是不能重載的,因為是全限名+方法名的保存和尋找策略。
MyBatis實現一對一、一對多關聯查詢一般有兩種方式:
方式一:sqlMapper配置文件
一對一:在resultMap標簽中使用 association 標簽
一對多:在resultMap 標簽中使用collection 標簽
方式二:注解
一對一:在@Results 注解中的@Result注解中使用@One注解
一對多:在@Results 注解中的@Result 注解中使用@Many注解
useGeneratedKeys為true,持自動生成主鍵,keyProperty和keyColumn分別代表數據庫記錄主鍵字段和java對象成員屬性名
dao層 修飾符 為 void,不需要返回任何
<insert id="insertEntity" parameterType="**" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
//dao層 修飾符 為 void,不需要返回任何
void batchInsert(List<TAlarmChannelEntity> list);
<insert id="batchInsert" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id" >
INSERT INTO t_alarm_channel
(channel, silent_cycle, aggregation_mode,threshold,effective_start_time,effective_end_time,inform_obj,selected,create_time)
VALUES
<foreach collection="list" index="index" item="bo" separator=",">
(
#{bo.channel}, #{bo.silentCycle}, #{bo.aggregationMode},#{bo.threshold},#{bo.effectiveStartTime},#{bo.effectiveEndTime},#{bo.informObj},#{bo.selected},now()
)
</foreach>
</insert>
ResultMap是??指定返回值與對象及與對象內部屬性名和數據庫列名的綁定
ResultType是直接返回值與別名庫當中的java對象的映射
1,第一種:
public UserselectUser(String name,String area); 對應的 xml,#{0}代表接收的是 dao 層中的第一個參數,#{1}代表 dao 層中第二 參數,更多參數一致往后加即可。
<select id="selectUser"resultMap="BaseResultMap">
? select * from user_user_t where user_name = #{0} and user_area=#{1}
</select>
2,第二種:使用@param注解:
public interface UserMapper {
? ? User selectUser(@param("username") String username,
? ? ? ? ? ? ? ? ? ? @param("hashedpassword") sString hashedpassword);
}
然后,就可以在 xml 像下面這樣使用(推薦封裝為一個 map,作為單個參數傳遞給mapper):
<select id="selectuser" resulttype="user">
? select id, username, hashedpassword
? from some_table
? where username = #{username} and hashedpassword = #{hashedpassword}
</select>
3、第三種:多個參數封裝成 map
try {
? ? //映射文件的命名空間.SQL 片段的 ID,就可以調用對應的映射文件中的SQL
? ? //由于我們的參數超過了兩個,而方法中只有一個 Object 參數收集,因此我們使用 ? ? Map 集合來裝載我們的參數
? ? Map < String, Object > map = new HashMap();
? ? map.put("start", start);
? ? map.put("end", end);
? ? return sqlSession.selectList("StudentID.pagination", map);
} catch (Exception e) {
? ? e.printStackTrace();
? ? sqlSession.rollback();
? ? throw e;
} finally {
? ? MybatisUtil.closeSqlSession();
}