Spring EntityManager createNativeQuery return Object[]

Scenario: You are lazy and don’t want to create an @Entity class and just want to query a few columns.

@PersistenceContext(unitName="dev")
EntityManager entityManager;

@SuppressWarnings("unchecked")
public List<Object[]> retrieveCustomerInfo(){
		try {
			return entityManager.createNativeQuery("select name, age from Customer").getResultList();
		} catch (Exception e) {
			logger.error("Customer Query Exception", e);
		}
		return null;
} 

public void invokeCustomerEndpointWithInfo(List<Object[]> customerInfo){
	Iterator<Object[]> it = customerInfo.iterator( );
        while (it.hasNext( )) {
			Object[] result = (Object[])it.next();
			String name = (String) result[0];
			Integer age = (Integer) result[1];
        }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: