java 将 bigint 转换为 long

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5553863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:38:28  来源:igfitidea点击:

Cast bigint to long

javadatabaseexceptioncasting

提问by Muhammad Imran Tariq

I am getting data from a database. I am getting classcastexception. In database my id is saved as BIGINT but in code(object) it is long. Is there is any problem while casting bigint to long?

我正在从数据库中获取数据。我正在收到 classcastexception。在数据库中,我的 id 被保存为 BIGINT 但在代码(对象)中它很长。将 bigint 转换为 long 时是否有任何问题?

采纳答案by aioobe

If this is MySql, you should probably use java.math.BigDecimal.

如果这是 MySql,您可能应该使用java.math.BigDecimal.

See the table at Java, JDBC and MySQL Types.

请参阅Java、JDBC 和 MySQL 类型中的表格。

enter image description here

在此处输入图片说明

回答by Lucas de Oliveira

have you tried casting your value to BigInteger first and then get the long value with longValue()? It should work. And aioobe is right, check for null values also.

您是否尝试先将您的值转换为 BigInteger,然后使用 longValue() 获取长值?它应该工作。aioobe 是对的,还要检查空值。

cheers!

干杯!

回答by Muhammad Waqas Dilawar

I was getting error java.math.BigInteger cannot be cast to java.lang.Longbecause I was getting the BigIntegerwhile querying using Spring Data native query, so then I've resolved using below code.

我收到错误java.math.BigInteger cannot be cast to java.lang.Long是因为我在使用 Spring Data 本机查询进行查询时得到了BigInteger,所以我使用下面的代码解决了这个问题。

((BigInteger)nativeQuery.getSingleResult()).longValue()