mybatis-plus实体子类的字段怎么insert和update

mybatis-plus实体子类的字段怎么insert和update 比如说 我实体类中有个子类 Area area 更新的s时候 想要area_id = #{area.id} 这样的 在mybatis plus里面怎么写呢

该回答引用chatgpt:
我们可以使用 @TableField 注解来指定实体类中的属性和数据库表中的列之间的映射关系。在您的情况下,您可以在父类实体类中声明一个 Area 对象,并在该对象的属性上添加 @TableField 注解,指定该属性对应的数据库表列名。例如:


public class EntityA {
    // ... 其他属性
    
    @TableField(value = "area_id")
    private Integer areaId;

    @TableField(exist = false)
    private Area area;
    
    // ... 其他方法
}

这里,我们在 areaId 属性上添加了 @TableField(value = "area_id") 注解,表示将 areaId 属性映射到数据库表的 area_id 列。我们还在 area 属性上添加了 @TableField(exist = false) 注解,表示 area 属性不对应数据库表的任何列,而只是一个 Java 对象。

然后,在进行插入或更新操作时,您可以使用 MyBatis-Plus 提供的 Wrapper 接口或 Lambda 表达式构建器来指定更新的条件和更新的字段。例如:

EntityA entityA = new EntityA();
entityA.setAreaId(area.getId());
// ... 其他属性赋值

// 构建更新条件
UpdateWrapper<EntityA> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", entityId); // 假设要更新的实体对象 ID 为 entityId

// 执行更新操作
int rows = entityAMapper.update(entityA, updateWrapper);


在这个例子中,我们首先将 Area 对象的 ID 赋值给 areaId 属性,然后构建一个 UpdateWrapper 对象,使用 eq 方法指定更新条件为 id = entityId。最后,我们调用 entityAMapper.update 方法执行更新操作。

类似地,如果要进行插入操作,您可以使用 Mybatis-Plus 提供的 BaseMapper 接口的 insert 方法插入新的记录。例如:

EntityA entityA = new EntityA();
entityA.setAreaId(area.getId());
// ... 其他属性赋值

int rows = entityAMapper.insert(entityA);


在这个例子中,我们创建一个新的 EntityA 对象,并将 Area 对象的 ID 赋值给 areaId 属性。然后,我们调用 entityAMapper.insert 方法将该实体对象插入到数据库中。

需要注意的是,在进行插入或更新操作时,实体对象中的所有属性都会被写入数据库,无论这些属性是属于父类还是子类。如果您只需要更新或插入部分属性,可以通过使用 Wrapper 接口或 Lambda 表达式构建器来指定要更新的属性,例如:


UpdateWrapper<EntityA> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", entityId) // 假设要更新的实体对象 ID 为 entityId
    .set("area_id", area.getId())
    .set("other


  • 你可以看下这个问题的回答https://ask.csdn.net/questions/229263
  • 这篇博客也不错, 你可以看下mybatis 的 insert
  • 除此之外, 这篇博客: mybatis的批量insert和update中的 批量insert 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • <insert id="batchInsert" parameterType="java.util.List">
    insert into 表名
    (字段1,字段2,字段3……)
    values
    <foreach collection="list" item="item" index="index" separator=",">
      (#{item.字段1,jdbcType=类型},
      #{item.字段2,jdbcType=类型},
      #{item.字段3,jdbcType=类型}……
      )
    </foreach>
    </insert>