數據庫:SqlServer2005,表結構:java
/*==============================================================*/ /* Table: Dic_City */ /*==============================================================*/ create table Dic_City ( ID int identity, City_Code varchar(10) not null, Provinces_Code varchar(20) not null, State_Code varchar(10) not null, City_Name varchar(50) null, PY_Code varchar(50) null, PY_Code_Short varchar(10) null, Ext1 varchar(20) null, Ext2 varchar(20) null, Ext3 varchar(20) null, Ext4 varchar(20) null, Ext5 varchar(20) null, constraint PK_DIC_CITY primary key (ID) )
MyBatisXML配置,下面兩種方式都行sql
方式1:數據庫
<insert id="insert" parameterType="cn.softsea.model.DicCity" > <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" > SELECT @@IDENTITY </selectKey> insert into Dic_City (City_Code, Provinces_Code, State_Code, City_Name, PY_Code, PY_Code_Short, Ext1, Ext2, Ext3, Ext4, Ext5) values (#{cityCode,jdbcType=VARCHAR}, #{provincesCode,jdbcType=VARCHAR}, #{stateCode,jdbcType=VARCHAR}, #{cityName,jdbcType=VARCHAR}, #{pyCode,jdbcType=VARCHAR}, #{pyCodeShort,jdbcType=VARCHAR}, #{ext1,jdbcType=VARCHAR}, #{ext2,jdbcType=VARCHAR}, #{ext3,jdbcType=VARCHAR}, #{ext4,jdbcType=VARCHAR}, #{ext5,jdbcType=VARCHAR}) </insert>
方式2:mybatis
<insert id="insert" parameterType="cn.softsea.model.DicCity" useGeneratedKeys="true" keyProperty="id"> insert into Dic_City (City_Code, Provinces_Code, State_Code, City_Name, PY_Code, PY_Code_Short, Ext1, Ext2, Ext3, Ext4, Ext5) values (#{cityCode,jdbcType=VARCHAR}, #{provincesCode,jdbcType=VARCHAR}, #{stateCode,jdbcType=VARCHAR}, #{cityName,jdbcType=VARCHAR}, #{pyCode,jdbcType=VARCHAR}, #{pyCodeShort,jdbcType=VARCHAR}, #{ext1,jdbcType=VARCHAR}, #{ext2,jdbcType=VARCHAR}, #{ext3,jdbcType=VARCHAR}, #{ext4,jdbcType=VARCHAR}, #{ext5,jdbcType=VARCHAR}) </insert>
調用Mapper返回主鍵:app
//生成新對象用於插入 DicCity city = new DicCity(); city.setCityCode("330100"); city.setCityName("杭州市"); //獲取mapper對象 DicCityMapper cityMapper = (DicCityMapper) SpringContextUtil.getBean("dicCityMapper"); int row = cityMapper.insert(city); //insrt再也不返回主鍵,只返回響應行數,這點和ibatis不一樣了 System.out.println("響應的行數:"+row); //取得自增的標識列 ID的值 System.out.println("新插入的數據的ID:"+city.getId());
若是使用mybatis.generator來生成DAO層的話,generatorConfig.xml中要使用:ide
<generatedKeycolumn="id"sqlStatement="MySql"identity="true"/>