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];
        }
}

Leave a Comment

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 )

Facebook photo

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

Connecting to %s