mybatis如何獲取oracle新插入資料記錄的主鍵?
阿新 • • 發佈:2019-02-06
第一 用序列
<insert id="insertSelective" parameterType="com.zehin.vpaas.base.domain.SfyHazardAnalysis"> <selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="hazardId"> SELECT SEQUENCE_1.NEXTVAL FROM DUAL </selectKey> insert into SFY_HAZARD_ANALYSIS <trim prefix="(" suffix=")" suffixOverrides=","> HAZARD_ID, <if test="hazardTime != null"> HAZARD_TIME,</if> <if test="hazardTitle != null"> HAZARD_TITLE, </if> <if test="hazardMeasure != null"> HAZARD_MEASURE, </if> <if test="buildId != null"> BUILD_ID, </if> </trim> <trim prefix=" values(" suffix=")" suffixOverrides=","> #{hazardId,jdbcType=INTEGER}, <if test="hazardTime != null">#{hazardTime,jdbcType=VARCHAR},</if> <if test="hazardTitle != null"> #{hazardTitle,jdbcType=VARCHAR}, </if> <if test="hazardMeasure != null"> #{hazardMeasure,jdbcType=VARCHAR}, </if> <if test="buildId != null"> #{buildId,jdbcType= INTEGER}, </if> </trim> </insert>
上面就能實現,當你在java中往資料庫中插入一個物件,即一條資料時,可以獲取主鍵值,如下所示
@RequestMapping(value = "/addConstruManageInfo") @ResponseBody public Result addConstruManageInfo(SfyBuild sfyBuild){ System.out.println("檢視傳入的值====================================="+JSONObject.fromObject(sfyBuild).toString()); System.out.println("===========================================================輸入前主鍵值"+sfyBuild.getBuildId());//NULL int rows = sfyConstruManageService.insert(sfyBuild); System.out.println("===========================================================輸入後主鍵值"+sfyBuild.getBuildId());//數值
第二種 guid
<insert id="insertUser" parameterType="com.danny.mybatis.po.User">
<selectKey keyProperty="userId" order="BEFORE" resultType="java.lang.Integer">
select SYS_GUID() as userId from DUAL
</selectKey>
insert into T_USER(userId,userName,birthday,sex,address) values (#{userId},#{userName},#{birthday},#{sex},#{address}) </insert>
以下是mysql中獲取插入資料主鍵的配置方法
<insert id="add" parameterType="EStudent" useGeneratedKeys="true" keyProperty="id">
insert into TStudent(name, age) values(#{name}, #{age})
</insert>