Published 2022-11-22

JPA Object To ResultSet

JPA Java Interaction. Get the data and its values without defining model class.

Amit Kumar Giri
                                
                                    JPA Java Interaction
/**
When you want to get the data without defining the model class
*/
try {
    Object[] value = (Object[]) em.createQuery("select id, name, joiningDate from Employee where id = :id")
                                  .setParameter("id", 100).getSingleResult();
    if (value != null && value.length == 3) {
        Integer empId = value[0];
        String empName = value[1];
        Date empJoinDate = value[2];
    }
} catch (NoResultException e) {
    // This exception will occur when no result is found in database. 
} catch (Exception ex) {
    // Catch any other exception
}