mybatis插入关联数据的问题?

mybatis插入关联数据的问题?,第1张

insert标签内 插入

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

SELECT SEQ_TEST.NEXTVAL FROM DUAL

</selectKey>

<insert id="User.insert" parameterType="User">

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

SELECT SEQ_USER.NEXTVAL FROM DUAL

</selectKey>

insert into

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

</insert>

你能得到此时插入后的id

可以通过关系映射查询出来 请看下面

在mybatis中,没有级联的概念,但是可以利用集合来实现类似的功能。

mybatis3.0添加了association和collection标签专门用于对多个相关实体类数据进行级联查询,但仍不支持多个相关实体类数据的级联保存和级联删除 *** 作。因此在进行实体类多对多映射表设计时,需要专门建立一个关联对象类对相关实体类的关联关系进行描述。

插入关联表:

<insert id="insertWife" useGeneratedKeys="true" keyProperty="wid" parameterType="com.cssl.pojo.Wife">

insert into wife (name,h_id) values (#{name},#{husband.hid})

</insert>

关联映射:嵌入式、继承式 引入式等

先在数据库建立好主外键关系

在xml里面写一个resultMap作为返回类型,如果是多对一 用association 一对多用collection

例子

<!-- 多对一 -->

<resultMap id="wifeandhusband" type="wife">

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

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

<association property="husband" column="w_hid" javaType="com.cssl.pojo.Husband">

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

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

</association>

</resultMap>

<!-- 一对多 -->

<resultMap id="husbandandwife" type="com.cssl.pojo.Husband">

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

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

<collection property="wifes" ofType="wife"> --ofType集合中的类型

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

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

</collection>

</resultMap>

<select id="selectWife" resultMap="wifeandhusband">

select w.*,h.* from wife w left join husband h on w.h_id=h.hid

</select>

注意:

1、关联查询一定要带有关联对象的id(主外键),否则集合只会有一条记录存在(认为你查询的是一个对象)

如:

select h.name,h.age,w.wname from wife w left join husband h on h.hid=w.h_id

2、表连接中不同表有同名字段的时候:a和b都有name字段

<resultMap type="b" id="b">

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

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

<association property="a" javaType="a">

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

<result property="name" column="aname"/>

</association>

</resultMap>

<select id="select" resultMap="b">

select a.id aid,a.name aname,b.id,b.name from a,b where a.id=b.id

</select>


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

原文地址: http://outofmemory.cn/bake/11619827.html

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

发表评论

登录后才能评论

评论列表(0条)

保存