1. 程式人生 > >mybatis -- 簡單增刪改

mybatis -- 簡單增刪改


----------------------- 增加 --------------------------------
<!--
   selectKey  ->    sql:獲得當前序列值 
   selectKey  ->    order :mysql(AFTER) 
   selectKey  ->    order :oracle(另一個)
-->
<insert id="insert" parameterType="com.rl.model.Person">  //傳入引數
    <selectKey keyProperty="personId"
order="AFTER" resultType="java.lang.Integer"> select last_insert_id() // selectKey:主建id返回 </selectKey> insert into person (person_id, naem, gender, addr, biethday) values (#{personId },#{name },#{gender },#{addr },#{biethday }) </insert> ----------------------- 修改 -------------------------------- <update id="update"
parameterType="com.rl.model.Person"> update person t set t.person_id = #{personId}, t.name = #{name} t.gender = #{gender} t.addr = #{addr} t.biethday = #{biethday} </update> ----------------------- 刪除 -------------------------------- <delete id="delete"
parameterType="java.lang.Integer"> delete from person where person_id = #{id} </delete> ----------------------- 資料層 ------------------------ @Test public void insert(){ SqlSession session = sessionFactory.openSession(); /* 增加不設定Id * 修改必須設定Id , 問題:沒設定的資料會被置空(動態修改) */ Person p = new Person(); //自行 set 資料(增加,修改) try { //返回響應條數(預設) / 返回 Id(需配置-selectKey ) int count = session.insert("com.rl.mapper.PersonMapper.insert", p); //新增 int count = session.update("com.rl.mapper.PersonMapper.update", p); //修改 int count = session.delete("com.rl.mapper.PersonMapper.delete", 1); //刪除 session.commit(); //提交事物 System.out.println(count); } catch (Exception e) { e.printStackTrace(); session.rollback(); //異常回滾 }finally{ session.close(); //關閉session } }