Insert时报“Column ‘id‘ cannot be null“ 错误如何自动生成主键id
如果你想让 MyBatis-Plus 自动生成主键值,可以使用 IdType.AUTO
或者不设置 type
属性。IdType.AUTO
将告诉 MyBatis-Plus 使用数据库自增策略来生成主键。
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.IdType;
public class YourEntity {
@TableId(type = IdType.AUTO)
private Long id; // 这里的id为主键字段
// 其他字段...
// getters and setters...
}
或者,你也可以省略 type
属性,因为默认的主键生成策略就是 AUTO
:
import com.baomidou.mybatisplus.annotation.TableId;
public class YourEntity {
@TableId
private Long id; // 这里的id为主键字段
// 其他字段...
// getters and setters...
}
如果你的主键是字符串,你可以考虑使用 IdType.UUID
或者不设置 type
,因为 MyBatis-Plus 默认会使用雪花算法生成一个唯一的字符串作为主键值。
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.IdType;
public class YourEntity {
@TableId(type = IdType.UUID)
private String id; // 这里的id为主键字段
// 其他字段...
// getters and setters...
}
或者省略 type
:
import com.baomidou.mybatisplus.annotation.TableId;
public class YourEntity {
@TableId
private String id; // 这里的id为主键字段
// 其他字段...
// getters and setters...
}
这样设置后,在插入数据时 MyBatis-Plus 会自动生成一个唯一的字符串作为主键值。确保数据库表中主键列允许为 null,且没有设置默认值。
还没有评论,来说两句吧...