Ali Khoshsirat
Ali Khoshsirat

Reputation: 103

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.

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;

Upvotes: 6

Views: 21613

Answers (6)

H-net
H-net

Reputation: 31

Above answer not worked for me.

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.

If the Entity has a composite key you should pass the entity itself (with filled pk) as second argument.

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).

Upvotes: 0

Chris Kimpton
Chris Kimpton

Reputation: 5541

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

Upvotes: 1

Rakesh
Rakesh

Reputation: 4334

You should have specified the type of error you are getting ! Anyways this should work..

long r = Long.valueOf(result) 

Upvotes: 0

James DW
James DW

Reputation: 1815

Try

long r = Long.valueOf(String.valueOf(result)).longValue();

Upvotes: 3

Xavi López
Xavi López

Reputation: 27880

Try using long r = ((Long) result).getLong() instead.

Upvotes: 0

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Try casting the result (since it's not a primitive) to Long instead of long.

Long r = (Long)result;
long longValue = r.longValue();

Upvotes: 8

Related Questions