[英]Java, convert(cast) Serializable objects to other objects
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;
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();
尝试
long r = Long.valueOf(String.valueOf(result)).longValue();
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,克里斯
Above answer not worked for me.以上答案对我不起作用。
I misunderstood the function of statelessSession.get(...)
.我误解了
statelessSession.get(...)
的功能。 The second parameter should be the primitive value of the primary-key
if it is a non-composte
key.如果
primary-key
non-composte
primary-key
则第二个参数应该是primary-key
的原始值。
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 always an entity as second argument to statelessSession.get
(because it works for multi-key-entitys).我很困惑,因为我认为我需要始终将一个实体作为第二个参数传递给
statelessSession.get
(因为它适用于多键实体)。
尝试使用long r = ((Long) result).getLong()
代替。
You should have specified the type of error you are getting !您应该已经指定了您遇到的错误类型! Anyways this should work..
无论如何这应该工作..
long r = Long.valueOf(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.