MyBatis Plus插入后返回ID主键(自增)

在MyBatisPlus中添加注解信息即可

//实体类(此处需要添加对应的MyBatisPlus主键信息)
public class Notice{
    private int noticeId;
    private String release_date;
    private String content;
}
//方案一:自定义SQL(自增主键)
 @Insert("insert into notice(release_date,content)values(#{releaseDate},#{content})")
//keyProperty对象的属性,keyColumn数据库表主键
 @Options(useGeneratedKeys = true,keyProperty = "noticeId",keyColumn = "notice_id")
 int addNotice(Notice notice);
//方案二:MyBatisPlus的insert方法(自增主键)
 @TableId(value = "notice_id",type=IdType.AUTO);//需要在实体类的主键属性上添加此句
 private int noticeId;

测试

@Test
public void test2(){
    Notice notice1 = new Notice();
    notice1.setContent("我是测试数据3");
    notice1.setReleaseDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    //自定义SQL
    int notice = activityMapper.addNotice(notice1);
    System.out.println(notice+"------------>"+notice1);
}
@Test
public void test3(){
	Notice notice = new Notice();
    notice.setContent("封装的id");
    notice.setReleaseDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    int i = noticeMapper.insert(notice);
    System.out.println(i+"------->"+notice);
}
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis Plus 中,插入数据并返回自增 ID 可以通过以下步骤实现: 1. 创建一个实体类,用于映射数据库表的字段和属性。 2. 在实体类中,标注 `@TableName` 注解,指定对应的数据库表名。 3. 在实体类中,使用 `@TableId` 注解标注主键字段,并设置 `@TableId(type = IdType.AUTO)`,表示使用数据库自增主键。 4. 调用 MyBatis Plus 提供的 `insert` 方法插入数据,插入成功后,自增 ID 将会被赋值到实体类对应的字段上。 以下是一个示例代码: ```java import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; @Repository public interface UserMapper extends BaseMapper<User> { } @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public boolean saveUser(User user) { return save(user); } } @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; // 省略 getter 和 setter } ``` 在上述示例中,`User` 类是一个实体类,对应数据库中的 `user` 表。`id` 字段使用 `@TableId(type = IdType.AUTO)` 注解标注为自增主键。 在 `UserServiceImpl` 类中,调用 `save` 方法插入数据,插入成功后,自增 ID 将会被赋值到 `user` 对象的 `id` 字段上。 你可以根据你的需求在 `UserServiceImpl` 类中添加其他方法,如查询、更新等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值