HQL语句--from(检索对象)

来源:互联网 发布:java版手机软件下载 编辑:程序博客网 时间:2024/05/23 23:41

from字句:HQL语句最简形式。from指定了HQL语句查询的主体–持久化类及其属性。

from子句中持久化类的引用
1、不需要引入持久化类的全限定名,直接引入类名即可。eg:from Seller
2、auto-import(自动引入)缺省情况

from子句中别名的应用
1、为被查询的类指定别名,使用AS关键字来设定别名(也可省略)。
2、定义别名的目的是,在HQL语句其他部分通过别名引用该类。
3、别名命名习惯,建议别名与持久化类名相同。eg:from Seller,Seller别名可为:seller或单字母s。
4、别名使用最多场景,是在from子句后设置多个持久化类。
eg:from Seller s,Customer c


检索单实体:

package com.model;import java.nio.channels.SeekableByteChannel;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.junit.After;import org.junit.Before;import org.junit.Test;import com.util.HibernateSessionFactory;public class CustomeriTest {    private Session session=null;  //会话实例变量    @Test    public void testFromClause(){ //测试from字句        //定义HQL查询语句,查询单实体        String hql="from Customer as customer";  //注意:Customer是类名,不是表名,要区分大小写,也可写为from com.model.Customer持久化类的全限定名        Query query=session.createQuery(hql); //定义query对象        List<Customer> customers=query.list(); //查询        for (Customer customer : customers) {            System.out.println("name:"+customer.getName());        }    }    @Before    public void setUp() throws Exception {        session=HibernateSessionFactory.getCurrentSession();    }    @After    public void tearDown() throws Exception {        session.close();    }}

控制台:
这里写图片描述
检索两个有主外键关联的实体:

package com.model;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.junit.After;import org.junit.Before;import org.junit.Test;import com.util.HibernateSessionFactory;public class CommodityTest {    private Session session=null;    @Test    public void testFromClause(){  //测试from字句        String hql="from Commodity"; //查询Commodity及其外键关联的Seller(即两个有关联的实体)        Query query=session.createQuery(hql);        List<Commodity> commodities=query.list();        for (Commodity commodity : commodities) {            System.out.println("name"+commodity.getName()); //商品名称            //查询外键关联的Seller            System.out.println("seller's name:"+commodity.getSeller().getName());//所属商家名称        }    }    @Before    public void setUp() throws Exception {        session=HibernateSessionFactory.getCurrentSession();    }    @After    public void tearDown() throws Exception {        session.close();    }}

控制台(部分):
这里写图片描述

0 0
原创粉丝点击