SelectKey returned more than one value

探讨使用MyBatis进行插入操作时遇到的错误及解决方法。通过调整实体类中主键生成策略的注解,避免了错误的发生,并详细解释了不同注解的意义及其适用场景。

问题:使用mybatis进行插入操作时一直报错,报错具体信息如下图,但是数据插入成功了,其他查询更新操作不会有问题。

解决方案:

网上百度好多方法是说查询操作时返回结果多于期望的一条,但姐姐是插入操作呢,蒙圈。

猜测应该是和主键自动生成有关系了,查看数据表对应的实体类,发现主键字段使用了注解

@GeneratedValue(strategy = GenerationType.IDENTITY),去掉该注解后,报错消失啦。

看了下其他实体类,有用@GeneratedValue(generator = "JDBC")这个的,也是没有问题的。

注解简单说明:

1、@GeneratedValue的两个属性

① generator=“JDBC”:属性值为所使用的主键生成器的名称,名称来源于SequenceGenerator 或TableGenerator注解的name属性值。

② strategy --- GenerationType 主键的生成策略, GenerationType 的值如下:

public enum GenerationType { 

    /**
     * Indicates that the persistence provider must assign 
     * primary keys for the entity using an underlying 
     * database table to ensure uniqueness.
     * 指示持久性提供程序必须使用基础数据库表为实体分配主键,以确保唯一性。
     */
    TABLE, 

    /**
     * Indicates that the persistence provider must assign 
     * primary keys for the entity using database sequence column.
     * 指示持久性提供程序必须使用数据库序列列为实体分配主键。
     */
    SEQUENCE, 

    /**
     * Indicates that the persistence provider must assign 
     * primary keys for the entity using database identity column.
     * 指示持久性提供程序必须使用数据库标识列为实体分配主键。
     */
    IDENTITY, 

    /**
     * Indicates that the persistence provider should pick an 
     * appropriate strategy for the particular database. The 
     * <code>AUTO</code> generation strategy may expect a database 
     * resource to exist, or it may attempt to create one. A vendor 
     * may provide documentation on how to create such resources 
     * in the event that it does not support schema generation 
     * or cannot create the schema resource at runtime.
     * 表示持久性提供程序应为特定数据库选择适当的策略。 <code> AUTO </ code>生成策略可能期望存 
     * 在数据库资源,或者它可能尝试创建数据库资源。 供应商可以提供有关如何在不支持模式生成或无法 
     * 在运行时创建模式资源的情况下创建此类资源的文档。
     */
    AUTO
}

上面Google翻译了一下:

Table:意思是,需要有数据表来解决主键生成,需要配合@TableGenerator注解使用

SEQUENCE:意思是,使用指定的sequence来生成主键,需要配合@SequenceGenerator注解使用

IDENTITY:根据数据库的Identity字段生成

AUTO:默认是该属性值,按数据库自增长

2、注解用和不用有什么区别;

 

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值