简体   繁体   中英

How to retrieve database table value in hibernate?

I am new to the Hibernate, i want to retrieve table values from database, I have a code but it returns object values. My sample code is,

Configuration conf=new Configuration();
    @SuppressWarnings("deprecation")
    SessionFactory sessionfactory=conf.configure().buildSessionFactory();

    Session session=sessionfactory.openSession();
    List maintable = null;
    try
    {
        org.hibernate.Transaction tx = session.beginTransaction();
        Query q = session.createQuery ("select main.empid,main.address from Main as main");
         maintable =q.list();
         Object[] obj=maintable.toArray();

          for(int i=0;i<obj.length;i++)
          {
              System.out.println("column valuse : "+obj[i]);

          }

    tx.commit();
    session.close();

    }
    catch(Exception e1)
    {
        System.out.println("Exception");
    }

I need to get multiple column values...How can i do that?

I can retrieve value from list easily.But in my above question i print only object property not a value.

Query qry=session.createQuery("from Main");
    List<Main> user=(List<Main>) qry.list();
    session.getTransaction().commit();

    session.close();
    for(Main u : user)
    {
        System.out.println("User id : "+u.getEmpid());
        System.out.println("User Address:"+u.getAddress());
    }

This is what Hibernate (or JPA rather) is meant for. If you want to access regular values, use JDBC instead.

select main.empid,main.address from Main as main

please check that empid,address are the column name in the database or the property name of Main class.

It should be the property name of entity(ie Main) class.

It's very useful when we retrieve some fields/properties from our entity class. The above query with “new” keyword can return a list of type “Main”. If we do not use such a keyword and specify the fields directly, a list of type Object [ ] is retrieved.

select new Main(main.empid,main.address) from Main as main ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM