Mybatis在xml方法里新增语句时回显id

1、应用场景

在新增方法里,我们希望在A表中新增一条数据,新增后把这条数据的id给B表的某一列做为数值,我们通过Java代码做控制,需要id回显,才能拿到这A表中新增这条数据的id。

useGeneratedKeys="true" keyColumn="id" keyProperty="id"

举个例子:

<insert id="insertSelective" useGeneratedKeys="true" keyColumn="id" keyProperty="id" parameterType="com.purete.api.entity.sys.SysAttachmentEntity" >

然后我们在Java代码中,可以这样操控对象。

首先:你得让A实体类和B实体类建立关系

实体类建立关系:

public class DeviceInfoEntity

{

  private Long id;

  private String name;

  private DeviceInfoExtendEntity  extendEntity;

扫描二维码关注公众号,回复: 6120079 查看本文章

 

    public Long getId() {

        return id;

    }

 

    public void setId(Long id) {

        this.id = id;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name == null ? null : name.trim();

    }

 

    public DeviceInfoExtendEntity getExtendEntity()

    {

        return extendEntity;

    }

 

    public void setExtendEntity(DeviceInfoExtendEntity extendEntity)

    {

        this.extendEntity = extendEntity;

    }

}

 

 

xml文件建立关系:

<resultMap id="BaseResultMap" type="com.purete.api.entity.opers.device.DeviceInfoEntity">

        <id column="id" property="id" jdbcType="BIGINT"/>

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

        <association property="extendEntity" resultMap="extendResultMap"/>

    </resultMap>

 

    <resultMap id="extendResultMap" type="com.purete.api.entity.opers.device.DeviceInfoExtendEntity">

        <result column="device_id" property="deviceId" jdbcType="BIGINT"/>

        <result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>

        <result column="location" property="location" jdbcType="VARCHAR"/>

        <result column="lati" property="lati" jdbcType="DOUBLE"/>

        <result column="lngi" property="lngi" jdbcType="DOUBLE"/>

        <result column="province" property="province" jdbcType="VARCHAR"/>

        <result column="city" property="city" jdbcType="VARCHAR"/>

        <result column="county" property="county" jdbcType="VARCHAR"/>

 

    </resultMap>

 

Java方法:

int count=0;
 count = deviceInfoMapper.insertSelective(deviceInfoEntity);
   deviceInfoEntity.getExtendEntity().setDeviceId(deviceInfoEntity.getId());
    if (count > 0)
      {
           deviceInfoExtendMapper.insert(deviceInfoEntity.getExtendEntity());
      }

猜你喜欢

转载自blog.csdn.net/qq_35797735/article/details/85006652