简体   繁体   中英

Java hibernate select multiple rows from a table and assign the result in a list

I want to select multiple rows/records from a table, and then put the result into a "variable". Then I want to print each row's content.

If I use hibernate with Java, how can I do that?

For example, I have a student table and I want to get all the rows of the tables. I know each row is an instance of the table/entity class/bean. (assume I have an entity class-student )

The table is like (assume I have a table in database with data):

table name: sutdent

with four colums

id, lname, fname, sex

I remember I can do something like:

List<student> stlist=HibernateUtil.getSession().createQuery("select*from student").list();

//here I want to print the lname of the first row/object
System.out.println(stlist.get(0).getLname(););

Why I get error with message "unexpectesd token * " ?

I cannot use * ? if I cannot use *, if I want to get everything (all the attributes/columns) of a record, what can I do?

or is there any other error? what I should do? Thanks!!

You can do it by two ways.

1. HQL query
2. SQL query

1. HQL Query

- you are using hibernate that means you have done mapping to Student table and Student class.
 you just need to change following line.

List<student> stlist=HibernateUtil.getSession().createQuery("from student").list();

and you will get all records from Student table.

2. SQL Query

- you can do by providing SQL query

     List<Object> stlist=HibernateUtil.getSession().createSQLQuery("select * from student").list();

you will get all records as Object so you need to manually cast to Student.

In HQL, this is how you write a query to get the list of all objects:-

List<student> stlist = HibernateUtil.getSession().createQuery("select s from student s").list();

or even this is allowed, if you want to fetch all the columns.

List<student> stlist = HibernateUtil.getSession().createQuery("from student s").list();

In above so many examples are placed. That are some correct just simply you can follow this one. I think this one is good for your requirement.

First you can open the session:

Session session = HibernateUtil.getSessionFactory().openSession();

If you already opened session in util, you can follow this one:

Session session = HibernateUtil.getCurrentSession();

If you want to fetch the records from a database table try this simple query:

List<Object> slist = session.createQuery("from Student").list();

Here Hibernate Query Language (HQL) removes the burden on the programmer. No need to write the entire query here.

Here you can remember one thing. The first letter of the table name must be a capital letter otherwise sometimes an exception will be raised.

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