Determining the primary key value of an entity bean using reflection

Given some Entity Object or generic type T, it may be useful to determine the value of the primary key without knowing the object type.

First, it’s necessary to determine the primary key property name.

This tutorial uses Hibernate.

This tutorial uses standard Reflection.

Once the name has been determined, the apache commons BeanUtils library can be used to obtain the value.

http://commons.apache.org/beanutils/

Determine the value as so:

(This assumes the primary key is a  Long value )

Ensure the apache commons BeanUtils library is in the class path.