1. 程式人生 > >MyBatis返回主鍵

MyBatis返回主鍵

mapper檔案中返回主鍵:

  <insert id="insert" parameterType="com.za.cls.model.CompanyLeaseInfo" >
    <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into company_lease_info (name, code, business_licence, 
      oper_name, oper_phone, card_no, 
      province_code, province_name, city_code, 
      city_name, area_code, area_name, 
      addr_detail, founded_time, contact_realname, 
      contact_phone, contact_email, manager_id, 
      open_account_status, status, create_time, 
      modify_time)
    values (#{name,jdbcType=VARCHAR}, #{code,jdbcType=VARCHAR}, #{businessLicence,jdbcType=VARCHAR}, 
      #{operName,jdbcType=VARCHAR}, #{operPhone,jdbcType=VARCHAR}, #{cardNo,jdbcType=VARCHAR}, 
      #{provinceCode,jdbcType=VARCHAR}, #{provinceName,jdbcType=VARCHAR}, #{cityCode,jdbcType=VARCHAR}, 
      #{cityName,jdbcType=VARCHAR}, #{areaCode,jdbcType=VARCHAR}, #{areaName,jdbcType=VARCHAR}, 
      #{addrDetail,jdbcType=VARCHAR}, #{foundedTime,jdbcType=VARCHAR}, #{contactRealname,jdbcType=VARCHAR}, 
      #{contactPhone,jdbcType=VARCHAR}, #{contactEmail,jdbcType=VARCHAR}, #{managerId,jdbcType=INTEGER}, 
      #{openAccountStatus,jdbcType=BIT}, #{status,jdbcType=TINYINT}, #{createTime,jdbcType=TIMESTAMP}, 
      #{modifyTime,jdbcType=TIMESTAMP})
  </insert>

  在service層,呼叫這個方法後,根據getId方法可以獲取主鍵。但在web層,controller的方法裡,卻獲取的是null。

原因:web層和service層是通過dubbo呼叫的,其物件不是同一個,故獲取不到主鍵。

解決方法:在service層返回主鍵,web層直接獲取主鍵,而不是通過物件的getId方法獲取。