6

Table Players:

ID | name  | email | age | ...
1  | 'bob' | null  | 23  | ...

This table is where instances of class Player are persisted (one row per instance, no composition etc.).

Having a Hibernate Session, how do I get the row (say with id - the PK - equal to 1) as a Java Map (key = column name, value = cell value) ?

Example usage:

Map<String,String> row = getPlayerByIdAsMap(1);

3 Answers 3

7

Use a query with AliasToEntityMapResultTransformer; is verbose but should works with Hibernate property definition and not with JavaBean definition (they can differ).

Map<String,Object> aliasToValueMap = 
    session.createCriteria(User.class)
      .add(Restrictions.idEq(userID))
      .setProjection(Projections.projectionList()
        .add(Projections.id().as("id"))
        // Add others properties
      )
      .setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE)
    .uniqueResult();

A worse approch can be write a custom ResultTransformer that introspect ClassMetadata and try to extract values...

class IntrospectClassMetadata extends BasicTransformerAdapter {
  PassThroughResultTransformer rt = PassThroughResultTransformer.INSTANCE;
  public Object transformTuple(Object[] tuple, String[] aliases) {
    final Object o = rt.transformTuple(tuple, aliases);
    ClassMetadata cm = sf.getClassMetadata(o.getClass());
    List<String> pns = new ArrayList<String>(Arrays.asList(cm.getPropertyNames()));
    Map<String, Object> m = new HashMap<String, Object>();
    for(String pn : pns) {
      m.put(pn, cm.getPropertyValue(o, pn));
    }
    m.put(cm.getIdentifierPropertyName(), cm.getIdentifier(o));
    return m;
  }
}

and use

Map<String,Object> aliasToValueMap = 
        session.createCriteria(User.class)
          .add(Restrictions.idEq(userID))
          .setResultTransformer(new IntrospectClassMetadata())
        .uniqueResult();

Last chance:

Map<String,Object> map = (Map<String,Object>)s.createSQLQuery("select * from user where id = :id")
  .setParameter("id",p.id)
  .setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE)
.uniqueResult();

but this doesn't map list,bags and other mapped object, but only raw column names and values...

Sign up to request clarification or add additional context in comments.

8 Comments

This would return a Map? Could you complete the example with a couple of keystrokes so it's cristal-clear how to use?
do you know if the opposite is possible, i.e. save a Map to a table? See stackoverflow.com/questions/21904041/… please
I'd love to accept your answer but the way it's right now it returns a Map<String, Player> rather than List<Map<String,Object>>.. and the key to that map is this, lol.
I'm sorry to tell you you need to specify a projections :/ or a custom (but a not-so-safe custom ResultTransformer)
God, this is terrible. I have ca. 50 columns.. Why is this so ridiculously complicated to read a row as a map ...
|
2

You can use HQL and do a query for selecting the result as a new Map

select new Map(p.id as ID, p.name as name, p.email as email, p.age as age)
from Player p

It will return you a collection of maps, being each one of the maps a row in the query result.

3 Comments

Cool, can you tell Hibernate to map all columns or do you have to list them all? I mean, I have 50 columns..
Unfortunatelly no. You'll have to specify every element of the map.
So I think @bellabax solution will be better for you.
0

You can use BeanUtils and do something like this:

User user = (User) session.get(User.class, userID);
Map map = BeanUtils.describe(user);

3 Comments

Yeah I thought about it, but describe adds the class property and reports nested objects as .. objects (I use @Embedded on them) and not as a set of their properties.
Do you need exactly a Map? I guess JSONObject can do some recursive transformation into a json format, then you can access it more or less like a Map of Maps
The other answers look more Hibernate-specific and quite more interesting though :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.