Java,将(转换)可序列化对象转换为其他对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7598692/
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
Java, convert(cast) Serializable objects to other objects
提问by Ali Khoshsirat
I'm using Session.save()
method (in Hibernate) to persist my entity objects which returns an object of type java.io.Serializable
.
我正在使用Session.save()
方法(在 Hibernate 中)来持久化我的实体对象,它返回一个类型为 的对象java.io.Serializable
。
The returned value is the generated primary key for the entity.
返回值是为实体生成的主键。
The generated primary key is of type long
(or bigint).
生成的主键是类型long
(或 bigint)。
The question is that: How can I convert or cast the returned value to long
?
问题是:如何将返回的值转换或转换为long
?
Serializable result = session.save(myEntityObject);
//This line of code fails.
long r = (long)result;
回答by Bhesh Gurung
Try casting the result (since it's not a primitive) to Long
instead of long
.
尝试将结果(因为它不是原始的)转换为Long
而不是long
.
Long r = (Long)result;
long longValue = r.longValue();
回答by Chris Kimpton
Have you tried using a debugger and breaking at that line to see what "result" is exactly?
您是否尝试过使用调试器并在该行中断以查看“结果”究竟是什么?
It could be BigDecimal or Long or ...
它可以是 BigDecimal 或 Long 或 ...
Alternatively, cant you just call the primary key getter method on the object - I'd have hoped it would be set by that point.
或者,您不能只调用对象上的主键 getter 方法 - 我希望它会在那时设置。
HTH, Chris
HTH,克里斯
回答by James DW
Try
尝试
long r = Long.valueOf(String.valueOf(result)).longValue();
回答by Rakesh
You should have specified the type of error you are getting ! Anyways this should work..
您应该已经指定了您遇到的错误类型!无论如何这应该工作..
long r = Long.valueOf(result)
回答by Xavi López
Try using long r = ((Long) result).getLong()
instead.
尝试使用long r = ((Long) result).getLong()
。
回答by H-net
thank you for your answers, but they were not the solution...
感谢您的回答,但它们不是解决方案...
I found it out... i misunderstood the function of statelessSession.get(...). The second parameter should be the primitive value of the primary-key if it is a non-composte key.
我发现了...我误解了 statelessSession.get(...) 的功能。如果是非组合键,第二个参数应该是主键的原始值。
If the Entity has a composite key you should pass the entity itself(with filled pk) as second argument...
如果实体有一个复合键,你应该将实体本身(用填充的 pk)作为第二个参数传递......
i was confused, because i thought that i need to pass allways an entity as second argument to statelessSession.get (because it works for multi-key-entitys)
我很困惑,因为我认为我需要将一个实体作为第二个参数传递给 statelessSession.get(因为它适用于多键实体)
Regards
问候