我的表中有两列是 BigInt 数据类型(NODEID 和 ULNODEID),我想保持这种状态。我正在为这些表使用 MYSQL workbench 8.0。
我想使用以下函数获取我的 nodeid 的值:
public long get_urlnodeid(long nodeID) {
try {
String sql = "select NODEID from urllink where ULNODEID="+nodeID;
if (em == null) {
throw new Exception("could not found URL object.");
}
return (long) em.createNativeQuery(sql).getSingleResult();
} catch (Exception e) {
msg = CoreUtil.wrapMsg(CoreUtil.FUNC_ERROR,
this.getClass().getName(), "get", e.getMessage());
}
return 0;
}
它抛出一个异常说 Big Integer cannot be cast to java.lang.Long
有没有一种方法可以检索值,同时将其保存在 long
中?
最佳答案
只需查看 BigInteger 的 Java 文档:
public long longValue()
Converts this BigInteger to a long. This conversion is analogous to a narrowing primitive conversion from long to int as defined in section 5.1.3 of The Java™ Language Specification: if this BigInteger is too big to fit in a long, only the low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.
所以你会想要这样的东西:
return ((BigInteger)em.createNativeQuery(sql).getSingleResult()).longValue();
我建议添加一些类型检查。
--
另一种选择,如果您可以完全控制您的应用程序,并且您希望值超出 long
的范围,则让您的方法返回 BigInteger
而不是长
:
public BigInteger get_urlnodeid(long nodeID) {
和:
return (BigInteger) em.createNativeQuery(sql).getSingleResult();
当然,调用此方法的应用程序的其余部分也必须使用 BigInteger
。
请注意,使用 BigInteger
而不是 long
的性能要低得多,因此只有在性能不是问题或者您绝对确定值会影响时才使用它如此之大,这是绝对必要的。
关于java- ClassCastException- BigInt 无法转换为 Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55528355/