8.MyBatis的主键如何获取

8.MyBatis的主键如何获取,第1张

插入 *** 作

对于自增主键的表,插入可以不配置插入的主键列。否则是必须的。

获取主键

插入语句之前配置:主要是针对Sequence主键而言,插入前必须指定一个主键值给要插入的记录。Oracle、DB2亦如此,方法是在插入语句标签<insert>之前配置上:

<insert id="AltNameinsert" parameterType="AltName">

<selectKey resultType="long" keyProperty="id">

SELECT SEQ_TESTNEXTVAL FROM DUAL

</selectKey>

insert into

altname(primaryName,alternateName,type)values(#{primaryName},#{alternateName},#{type})

</insert>

插入语句之后配置:蛀牙是针对自增主键的表而言,这类表在插入时不需要主键,而是在插入过程自动获取一个自增的主键。比如MySQL

<insert id="AltNameinsert" parameterType="AltName">

<selectKey resultType="long" keyProperty="id">

SELECT LAST_INSERT_ID()

</selectKey>

insert into

altname(primaryName,alternateName,type)values(#{primaryName},#{alternateName},#{type})

</insert>

当然,是否需要配置<selectKey>根据情况,只要能保证记录有主键即可。一旦配置了<selectKey>,就可以在执行插入 *** 作时获取到新增记录的主键。

注意:如果没有配置<selectKey>那么保存后的对象的主键依旧为null

使用现有的Service接口,或者自己在编写一些用到的接口,手动使用Java代码来分别调用Service接口来查出各个model,然后在业务层将model转换为vo,最后返回给前端json串。

为需求相关的页面定义自己的vo,在vo中只定义前端用到的字段。而不是像第一种方式一样vo中一层一层的嵌套model。然后使用sql语句进行表关联,查询用到的字段。组装为vo直接返回

<resultMap id="checkAccountReturn" type="javautilHashMap">

<id property="account_id" column="account_id" />

<result property="sub_account_id" column="sub_account_id"/>

<result property="status" column="status"/>

<result property="account_status" column="account_status"/>

<result property="total_count" column="total_count"/>

<result property="sms_sign" column="sms_sign"/>

</resultMap>

<select id="checkSub_account" resultMap="checkAccountReturn">

SELECT account_id,sub_account_id,status,account_status,total_count,sms_sign

FROM sub_account

<where>

<if test="account_id!=null">

account_id=#{account_id}

</if>

<if test="sub_account_id!=null">

and sub_account_id = #{sub_account_id} and status=1 and total_count!=0 and account_status=1

</if>

</where>

</select>

无法直接通过insert *** 作返回,insert只能返回 *** 作成功的数据条数,一般为0,1等。

如果想要知道插入的数据的id,一般做法是提前知道了那条数据对于的编号,或者名称等可能可以作为唯一判断的条件,或者组合条件,在插入完成后再通过这些条件去查询数据库获取到这条数据,从而获取id等数据

12<insert id="xxx" parameterType="xxx" useGeneratedKeys="true" keyProperty="id"></insert>

useGeneratedKeys

true,需要你表主键自动增长

keyProperty

id,主键名称为id

比如又一个实体类User,实例化成user,里面有

id

name

sex,三个属性,name

sex赋值之后,调用insert,此时user

的id值会自动赋值进去。

以上就是关于8.MyBatis的主键如何获取全部的内容,包括:8.MyBatis的主键如何获取、mybatis中resultmap用法问题、mybatis 做 insert *** 作的时候 怎么才能返回插入的那条数据的id等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/9696402.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-01
下一篇 2023-05-01

发表评论

登录后才能评论

评论列表(0条)

保存