0

I have entity

@Entity
@Table(name = "TEST")
public class TEST implements Serializable {
   ...

    private String f1;
    private String f2;
    private String f3;
   ....

I need create select abd get only f1, f2 fields.

public Map<Stirng, String> getTestF1AndF2() {
Map<String, String> map = new HashMap<>();
        try { 
            Session mySession = HibernateUtil.getSessionFactory().openSession();
            Query q = mySession.createSQLQuery("SELECT f1, f2 from TEST");
            //???????????????
            //fill map 
            mySession.close();
            return map;
        } catch (Exception e) {
            LOG.log(Level.INFO, e.getMessage());
        }
        return null;
    }

I can use myBatis or another libs but I need use only hibernate. How can I reate this Mapping?

user5620472
  • 2,722
  • 8
  • 44
  • 97

1 Answers1

2

Use below HQL query to get the results as Map:

Query query = session.createQuery("select new map(f1 as f1, f2 as f2) from Test");
List<Map<String,String>> result = query.list();

Refer to this similar post:

How to fetch hibernate query result as associative array of list or hashmap

If you want to use SQL query then use this:

Query query1 = session.createSQLQuery("select sname as name, grp as grp from students").setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

List<Map<String,String>> result = query.list();

Note that the queries returns list of values, so result is List of Map elements in it.

Community
  • 1
  • 1
Chaitanya
  • 15,403
  • 35
  • 96
  • 137