1

I want to be able to create an object, assign a value, pass it to hibernate, and get back a fully populated object. I am using hibernate with annotations if that makes a difference. Example of what I would like to do:

Person person = new person();
person.setSin("135873546");

try (Session session = sessionFactory.openSession()) {
    session.beginTransaction();
    //this is what I don't want to have to do:
    //List<Person> result = session.createQuery("From Person where sin ='135873546'").list();

    //this is what I want to do:
    List<Person> result = session.get(person).list();
    Person firstPerson = result.get(0);

    System.out.println(firstSteve.getName());          // prints "Steve"
    System.out.println(firstSteve.getAge());           // prints "38"
    System.out.println(firstSteve.getGender());        // prints "Male"
    System.out.println(firstSteve.getMaritalStatus()); // prints "Single"
} catch (HibernateException e) {
    logger.error("Failed to retrieve object.", e);
    return new ArrayList<>();
}

Is this a feature that exists in hibernate or is there another library I could use? I've been going though some of the documentation and looked at a few tutorials but have not found an example of accessing data this way yet. Any help would be appreciated. Thanks.

edit: this is what I am currently doing...

/**
 * Retrieve and object from the database.
 *
 * @param <T>    the object type
 * @param clazz  the clazz
 * @param object the object
 * @return return the object
 */
public <T> List<T> retrieveObjectList(Class<T> clazz, T object) {
    String tableName = ((Entity) ReflectionUtils.getClassAnnotation(clazz, Entity.class)).name();
    Map<String, Object> importantFields = getFields(clazz, object);
    String queryString = buildQueryString(tableName, importantFields);

    try (Session session = DatabaseHelper.getSession()) {
        Query q = session.createQuery(queryString);
        setQueryParameters(q, importantFields);
        return q.getResultList();
    }catch (HibernateException e) {
        Util.logger.error("Failed to persist object.", e);
        return new ArrayList<>();
    }
}

/**
 * populate where clauses
 *
 * @param q the query
 * @param importantFields the where clauses
 */
private void setQueryParameters(Query q, Map<String, Object> importantFields) {
    for (Map.Entry<String, Object> field : importantFields.entrySet()) {
        //Integer must be converterted to double or Hibernate fails to properly identify it. I don't know why.
        q.setParameter(field.getKey(), (field.getValue() instanceof Integer)
                ? ((Integer) field.getValue()).doubleValue()
                : field.getValue());
    }
}

/**
 * Assemble query string
 *
 * @param tableName the name of the table taken from annotations
 * @param importantFields where clauses
 * @return the query
 */
private String buildQueryString(String tableName, Map<String, Object> importantFields) {
    StringBuilder queryString = new StringBuilder("FROM " + tableName + " ");
    Iterator<Map.Entry<String, Object>> iterator = importantFields.entrySet().iterator();

    for (int i=0; i<importantFields.size() ; i++) {
        Map.Entry<String, Object> next = iterator.next();
        queryString.append(i>0 ? " AND " : " WHERE ");
        queryString.append(String.format("%s = :%s ", next.getKey(), next.getKey()));
    }

    Util.logger.info("Composed query string:\n" + queryString + "\n");
    return queryString.toString();
}

/**
 * Get list of non-primitive fields
 *
 * @param clazz the class
 * @param object the object
 * @param <T> the type
 * @return the list of where clauses
 */
private <T> Map<String, Object> getFields(Class clazz, T object) {
    Map<String, Object> importantFields = new TreeMap<>();
    for (Field member : clazz.getDeclaredFields()) {
        try {
            member.setAccessible(true);
            Object val = member.get(object);
            if (!member.getType().isPrimitive() && val != null) {
                importantFields.put(member.getName(), val);
            }
        } catch (Exception e) {
            Util.logger.error("Failed to create query.", e);
        }
    }
    return importantFields;
}
maxl
  • 13
  • 5
  • credit - I found a lot of this in a comment on this thread http://stackoverflow.com/questions/14977018/jpa-how-to-get-entity-based-on-field-value-other-than-id – maxl Jan 23 '17 at 19:52
  • You should look into Hibernate criteria. – AHungerArtist Jan 23 '17 at 19:52
  • @AHungerArtist - unfortunately criteria doesn't work with generics from what I have been able to find. – maxl Jan 23 '17 at 19:53

1 Answers1

0

You can refer this tutorial, which uses session.get(class,id). You can also use Spring's HibernatreOperations get methods as well which is a wrapper around session.get method as mentioned in the document. Basically using HibernateTemplate as well.

Rohit Gulati
  • 542
  • 3
  • 15