mybatisPlus save(storageLocation)后如何获得自增主键
时间: 2024-02-18 17:03:05 浏览: 39
MybatisPlus的save方法会自动将生成的自增主键赋值给传入的实体对象中,你可以通过实体对象的getId()方法来获取自增主键的值。例如:
```java
StorageLocation storageLocation = new StorageLocation();
storageLocation.setName("test");
storageLocation.setCapacity(10);
storageLocationMapper.save(storageLocation);
Long id = storageLocation.getId(); // 获取自增主键的值
```
注意,如果你使用的是MybatisPlus的saveBatch方法来批量插入数据,那么因为批量插入时并不会返回自增主键值,所以无法获取自增主键。
相关问题
servce层获得 mybatisPlus 插入后bigint类型的自增主键
在使用 MybatisPlus 插入数据时,如果表中有自增主键(如 MySQL 中的 bigint 类型的自增主键),可以通过以下方式获取插入后的主键值:
1. 在实体类中使用 @TableId 注解标注自增主键,并设置注解的 type 属性为 IdType.AUTO,示例代码如下:
```java
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
// getter and setter methods
}
```
2. 在 Service 层中使用 MybatisPlus 提供的 save 方法插入数据,示例代码如下:
```java
User user = new User();
user.setName("张三");
user.setAge(20);
userService.save(user);
Long id = user.getId(); // 获取插入后的主键值
```
注意:在插入数据时,如果使用 MybatisPlus 提供的 saveOrUpdate 方法,需要先判断实体类中的自增主键是否为 null,如果不为 null,则认为该数据已存在,会执行更新操作而不是插入操作,此时无法获取插入后的主键值。
jfinal自增Db.save获取自增主键id
在 JFinal 中,我们可以通过 `Db.save()` 方法向数据库中插入一条记录,并且获取该记录的自增主键 id。具体实现方式如下:
1. 首先,我们需要在数据库表中设置自增主键,例如:
```sql
CREATE TABLE user (
id INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
```
2. 在 Java 代码中,我们可以使用 `Record` 对象来表示一条记录,例如:
```java
Record user = new Record().set("username", "test").set("password", "123456");
```
3. 然后,我们可以调用 `Db.save()` 方法将该记录插入到数据库中,并且获取自增主键 id,例如:
```java
boolean success = Db.save("user", user);
if (success) {
int id = user.get("id");
System.out.println("插入成功,自增主键 id 为:" + id);
} else {
System.out.println("插入失败");
}
```
在上面的代码中,我们首先调用 `Db.save()` 方法将记录插入到数据库中,然后通过 `Record.get()` 方法获取自增主键 id。
需要注意的是,在使用 `Db.save()` 方法时,如果表中存在自增主键,则必须将该字段设置为 null 或者不设置该字段,否则会导致插入失败。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)