SqlServer主键自增及插入操作问题

定义主键自增

在这里插入图片描述
更改标识规范改为,就完成了主键自增的设置

插入操作

Person
对于此表

insert into Person(id,tname,age) values (#{id},#{tname},#{age})

//报错
org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: com.microsoft.sqlserver.jdbc.SQLServerException: 当 IDENTITY_INSERT 设置为 OFF 时,不能为表 'Person' 中的标识列插入显式值。
### The error may exist in cn/mapper/PersonMapper.xml
### The error may involve cn.mapper.PersonMapper.InsertPerson-Inline
### The error occurred while setting parameters
### SQL: /*set IDENTITY_INSERT Person ON*/         insert into Person(id,tname,age) values (?,?,?)         /*set IDENTITY_INSERT Person OFF*/
### Cause: com.microsoft.sqlserver.jdbc.SQLServerException: 当 IDENTITY_INSERT 设置为 OFF 时,不能为表 'Person' 中的标识列插入显式值。

//或者
org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: com.microsoft.sqlserver.jdbc.SQLServerException: 不能将值 NULL 插入列 'id',表 'tan.dbo.Person';列不允许有 Null 值。INSERT 失败。
### The error may exist in cn/mapper/PersonMapper.xml
### The error may involve cn.mapper.PersonMapper.InsertPerson-Inline
### The error occurred while setting parameters
### SQL: set IDENTITY_INSERT Person ON         insert into Person(id,tname,age) values (?,?,?)         set IDENTITY_INSERT Person OFF
### Cause: com.microsoft.sqlserver.jdbc.SQLServerException: 不能将值 NULL 插入列 'id',表 'tan.dbo.Person';列不允许有 Null 值。INSERT 失败。

正确的自增插入语句

insert into Person(tname,age) values (#{tname},#{age})

不需要自增字段

关于插入返回id值的配置

<!--
xml方式
	useGeneratedKeys="true"		开启自动返回主键id
	keyProperty="id"			实体属性名称
	keyColumn="id"				数据库表字段名称
-->
<insert id="InsertPerson" parameterType="Person" useGeneratedKeys="true" keyProperty="id" keyColumn="id">

<--注解方式-->
@Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id")

id值就返回到实例中

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值