数据库是mysql,插入A表一条数据,会生成一个主键id,作为B表第二条数据的外键,把两次插入放到同一事务实现,请问具体应该怎么实现MyBatisSpringMySQL

解决方案 »

  1.   


    <insert id="insert" parameterType="Role">
    <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id"> 
             select last_insert_rowid() as id
            </selectKey>
    insert into t_role
    <trim prefix="(" suffix=")" suffixOverrides=",">
       <if test="id != null">id,</if>
       <if test="name != null">name,</if>
       <if test="desecr != null">descr,</if>
       <if test="status != null">status,</if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
       <if test="id != null">#{id,jdbcType=INTEGER},</if>
       <if test="name != null">#{name,jdbcType=VARCHAR},</if>
       <if test="descr != null">#{descr,jdbcType=VARCHAR},</if>
       <if test="status != null">#{status,jdbcType=INTEGER},</if>
    </trim>
    </insert>
    select last_insert_rowid() as id这句换成mysql适用的...然后你的model就会在插入记录后产生一个id自动set进对象属性里面
      

  2.   


    这个我知道,只是返回id后,在执行另外一个insert的时候报错了Cannot change the ExecutorType when there is an existing transaction。
    bean我是这样配置的:
    <bean id="wkGoodsMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.wukong.mobile.mapper.WkGoodsMapper" />
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
    <bean id="wkGoodsDetaiMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.wukong.mobile.mapper.WkGoodsDetailMapper" />
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
    sqlSessionFactory是这样的:
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    .........
    </bean>
    还有一个:
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory" />
    <constructor-arg index="1" value="BATCH" />
    </bean>
    如果注入了这个,id就不会返回了
      

  3.   

    service是这样的:
    wkGoodsMapper.insertGoods(goodsVo);
    GoodsDetailVo detailVo = goodsVo.getGoodsDetailVo();
    detailVo.setGoodsId(goodsVo.getId());
    wkGoodsDetailMapper.insertGoodsDetail(detailVo);
      

  4.   

    <insert id="insertArticle" parameterType="com.tm.bean.Article" useGeneratedKeys="true" keyProperty="id">
    比如你传的article,加上useGeneratedKeys 和keyProperty属性,mybatis会把id返回赋值到article,和bibernate类似的save() 方法很类似  然后你从article就可以取出新生成的id了  
    控制事物的话,你把它放到同一个service层的方法中不就行了
      

  5.   


    我现在就是放到同一个service里面的:
    wkGoodsMapper.insertGoods(goodsVo);
    GoodsDetailVo detailVo = goodsVo.getGoodsDetailVo();
    detailVo.setGoodsId(goodsVo.getId());
    wkGoodsDetailMapper.insertGoodsDetail(detailVo);mapper配置的sqlSessionFactory,wkGoodsDetailMapper.insertGoodsDetail(detailVo);就会报错