开发者

Java, convert(cast) Serializable objects to other objects

开发者 https://www.devze.com 2023-04-09 14:09 出处:网络
I\'m using Session.save() method (in Hibernate) to persist my entity objects which returns an object of type java.io.Serializable.

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 questio开发者_Go百科n 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;


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


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


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

long r = Long.valueOf(result) 


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

0

精彩评论

暂无评论...
验证码 换一张
取 消