总结:
使用gorm时,记得要给主键和索引字段,增加gorm的tag,可以显著提升insert的速度
type Student struct {StudentId stringIdCard stringStudentNum stringBirthday stringName stringGender stringClassId stringNation string `gorm:"type:varchar(10);not null;default:'';comment:'民族'"`OrgId string}
如上图结构体定义,Nation写了gorm的tag,不是必填项,这个时候使用gorm做insert操作效率会非常低
原因:
gorm成功插入数据后,紧接着会查询一次,确认数据是否入库,而作为查询条件的字段,就是tag标记的字段,但是这个字段不是必填项,且默认值是零值,所以库中符合条件的数据会非常多,如果数据量较大那么接口必定超时。
解决办法:
给主键和索引字段都加上tag
type Student struct {StudentId string `gorm:"type:varchar(32);primary_key;not null;"`IdCard string `gorm:"type:varchar(20);index:stu_id_index;not null;"`StudentNum stringBirthday stringName stringGender stringClassId stringNation string `gorm:"type:varchar(10);not null;default:'';comment:'民族'"`OrgId string}
