简体   繁体   English

MySQL DB 上的 SimpleJdbcInsert 在 executeAndReturnKey 方法后返回 BigInteger 而不是 Long

[英]SimpleJdbcInsert on MySQL DB returning BigInteger instead of Long after executeAndReturnKey method

I am running a simple insert query on a MySQL table with the following primary key declaration:我正在使用以下主键声明对 MySQL 表运行简单的插入查询:

id BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY

They key returned is a BigInteger for some reason.由于某种原因,他们返回的键是 BigInteger。 What changes do I need to make for a Long value to be returned as the key?我需要进行哪些更改才能将 Long 值作为键返回?

EDIT编辑

I'm making a mini-ORM basically and the Long type is not known at compile time since it is a class parameter ( AbstractDao<T, I> ).我基本上正在制作一个 mini-ORM,并且 Long 类型在编译时是未知的,因为它是一个 class 参数( AbstractDao<T, I> )。 Essentially I need to be able to convert a Number to a Long without using anything that has long in it (Long.valueOf(), .longValue(), etc).本质上,我需要能够将 Number 转换为 Long 而无需使用其中包含 long 的任何内容(Long.valueOf()、.longValue() 等)。

I do however have a Class instance that contains Long.class:但是,我确实有一个包含 Long.class 的 Class 实例:

protected Class<?> idClass = ((Class<?>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1]);

Can that instance somehow be used to perform the casting?该实例可以以某种方式用于执行强制转换吗? You cannot just cast a BigInteger to a Long, nor can you cast a String representation of BigInteger to a Long sadly.您不能只将 BigInteger 转换为 Long,也不能将 BigInteger 的 String 表示形式转换为 Long。 If there was a way to access valueOf() from my class object this might work?如果有办法从我的 class object 访问 valueOf() 这可能有效吗?

executeAndReturnKey(...) returns aNumber , so call longValue() if you want the result as a long . executeAndReturnKey(...)返回一个Number ,因此如果您希望结果为long ,请调用longValue()

If your method doesn't know the exact numeric type needed by the caller, let the caller do the longValue() .如果您的方法不知道调用者所需的确切数字类型,请让调用者执行longValue() Alternatively, write multiple methods, for the various return types you want to support, eg或者,为您想要支持的各种返回类型编写多个方法,例如

public Number insertAndGetKey(...) {
    return ...executeAndReturnKey(...);
}
public int insertAndGetIntKey(...) {
    return insertAndGetKey(...).intValue();
}
public long insertAndGetLongKey(...) {
    return insertAndGetKey(...).longValue();
}

This, although extremely ugly, works like a charm:这虽然非常丑陋,但就像一个魅力:

var method = idClass.getMethod("valueOf", String.class);
var result = method.invoke(null, key.toString());

This returns something I can then typecast to (I) without issues.这会返回一些我可以毫无问题地类型转换为 (I) 的内容。 Please do let me know if you have a better solution to all this.如果您有更好的解决方案,请告诉我。 The original question being about the BigInteger return type, this can probably be avoided.最初的问题是关于 BigInteger 返回类型,这可能是可以避免的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM