Presentation of Hibernate query results

Source: Internet
Author: User

We use hibernate (hereinafter referred to as h) to manage the association between database tables. The basic principle is actually very simple, that is, to transfer the association between tables in the database to the class of the Entity bean, after the configuration, h can help us maintain this association. This indeed brings great convenience. We can use hql in our program to obtain or store data in an object-oriented manner. For example, we used to query the information of the students in a class, if you write an SQL statement by yourself, you need to associate two tables and manually extract the queried data one by one, and then encapsulate it into our bean to display the word in jsp. This process is very cumbersome. With h, we don't need to explicitly write this association in SQL. We chose to write this association to the h ing file, so that h will help us maintain this relationship, when we need to query the student information in the Class, we only need to use hql: from Class as c where c. id =: id; then you can get the object of a specific class (assuming c), and Set <Student> students = c. getStudents (); you can get all the students in the class. There are no join operations and other related operations throughout the process, so we can ignore this association because h has helped us maintain it.

As we know above, Hibernate maintains the relationship through object inclusion, so when we need to query the associated object, we first get the primary object through Hibernate, call the get X of the primary object to obtain the associated object. Then, you can obtain the associated information and assemble the data to display it in jsp. We can simply write it as: hql = "select new map (c. id as id, c. name as name, c. students [0]. name as studentname) from Class as c where c. id =: id "; this completes Data Query and assembly at the same time. Assemble the queried data into a map. The as is followed by the map key, and the map value is the queried data. This data assembly mode ratio:

While(It. hasNext ()){
10Object [] tuple = (Object []) it. next ();
11Members members = (Members) tuple [0];
12String className = (String) tuple [1];

It is much simpler.

Of course, we can also define our own entity classes to accommodate the queried data:

Selectnew NewMembers (members, classInfo. className) "+
3"From Members members, ClassInfo classInfo" +
4"Where members. level = classInfo. classCode"

You can also use the hibernateapi function setResultTransformer to store the query results in our custom bo object:

String sql = "select u.userName as userName ,p.title as title ,p.addTime as addTime from user as u,post as p where"
Query q = factory.getCurrentSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(PostVO.class));
About data assembly, There are many methods, not all.
We will discuss how to use h when it involves complex queries for three or more tables.
We know that it is enough to use the method described above when two or more tables exist. However, for complex queries associated with more than three tables, we need to compare the two methods:
One way is to still hand over the table relationship to h for management through the configuration ing file, so that we not only need to configure multiple relationships in the configuration file, in addition, the associated attributes must be added to the corresponding object class. After the primary object is obtained during the query, its attributes are called multiple times to obtain the information of the associated table. This is not the case, however, it is complicated. If you do not pay attention to it, errors may occur.
If you want to query more than five tables, we recommend that you use native SQL to directly execute SQL statements. The association between tables is directly indicated in the SQL statement, do not use h for management. In this way, the h configuration is missing, and the entity classes corresponding to each table are not required. This saves a lot of trouble, note the following when using native SQL:
  Session s = sessionFactory.openSession();           String sql="select book.bookname,borr.borrowTime,borr.backTime,pub.pubname,  bookcasename,book.price from "+"(select * from tb_borrow where ifback=0) "+"as borr left join tb_bookinfo book on join tb_publishing pub "+"on book.isbn=pub.isbn join tb_bookcase bs "+" on join tb_reader r on where r.barcode=?";  Query query=s.createSQLQuery(sql).addScalar("bookname", Hibernate.STRING) .addScalar("borrowTime", Hibernate.STRING).  addScalar("backTime", Hibernate.STRING).addScalar("pubname", Hibernate.STRING).  addScalar("bookcasename", Hibernate.STRING).addScalar("price", Hibernate.STRING);     query.setParameter(0, barCode);   List list=null;      try{    list=query.list();   s.close(); }  catch (Exception e)  {      e.printStackTrace();  }return list;
1. Session session = sessionFactory. openSession (); session. createSQLQuery (SQL); query object query is obtained in this way.
List = query. list ();The result is an array list (ArrayList), Where each element in the list is an array of the object type, representing a record of the query result, that is, h will queryEach field is forcibly converted to the Object type, and then a number group is formed into the list..
3. Simple use
S. createSQLQuery (SQL) often reports the "column not found" error. In fact, this is why h supports native SQL, becauseHibernate uses ResultSetMetadata to determine the actual sequence and type of returned scalar values,If a specified type is not mapped or is not the expected type, the above error occurs.AddScalar () explicitly specifies the returned column and the type of each column to avoid the above errors..
It is best to convert the object to the actual type based on the actual type to obtain the information stored in these types.
  • 1
  • 2
  • 3
  • 4
  • Next Page

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.