JAVA中使用mybatis-plus,如何得到刚插入信息的ID
JAVA中使用mybatis-plus,如何得到刚插入信息的ID在 Java 中使用 MyBatis-Plus 插入数据后,如果想要获取刚插入记录的 ID,可以通过以下几种方式实现。MyBatis-Plus 提供了很好的支持来自动获取主键。
### 1. 使用`@TableId`注解
确保你的实体类中主键字段使用了`@TableId`注解,并且设置了`type`属性为`IdType.AUTO`或`IdType.INPUT` (具体取决于你的数据库和需求)。
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("your_table_name")
public class YourEntity {
@TableId(type = IdType.AUTO) // 或者 IdType.INPUT
private Long id; // 主键字段
// 其他字段
// getters 和 setters
}
### 2. 插入数据并获取 ID
在插入数据时,可以直接使用 MyBatis-Plus 提供的`save`方法,插入成功后实体对象的主键字段会被自动填充。
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@Autowired
private IService<YourEntity> yourEntityService; // 这里使用 MyBatis-Plus 的 IService
public Long insertAndGetId(YourEntity entity) {
yourEntityService.save(entity); // 插入数据
return entity.getId(); // 返回插入后自动生成的 ID
}
}
### 3. 使用`insert`方法
如果你使用的是`BaseMapper` ,可以直接调用`insert`方法。
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@Autowired
private BaseMapper<YourEntity> yourEntityMapper;
public Long insertAndGetId(YourEntity entity) {
yourEntityMapper.insert(entity); // 插入数据
return entity.getId(); // 返回插入后自动生成的 ID
}
}
### 总结
- 在实体类中使用`@TableId`注解标记主键,并设置适当的 ID 生成策略。
- 使用 MyBatis-Plus 的`save`方法或`insert`方法插入数据,插入后主键字段会自动填充。
- 通过返回的实体对象获取刚插入记录的 ID。
页:
[1]