注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

我的博客

 
 
 

日志

 
 
关于我

砍过人吸过粉站在路边接过吻 当过兵站过岗耍过流氓入过党 上过班下过岗打过领导得过奖

网易考拉推荐

MyEclipse+Hibernate 2--Operatation with database, query and list records  

2007-01-07 15:52:13|  分类: 网站设计 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

MyEclipse+Hibernate 2--Operatation with database, query and list records

Submitted by leelight on Tue, 2006-12-12 23:00.

Let's go over the project we have done. Open Package Explorer, the class and file structue is like this:
MyEclipse+Hibernate 2--Operatation with database, query and list records - 日月光明 - 我的博客
Open User.hbm.xml, this file  is the database mapping file of project, open it.

<hibernate-mapping>
    <class table="user" catalog="test">
        <id type="java.lang.Integer">
            <column />
            <generator />
        </id>
        <property type="java.lang.String">
            <column length="30" not-null="true" />
        </property>
        <property type="java.lang.String">
            <column length="30" />
        </property>
    </class>
</hibernate-mapping>

It has the same data structure in MySQL, id, username and password. Pay attention to the class and property name, which will be used in HQL(Hibernate Query Language  later, the class and property name wil be same with the name in MySQL database. But the class name has turn to user.User, so User not user will be used in HQL.

Now I will tried to list the records I have added before. Create new class name TestListRecord in package test.

package test;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import user.User;

public class TestListRecord {

    public static void main(String[] args) {
       
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
           Session session = sf.openSession();
       
        Transaction newTransaction = session.beginTransaction();
       
        //select u.id, u.username, u.password
        //from user u
        //order by u.id asc
        String query = "select u "
            + "from User as u order by u.id asc ";
       
        Query q = session.createQuery(query);
     
        List usersList = q.list();
       
        System.out.println( usersList.size() + " user(s) were found:" );

        for ( Iterator iter = usersList.iterator(); iter.hasNext(); ) {
           User user = (User) iter.next();
           //display the username
           System.out.println("usernames: "+user.getUsername() );
           //display the password
           System.out.println("password:" +user.getPassword());
        }
       
        newTransaction.commit();
        session.close();

    }

}

And if run successfully, the following results will be listed:

3 user(s) were found:
usernames: 1
password:1
usernames: 1
password:1
usernames: mway
password:mway

Now continue to list the records with which id is >1 by the usernames.
Just modify the HQL query:

 String query = "select u from "
            + "User as u where u.id>1 group by u.username ";

Results:

2 user(s) were found:
usernames: 1
password:1
usernames: mway
password:mway

If you want to select the username only, change the HQL, and the code:

        String query = "select u.username from "
            + "User as u where u.id>1 group by u.username ";
..............................
        for ( Iterator iter = usersList.iterator(); iter.hasNext(); ) {
               String username = (String) iter.next();
               //display the username
               System.out.println("usernames: "+username );
            }
.................................
Notice: Here
User user = (User) iter.next(); was not used, because we only query one column from database, the User Class is for the whole query: id, username,pasword
2 user(s) were found:
usernames: 1
usernames: mway

How to select more than 1 column but not all the columns? Easy:

        String query3 = "select u.username,u.password from "
            + "User as u where u.id>1 group by u.username ";
.......................
        for ( Iterator iter = usersList.iterator(); iter.hasNext(); ) {
//
Object can be used to transfer the data, and we know it's sequence
            Object[] rows = (Object[]) iter.next();
            String username = (String) rows[0];
            String password = (String) rows[1];
            System.out.println("name: " + username + " password: " + password);
            //display the username and password
            }
2 user(s) were found:
name: 1 password: 1
name: mway password: mway

And more, some functions can be used to perform the statistic task, the number of selected record and the avarage id will be count:

import java.util.ListIterator;


        String query = "select count(*),avg(u.id) from "

            + "User as u";

       ListIterator iter = usersList.listIterator();
      Object[] rows = (Object[]) iter.next();
      System.out.println("count: " + rows[0] + " avg: " + rows[1]);

count: 3 avg: 2.0

User Query Interface, we can  save some time not ererytime write the full HQL command, through setting the query parameters and setXXX() it later, for example

        String query5 = "select u.password from User as u " +
                "where u.id = ? and u.username = ?";

         Query q = session.createQuery(query5);   
         //the setXXX() must follow the order of parameters('?') that has been set
         q.setInteger(0, 3);
         q.setString(1, "mway");

        for (ListIterator iter = usersList.listIterator(); iter.hasNext(); ) {
            String password = (String) iter.next();
            System.out.println("password: " + password);
        }

1 user(s) were found:
password: mway

But we can use 'Named Parameter' instead of this way, the value can be set in the setXXX() according the parameter name, does not following the parameters' sequence. Fortunately, we have named those parameters before in User.hbm.xml:

        <property color="#ff6600">username" type="java.lang.String">
            <column length="30" not-null="true" />
        </property>
        <property color="#ff6600">password" type="java.lang.String">
            <column length="30" />
        </property>
        String query6 ="select u.password from User as u " +
                "where u.id = :id and u.username = :username";
       
        Query q = session.createQuery(query6);
       
        q.setInteger("id", 3);
        q.setString("username", "mway");

        for (ListIterator iter = usersList.listIterator(); iter.hasNext(); ) {
            String password = (String) iter.next();
            System.out.println("password: " + password);
        }

1 user(s) were found:
password: mway
Ref:
http://www.javaworld.com/javaworld/jw-10-2004/jw-1018-hibernate.html
http://www.javaworld.com.tw/confluence/pages/viewpage.action?pageId=1472
http://www.hibernate.org/hib_docs/reference/en/html/manipulatingdata.html
  评论这张
 
阅读(176)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2016