I'm using Session.save()
method (in Hibernate) to persist my entity objects which returns an object of type java.io.Serializable
.
The returned value is the generated primary key for the entity.
The generated primary key is of type long
(or bigint).
The question is that: How can I convert or cast the returned value to long
?
Serializable result = session.save(myEntityObject);
//This line of code fails.
long r = (long)result;
Using serialization, an object can be transferred across domains through firewalls, as well as be used for different languages and platforms. The formats of serialized objects are standardized so as to be able to be read by different platforms, if needed.
Data serialization is the process of converting an object into a stream of bytes to more easily save or transmit it. The reverse process—constructing a data structure or object from a series of bytes—is deserialization.
You don't always require serialization/deserialization. If you're sending an object over a network, then it gets serialized to send it via a byte stream. That's the point of serialization, precisely so that you CAN send via a network.
If the superclass is Serializable, then by default, every subclass is serializable. Hence, even though subclass doesn't implement Serializable interface( and if its superclass implements Serializable), then we can serialize subclass object.
Try casting the result (since it's not a primitive) to Long
instead of long
.
Long r = (Long)result;
long longValue = r.longValue();
Try
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 ...
Alternatively, cant you just call the primary key getter method on the object - I'd have hoped it would be set by that point.
HTH, Chris
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With