Hibernate基础学习笔记(四)

w# 一.主要内容
Hibernate的各种查询
Hibernate的查询优化
Hibernate小练习

二.基本环境配置

基本结构

这里写图片描述

Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- 必须的配置 -->
        <!-- 配置数据库的基本信息 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///hibernatedemo02</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>

        <!-- 配置方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- 配置可选参数 -->
        <!-- 显示SQL语句 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 格式化SQL语句 -->
        <property name="hibernate.format_sql">true</property>
        <!-- 自动更新表,可以根据映射文件自动创建表 -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- 设置数据库的隔离级别,就使用默认值就OK -->
        <property name="hibernate.connection.isolation">4</property>

        <!-- 开启绑定本地的session -->
        <property name="hibernate.current_session_context_class">thread</property>

        <!-- 加载映射文件 -->
        <mapping resource="com/fjut/entity/Customer.hbm.xml"/>
        <mapping resource="com/fjut/entity/Linkman.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Customer类

public class Customer implements Serializable{

    private Long cust_id;
    private String cust_name;
    private Long cust_user_id;

    private Long cust_create_id;
    private String cust_source;
    private String cust_industry;

    private String cust_level;
    private String cust_linkman;
    private String cust_phone;
    private String cust_mobile;
    private Set<Linkman> linkmans = new HashSet<Linkman>();

    public Customer() {

    }

    public Customer(Long cust_id, String cust_name, Long cust_user_id, Long cust_create_id, String cust_source,
            String cust_industry, String cust_level, String cust_linkman, String cust_phone, String cust_mobile) {
        this.cust_id = cust_id;
        this.cust_name = cust_name;
        this.cust_user_id = cust_user_id;
        this.cust_create_id = cust_create_id;
        this.cust_source = cust_source;
        this.cust_industry = cust_industry;
        this.cust_level = cust_level;
        this.cust_linkman = cust_linkman;
        this.cust_phone = cust_phone;
        this.cust_mobile = cust_mobile;
    }

    public Long getCust_id() {
        return cust_id;
    }
    public void setCust_id(Long cust_id) {
        this.cust_id = cust_id;
    }
    public String getCust_name() {
        return cust_name;
    }
    public void setCust_name(String cust_name) {
        this.cust_name = cust_name;
    }
    public Long getCust_user_id() {
        return cust_user_id;
    }
    public void setCust_user_id(Long cust_user_id) {
        this.cust_user_id = cust_user_id;
    }
    public Long getCust_create_id() {
        return cust_create_id;
    }
    public void setCust_create_id(Long cust_create_id) {
        this.cust_create_id = cust_create_id;
    }
    public String getCust_source() {
        return cust_source;
    }
    public void setCust_source(String cust_source) {
        this.cust_source = cust_source;
    }
    public String getCust_industry() {
        return cust_industry;
    }
    public void setCust_industry(String cust_industry) {
        this.cust_industry = cust_industry;
    }
    public String getCust_level() {
        return cust_level;
    }
    public void setCust_level(String cust_level) {
        this.cust_level = cust_level;
    }
    public String getCust_linkman() {
        return cust_linkman;
    }
    public void setCust_linkman(String cust_linkman) {
        this.cust_linkman = cust_linkman;
    }
    public String getCust_phone() {
        return cust_phone;
    }
    public void setCust_phone(String cust_phone) {
        this.cust_phone = cust_phone;
    }
    public String getCust_mobile() {
        return cust_mobile;
    }
    public void setCust_mobile(String cust_mobile) {
        this.cust_mobile = cust_mobile;
    }
    public Set<Linkman> getLinkmans() {
        return linkmans;
    }

    public void setLinkmans(Set<Linkman> linkmans) {
        this.linkmans = linkmans;
    }

    @Override
    public String toString() {
        return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + ", cust_user_id=" + cust_user_id
                + ", cust_create_id=" + cust_create_id + ", cust_source=" + cust_source + ", cust_industry="
                + cust_industry + ", cust_level=" + cust_level + ", cust_linkman=" + cust_linkman + ", cust_phone="
                + cust_phone + ", cust_mobile=" + cust_mobile + "]";
    }

}

Customer.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.fjut.entity.Customer" table="cst_customer">
        <id name="cust_id" column="cust_id">
            <!-- 设置id自增 -->
            <generator class="native"></generator>
        </id>
        <property name="cust_name" column="cust_name" />
        <property name="cust_user_id" column="cust_user_id" />
        <property name="cust_create_id" column="cust_create_id" />
        <property name="cust_source" column="cust_source" />
        <property name="cust_industry" column="cust_industry" />
        <property name="cust_level" column="cust_level" />
        <property name="cust_linkman" column="cust_linkman" />
        <property name="cust_phone" column="cust_phone" />
        <property name="cust_mobile" column="cust_mobile" />

        <set name="linkmans" inverse="true">
            <key column="lkm_cust_id"></key>
            <one-to-many class="com.fjut.entity.Linkman"/>
        </set>
    </class>
</hibernate-mapping>

Linkman类

public class Linkman implements Serializable{
    private Long lkm_id;
    private String lkm_name;
    private String lkm_gender;
    private String lkm_phone;
    private String lkm_mobile;
    private String lkm_email;
    private String lkm_qq;
    private String lkm_position;
    private String lkm_memo;

    private Customer customer;

    public Linkman() {

    }

    public Linkman(Long lkm_id, String lkm_name, String lkm_gender, String lkm_phone, String lkm_mobile,
            String lkm_email, String lkm_qq, String lkm_position, String lkm_memo, Customer customer) {
        super();
        this.lkm_id = lkm_id;
        this.lkm_name = lkm_name;
        this.lkm_gender = lkm_gender;
        this.lkm_phone = lkm_phone;
        this.lkm_mobile = lkm_mobile;
        this.lkm_email = lkm_email;
        this.lkm_qq = lkm_qq;
        this.lkm_position = lkm_position;
        this.lkm_memo = lkm_memo;
        this.customer = customer;
    }

    public Long getLkm_id() {
        return lkm_id;
    }

    public void setLkm_id(Long lkm_id) {
        this.lkm_id = lkm_id;
    }

    public String getLkm_name() {
        return lkm_name;
    }

    public void setLkm_name(String lkm_name) {
        this.lkm_name = lkm_name;
    }

    public String getLkm_gender() {
        return lkm_gender;
    }

    public void setLkm_gender(String lkm_gender) {
        this.lkm_gender = lkm_gender;
    }

    public String getLkm_phone() {
        return lkm_phone;
    }

    public void setLkm_phone(String lkm_phone) {
        this.lkm_phone = lkm_phone;
    }

    public String getLkm_mobile() {
        return lkm_mobile;
    }

    public void setLkm_mobile(String lkm_mobile) {
        this.lkm_mobile = lkm_mobile;
    }

    public String getLkm_email() {
        return lkm_email;
    }

    public void setLkm_email(String lkm_email) {
        this.lkm_email = lkm_email;
    }

    public String getLkm_qq() {
        return lkm_qq;
    }

    public void setLkm_qq(String lkm_qq) {
        this.lkm_qq = lkm_qq;
    }

    public String getLkm_position() {
        return lkm_position;
    }

    public void setLkm_position(String lkm_position) {
        this.lkm_position = lkm_position;
    }

    public String getLkm_memo() {
        return lkm_memo;
    }

    public void setLkm_memo(String lkm_memo) {
        this.lkm_memo = lkm_memo;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    @Override
    public String toString() {
        return "Linkman [lkm_id=" + lkm_id + ", lkm_name=" + lkm_name + ", lkm_gender=" + lkm_gender + ", lkm_phone="
                + lkm_phone + ", lkm_mobile=" + lkm_mobile + ", lkm_email=" + lkm_email + ", lkm_qq=" + lkm_qq
                + ", lkm_position=" + lkm_position + ", lkm_memo=" + lkm_memo + "]";
    }



}

Linkman.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.fjut.entity.Linkman" table="cst_linkman">
        <id name="lkm_id" column="lkm_id">
            <generator class="native" />
        </id>
        <property name="lkm_name" column="lkm_name" />
        <property name="lkm_gender" column="lkm_gender" />
        <property name="lkm_phone" column="lkm_phone" />
        <property name="lkm_mobile" column="lkm_mobile" />
        <property name="lkm_email" column="lkm_email" />
        <property name="lkm_qq" column="lkm_qq" />
        <property name="lkm_position" column="lkm_position" />
        <property name="lkm_memo" column="lkm_memo" />

        <many-to-one name="customer" class="com.fjut.entity.Customer" column="lkm_cust_id" cascade="save-update"/>
    </class>
</hibernate-mapping>

SessionUtils工具类

/**
 * Session获取工具类
 * @author LGX
 *
 */
public class SessionUtils {
    private static final Configuration CONFIG;
    private static final SessionFactory FACTORY;


    static {
        CONFIG = new Configuration().configure();//加载hibernate.cfg.xml 配置文件
        FACTORY = CONFIG.buildSessionFactory(); //创建SessionFactory
    }


    /**
     * 获取Session,绑定本地Session
     * @return
     */
    public static Session getCurrentSession() {
        return FACTORY.getCurrentSession();
    }
}

三.Hibernate 的查询方式

Hibernate中提供了5种检索方式
1.OID检索

2.对象导航检索

3.HQL检索

4.QBC检索

5.SQL检索

OID检索

session.get(对象.class,OID)

例子:

    /**
     * 1.OID检索
     */
    @Test
    public void test01() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        Customer c = session.get(Customer.class, 1L);
        System.out.println(c);

        tr.commit();
    }

结果:

Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_0_,
        customer0_.cust_name as cust_nam2_0_0_,
        customer0_.cust_user_id as cust_use3_0_0_,
        customer0_.cust_create_id as cust_cre4_0_0_,
        customer0_.cust_source as cust_sou5_0_0_,
        customer0_.cust_industry as cust_ind6_0_0_,
        customer0_.cust_level as cust_lev7_0_0_,
        customer0_.cust_linkman as cust_lin8_0_0_,
        customer0_.cust_phone as cust_pho9_0_0_,
        customer0_.cust_mobile as cust_mo10_0_0_ 
    from
        cst_customer customer0_ 
    where
        customer0_.cust_id=?
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

对象导航检索

简单来说就是用查询出来的对象进行下次查询

例子:

    /**
     * 2.对象导航检索 
     */
    @Test
    public void test02() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        Customer c = session.get(Customer.class, 1L);
        System.out.println("=========================");
        System.out.println(c.getLinkmans().size());

        tr.commit();
    }

结果:

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_0_,
        customer0_.cust_name as cust_nam2_0_0_,
        customer0_.cust_user_id as cust_use3_0_0_,
        customer0_.cust_create_id as cust_cre4_0_0_,
        customer0_.cust_source as cust_sou5_0_0_,
        customer0_.cust_industry as cust_ind6_0_0_,
        customer0_.cust_level as cust_lev7_0_0_,
        customer0_.cust_linkman as cust_lin8_0_0_,
        customer0_.cust_phone as cust_pho9_0_0_,
        customer0_.cust_mobile as cust_mo10_0_0_ 
    from
        cst_customer customer0_ 
    where
        customer0_.cust_id=?
=========================
Hibernate: 
    select
        linkmans0_.lkm_cust_id as lkm_cus10_1_0_,
        linkmans0_.lkm_id as lkm_id1_1_0_,
        linkmans0_.lkm_id as lkm_id1_1_1_,
        linkmans0_.lkm_name as lkm_name2_1_1_,
        linkmans0_.lkm_gender as lkm_gend3_1_1_,
        linkmans0_.lkm_phone as lkm_phon4_1_1_,
        linkmans0_.lkm_mobile as lkm_mobi5_1_1_,
        linkmans0_.lkm_email as lkm_emai6_1_1_,
        linkmans0_.lkm_qq as lkm_qq7_1_1_,
        linkmans0_.lkm_position as lkm_posi8_1_1_,
        linkmans0_.lkm_memo as lkm_memo9_1_1_,
        linkmans0_.lkm_cust_id as lkm_cus10_1_1_ 
    from
        cst_linkman linkmans0_ 
    where
        linkmans0_.lkm_cust_id=?
3

HQL的检索方式

1.基本的查询格式

例子:

    /**
     * HQL检索
     * 基本的查询格式
     */
    @Test
    public void test03() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        Query query = session.createQuery("from Customer");
        List<Customer> list = query.list();
        for (Customer customer : list) {
            System.out.println(customer);
        }

        tr.commit();
    }

结果:

Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_,
        customer0_.cust_name as cust_nam2_0_,
        customer0_.cust_user_id as cust_use3_0_,
        customer0_.cust_create_id as cust_cre4_0_,
        customer0_.cust_source as cust_sou5_0_,
        customer0_.cust_industry as cust_ind6_0_,
        customer0_.cust_level as cust_lev7_0_,
        customer0_.cust_linkman as cust_lin8_0_,
        customer0_.cust_phone as cust_pho9_0_,
        customer0_.cust_mobile as cust_mo10_0_ 
    from
        cst_customer customer0_
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=2, cust_name=zhangsan2, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=3, cust_name=lisi, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=4, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

2.使用别名

例子:

    /**
     * HQL检索
     * 起别名
     */
    @Test
    public void test04() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();
        Query query = session.createQuery("select c from Customer c");
        List<Customer> list = query.list();
        for (Customer customer : list) {
            System.out.println(customer);
        }
        tr.commit();
    }

结果:

Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_,
        customer0_.cust_name as cust_nam2_0_,
        customer0_.cust_user_id as cust_use3_0_,
        customer0_.cust_create_id as cust_cre4_0_,
        customer0_.cust_source as cust_sou5_0_,
        customer0_.cust_industry as cust_ind6_0_,
        customer0_.cust_level as cust_lev7_0_,
        customer0_.cust_linkman as cust_lin8_0_,
        customer0_.cust_phone as cust_pho9_0_,
        customer0_.cust_mobile as cust_mo10_0_ 
    from
        cst_customer customer0_
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=2, cust_name=zhangsan2, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=3, cust_name=lisi, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=4, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

3.排序查询

例子:

    /**
     * HQL检索
     * 排序查询
     */
    @Test
    public void test05() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();
        Query query = session.createQuery("select c from Customer c order by c.cust_id desc");
        List<Customer> list = query.list();
        for (Customer customer : list) {
            System.out.println(customer);
        }
        tr.commit();
    }

结果:

Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_,
        customer0_.cust_name as cust_nam2_0_,
        customer0_.cust_user_id as cust_use3_0_,
        customer0_.cust_create_id as cust_cre4_0_,
        customer0_.cust_source as cust_sou5_0_,
        customer0_.cust_industry as cust_ind6_0_,
        customer0_.cust_level as cust_lev7_0_,
        customer0_.cust_linkman as cust_lin8_0_,
        customer0_.cust_phone as cust_pho9_0_,
        customer0_.cust_mobile as cust_mo10_0_ 
    from
        cst_customer customer0_ 
    order by
        customer0_.cust_id desc
Customer [cust_id=4, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=3, cust_name=lisi, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=2, cust_name=zhangsan2, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

4.分页查询

例子:

    /**
     * HQL检索
     * 分页查询
     */
    @Test
    public void test06() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();
        Query query = session.createQuery("from Customer");

        query.setFirstResult(0);//从第一条记录开始
        query.setMaxResults(2);//最大查询两条

        List<Customer> list = query.list();
        for (Customer customer : list) {
            System.out.println(customer);
        }
        tr.commit();
    }

结果:

Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_,
        customer0_.cust_name as cust_nam2_0_,
        customer0_.cust_user_id as cust_use3_0_,
        customer0_.cust_create_id as cust_cre4_0_,
        customer0_.cust_source as cust_sou5_0_,
        customer0_.cust_industry as cust_ind6_0_,
        customer0_.cust_level as cust_lev7_0_,
        customer0_.cust_linkman as cust_lin8_0_,
        customer0_.cust_phone as cust_pho9_0_,
        customer0_.cust_mobile as cust_mo10_0_ 
    from
        cst_customer customer0_ limit ?
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=2, cust_name=zhangsan2, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

5.带条件的查询

例子:

    /**
     * HQL检索
     * 带条件的查询
     */
    @Test
    public void test07() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        //使用?作为占位符
        Query query = session.createQuery("from Customer where cust_id = ?");
        query.setParameter(0, 1L);

        List<Customer> list = query.list();
        for (Customer customer : list) {
            System.out.println(customer);
        }

        System.out.println("================================================");

        //使用字符串作为占位符
        Query query2 = session.createQuery("from Customer where cust_id = :id");
        query2.setParameter("id", 3L);

        List<Customer> list2 = query2.list();
        for (Customer customer : list2) {
            System.out.println(customer);
        }

        tr.commit();
    }

结果:

Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_,
        customer0_.cust_name as cust_nam2_0_,
        customer0_.cust_user_id as cust_use3_0_,
        customer0_.cust_create_id as cust_cre4_0_,
        customer0_.cust_source as cust_sou5_0_,
        customer0_.cust_industry as cust_ind6_0_,
        customer0_.cust_level as cust_lev7_0_,
        customer0_.cust_linkman as cust_lin8_0_,
        customer0_.cust_phone as cust_pho9_0_,
        customer0_.cust_mobile as cust_mo10_0_ 
    from
        cst_customer customer0_ 
    where
        customer0_.cust_id=?
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
================================================
Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_,
        customer0_.cust_name as cust_nam2_0_,
        customer0_.cust_user_id as cust_use3_0_,
        customer0_.cust_create_id as cust_cre4_0_,
        customer0_.cust_source as cust_sou5_0_,
        customer0_.cust_industry as cust_ind6_0_,
        customer0_.cust_level as cust_lev7_0_,
        customer0_.cust_linkman as cust_lin8_0_,
        customer0_.cust_phone as cust_pho9_0_,
        customer0_.cust_mobile as cust_mo10_0_ 
    from
        cst_customer customer0_ 
    where
        customer0_.cust_id=?
Customer [cust_id=3, cust_name=lisi, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

6.投影查询

投影查询返回的是一个Object数组
可以使用fetch迫切查询

1)普通查询

例子:

    /**
     * HQL检索
     * 投影查询
     */
    @Test
    public void test08() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        //使用?作为占位符
        Query query = session.createQuery("select cust_id,cust_name from Customer");
        List<Object[]> list = query.list();
        for (Object[] objects : list) {
            for (Object object : objects) {
                System.out.print(object + " ");
            }
            System.out.println();
        }
        tr.commit();
    }   

结果:

Hibernate: 
    select
        customer0_.cust_id as col_0_0_,
        customer0_.cust_name as col_1_0_ 
    from
        cst_customer customer0_
1 zhangsan 
2 zhangsan2 
3 lisi 
4 zhangsan 

2)可以将查询结果封装到对象中

HQL:select new Customer(cust_id,cust_name) from Customer

例子:

    /**
     * HQL检索
     * 投影查询
     * 注:使用封装对象的方法首先要提供对应的构造函数
        public Customer(Long cust_id, String cust_name) {
            this.cust_id = cust_id;
            this.cust_name = cust_name;
        }
     */
    @Test
    public void test08() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        Query query = session.createQuery("select new Customer(cust_id,cust_name) from Customer");
        List<Customer> list = query.list();
        for (Customer customer : list) {
            System.out.println(customer);
        }
        tr.commit();
    }   

结果:

Hibernate: 
    select
        customer0_.cust_id as col_0_0_,
        customer0_.cust_name as col_1_0_ 
    from
        cst_customer customer0_
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=2, cust_name=zhangsan2, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=3, cust_name=lisi, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=4, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

3)聚合函数查询

可以使用SQL语法内的聚合函数,但是不同的是Hibernate 内不能使用 * 来代替所有
例如:
SQL: select count(*) from cust
HQL: select count(cust_id) from cust 要用具体属性

例子:

    /**
     * HQL检索
     * 投影查询
     * 聚合函数的使用
     */
    @Test
    public void test09() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        Query query = session.createQuery("select count(cust_id) from Customer");
        List<Number> list = query.list();
        System.out.println(list.get(0).intValue());
        tr.commit();
    }   

结果:

Hibernate: 
    select
        count(customer0_.cust_id) as col_0_0_ 
    from
        cst_customer customer0_
4

QBC的检索方式

简单的查询

    /**
     * QBC查询
     */
    @SuppressWarnings("all")
    @Test
    public void test10() {
        //1.创建Session
        Session session = SessionUtils.getCurrentSession();
        //2.开启事务
        Transaction tr = session.beginTransaction();
        //3.创建criteria
        Criteria criteria = session.createCriteria(Customer.class);
        List<Customer> lisy = criteria.list();
        for (Customer customer : lisy) {
            System.out.println(customer);
        }
        tr.commit();
    }   

结果:

Hibernate: 
    select
        this_.cust_id as cust_id1_0_0_,
        this_.cust_name as cust_nam2_0_0_,
        this_.cust_user_id as cust_use3_0_0_,
        this_.cust_create_id as cust_cre4_0_0_,
        this_.cust_source as cust_sou5_0_0_,
        this_.cust_industry as cust_ind6_0_0_,
        this_.cust_level as cust_lev7_0_0_,
        this_.cust_linkman as cust_lin8_0_0_,
        this_.cust_phone as cust_pho9_0_0_,
        this_.cust_mobile as cust_mo10_0_0_ 
    from
        cst_customer this_
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=2, cust_name=zhangsan2, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=3, cust_name=lisi, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=4, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

条件查询

这里写图片描述

    @SuppressWarnings("all")
    @Test
    public void test11() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        Criteria criteria = session.createCriteria(Customer.class);
        //查找Id等于1的人
        criteria.add(Restrictions.eq("cust_id", 1L));
        List<Customer> list = criteria.list();
        for (Customer customer : list) {
            System.out.println(customer);
        }
        tr.commit();
    }

结果:

Hibernate: 
    select
        this_.cust_id as cust_id1_0_0_,
        this_.cust_name as cust_nam2_0_0_,
        this_.cust_user_id as cust_use3_0_0_,
        this_.cust_create_id as cust_cre4_0_0_,
        this_.cust_source as cust_sou5_0_0_,
        this_.cust_industry as cust_ind6_0_0_,
        this_.cust_level as cust_lev7_0_0_,
        this_.cust_linkman as cust_lin8_0_0_,
        this_.cust_phone as cust_pho9_0_0_,
        this_.cust_mobile as cust_mo10_0_0_ 
    from
        cst_customer this_ 
    where
        this_.cust_id=?
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

例子2:

    @SuppressWarnings("all")
    @Test
    public void test11() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        Criteria criteria = session.createCriteria(Customer.class);
        //查找名字中含有z的人
        criteria.add(Restrictions.ilike("cust_name", "%z%"));
        List<Customer> list = criteria.list();
        for (Customer customer : list) {
            System.out.println(customer);
        }
        tr.commit();
    }

结果:

Hibernate: 
    select
        this_.cust_id as cust_id1_0_0_,
        this_.cust_name as cust_nam2_0_0_,
        this_.cust_user_id as cust_use3_0_0_,
        this_.cust_create_id as cust_cre4_0_0_,
        this_.cust_source as cust_sou5_0_0_,
        this_.cust_industry as cust_ind6_0_0_,
        this_.cust_level as cust_lev7_0_0_,
        this_.cust_linkman as cust_lin8_0_0_,
        this_.cust_phone as cust_pho9_0_0_,
        this_.cust_mobile as cust_mo10_0_0_ 
    from
        cst_customer this_ 
    where
        lower(this_.cust_name) like ?
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=2, cust_name=zhangsan2, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=4, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

分页查询

    //设置开始查询位置
    criteria.setFirstResult(0);
    //设置最大查询长度
    criteria.setMaxResults(2);

例子:

    @SuppressWarnings("all")
    @Test
    public void test11() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        Criteria criteria = session.createCriteria(Customer.class);
        //设置开始查询位置
        criteria.setFirstResult(0);
        //设置最大查询长度
        criteria.setMaxResults(2);
        List<Customer> list = criteria.list();

        for (Customer customer : list) {
            System.out.println(customer);
        }
        tr.commit();
    }

结果:

Hibernate: 
    select
        this_.cust_id as cust_id1_0_0_,
        this_.cust_name as cust_nam2_0_0_,
        this_.cust_user_id as cust_use3_0_0_,
        this_.cust_create_id as cust_cre4_0_0_,
        this_.cust_source as cust_sou5_0_0_,
        this_.cust_industry as cust_ind6_0_0_,
        this_.cust_level as cust_lev7_0_0_,
        this_.cust_linkman as cust_lin8_0_0_,
        this_.cust_phone as cust_pho9_0_0_,
        this_.cust_mobile as cust_mo10_0_0_ 
    from
        cst_customer this_ limit ?
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=2, cust_name=zhangsan2, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

排序查询

criteria.addOrder(Order.desc(“cust_id”));

例子:

    @SuppressWarnings("all")
    @Test
    public void test11() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        Criteria criteria = session.createCriteria(Customer.class);

        //按照cust_id 降序
        criteria.addOrder(Order.desc("cust_id"));
        List<Customer> list = criteria.list();

        for (Customer customer : list) {
            System.out.println(customer);
        }
        tr.commit();
    }

结果:

Hibernate: 
    select
        this_.cust_id as cust_id1_0_0_,
        this_.cust_name as cust_nam2_0_0_,
        this_.cust_user_id as cust_use3_0_0_,
        this_.cust_create_id as cust_cre4_0_0_,
        this_.cust_source as cust_sou5_0_0_,
        this_.cust_industry as cust_ind6_0_0_,
        this_.cust_level as cust_lev7_0_0_,
        this_.cust_linkman as cust_lin8_0_0_,
        this_.cust_phone as cust_pho9_0_0_,
        this_.cust_mobile as cust_mo10_0_0_ 
    from
        cst_customer this_ 
    order by
        this_.cust_id desc
Customer [cust_id=4, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=3, cust_name=lisi, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=2, cust_name=zhangsan2, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]
Customer [cust_id=1, cust_name=zhangsan, cust_user_id=null, cust_create_id=null, cust_source=null, cust_industry=null, cust_level=null, cust_linkman=null, cust_phone=null, cust_mobile=null]

聚合查询

QBC的聚合函数查询,使用setProjection尽行聚合查询
criteria.setProjection(Projections.max(“cust_id”));

例子:

    @SuppressWarnings("all")
    @Test
    public void test11() {
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        Criteria criteria = session.createCriteria(Customer.class);
        //查询最大的id值
        criteria.setProjection(Projections.max("cust_id"));

        List<Number> list = criteria.list();
        System.out.println(list.get(0).intValue());
        tr.commit();
    }

结果:

Hibernate: 
    select
        max(this_.cust_id) as y0_ 
    from
        cst_customer this_
4

离线查询

离线条件查询使用的是DetachedCriteria接口进行查询,离线条件查询对象在创建的时候,不需要使用Session对象,只是在查询的时候使用Session对象即可
例子:

    @Test
    public void test12() {
        //1.获得离线条件查询的对象
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);

        //2.添加查询条件
        detachedCriteria.add(Restrictions.eq("cust_id", 1L));

        //3.获取session
        Session session = SessionUtils.getCurrentSession();
        Transaction tr = session.beginTransaction();

        //4.获取criteria对象
        Criteria criteria = detachedCriteria.getExecutableCriteria(session);

        //5.执行
        List<Customer> list = criteria.list();

        for (Customer customer : list) {
            System.out.println(customer);
        }
        tr.commit();        
    }

多表查询

SQL检索方式

四.Hibernate的查询策略

猜你喜欢

转载自blog.csdn.net/l1336037686/article/details/80291162