zoukankan      html  css  js  c++  java
  • hibernate入门---Hibernate查询方式(for循环、构造器、对象数组等)【第三天,相当于总结整合】

    Hibernate查询方式【内连接和外连接不在此篇】

    本文讲述的是HQL以及各种情况输出对象的for循环以及构造器的例子,当然这是Hibernate结合一起完成的任务。技术上,离开一些方法,不掌握一些基本的方法,灵活使用,是会带来诸多不便的。

    查询方式都在例子里的方法里,我把全部都写在了一个类里,基本思路:

    类:Customer->CustomerManager->Demo

    配置文件:hibernate.cfg.xml->Customer.hbm.xml

    关系:

    (我们不去考虑什么session啊之类的内部机制,单纯的从自己写的类和配置文件来进行初步理解,深入机制前面已有/也可查阅资料了解更多)

     

    下面直接贴例子,自行体会(因为之前的文章基本总结过了,当然这个例子还是能够看出一些思想的):

    一、配置文件:(你没有看错,还是那个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>
    <!-- 配置文件标签顺序property*,mapping*,(class-cache|collection-cache),event,listener* -->
        <session-factory>
          <!-- 设置访问mysql数据库的驱动描述 -->
          <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
          <!-- 设置数据库的url -->
          <property name="connection.url">jdbc:mysql://127.0.0.1:3306/test</property>
          <!-- 指定登录数据库用户账户 -->
          <property name="connection.username">root</property>
          <!-- 指定登录数据库用户密码 -->
          <property name="connection.password">123456</property>
          
          <!-- 设置访问数据库的方言,提高数据库访问性能 -->
          <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
          <!-- 设置ddl -->
          <!-- <property name="hbm2ddl.auto">auto</property> -->
           <!-- 配置控制台视图,显示查询内容 -->
           <property name="show_sql">true</property>
           <!-- 下面是多表映射 -->
          <!-- 指出映射文件 -->
          <mapping resource="resource/Customer.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>

     二、还是配置文件【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 package="bean" auto-import="false">
       <!-- POJO类映射表及某表的关系-->
       <class name="bean.Customer" table="customers" catalog="test">
           <id name="customerID" type="java.lang.String">
               <column name="customerID" length="8"/>
               <generator class="assigned"></generator>
           </id>
           <!-- 映射表中name字段 -->
           <property name="name" type="java.lang.String">
              <column name="name" length="40"/>
           </property>
           <!-- 映射表中phone字段 -->
           <property name="phone" type="java.lang.String">
              <column name="phone" length="16"/>
           </property>  
       </class>
    </hibernate-mapping>

    三、映射数据库的类:

    package bean;
    
    public class Customer {
        private String customerID,name,phone;
        
        public String getCustomerID() {
            return customerID;
        }
    
        public void setCustomerID(String customerID) {
            this.customerID = customerID;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPhone() {
            return phone;
        }
    
        public void setPhone(String phone) {
            this.phone = phone;
        }
    }

    四、会话工厂类:

    package hibernate.factory;
    
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    
    public class HibernateSessionFactory {
        private static String configfile = "resource/hibernate.cfg.xml";
        /**ThreadLocal是一个本地线程**/
        private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
        private static Configuration config;
        private static SessionFactory sessionFactory;
        /**读取配置文件,创建一个工厂会话,这段代码为静态块,编译后已经运行**/
        static{
            try {
                config = new Configuration().configure(configfile);
                sessionFactory = config.buildSessionFactory();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        /**通过会话工厂打开会话,就可以访问数据库了**/
        public static Session getSession(){
            Session session = (Session)threadLocal.get();
            if (session==null||!session.isOpen()) {
                if (sessionFactory==null) {
                    rebuildSessionFactory();
                }
                session = (sessionFactory!=null)?sessionFactory.openSession():null;
            }
            return session;
        }
        /**重新创建一个会话工厂**/
        public static void rebuildSessionFactory() {
            try {
                config.configure(configfile);
                sessionFactory = config.buildSessionFactory();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        /**关闭与数据库的会话**/
        public static void closeSession() {
            Session session = (Session)threadLocal.get();
            threadLocal.set(null);
            if (session!=null) {
                session.close();
            }
        }
    }

    五、查询Customer的类:

    package bean.dao;
    
    import java.util.List;
    
    import hibernate.factory.HibernateSessionFactory;
    
    import org.hibernate.Session;
    import org.hibernate.query.Query;
    
    import bean.Customer;
    
    
    
    
    //针对各类查询的单表查询
    public class CustomerManager {
        //各类查询方式
        /**
         * @see 限制查询结果记录数与起始记录
         * @return list
         */
        @SuppressWarnings("rawtypes")
        public List selLimitCustomerScore(){
            Session session = HibernateSessionFactory.getSession();
            Query query = session.createQuery("from bean.Customer");
            //即从第三条记录开始查询,并且只查询两条记录
            query.setFirstResult(2);
            query.setMaxResults(2);
            List list = query.list();
            return list;
        }
        /**
         * @see 通过条件查询,起别名
         * @return list
         */
        @SuppressWarnings("rawtypes")
        public List selConditionCustomer(){
            Session session = HibernateSessionFactory.getSession();
            Query query = session.createQuery("from bean.Customer cus where cus.name='we'");
            List list = query.list();
            return list;
        }
        /**
         * @see 取表中部分列,单一属性查询,还是返回一个集合,不过集合中存储的不是表的实例,而是实例的对象<br/>在使用时:<br/>
         for(int i=0;i&lt;list.size;i++){
         String name = (String)list.get(i);
         System.out.println(name);
         }
         * @return list
         *
         */
        public List selOneCustomer(){
            Session session = HibernateSessionFactory.getSession();
            return session.createQuery("from bean.Customer cus where cus.name='we'").list();
        }
        /**
         * @see 多个属性的查询,使用对象数组
         */
        @SuppressWarnings("null")
        public List selMoreCustomer() {
            Session session = HibernateSessionFactory.getSession();
            List customers = session.createQuery("select name,phone from bean.Customer").list();
            return customers;
        }
        /**
         * @see 多个属性查询,使用集合装“部分”列。
         * @return list
         */
        public List selListCustomer() {
            Session session = HibernateSessionFactory.getSession();
            List list = session.createQuery("select new list(cus.name,cus.phone) from bean.Customer cus").list();
            return list;
        }
        /**
         * @see 使用map集合装部分列
         * @return map
         * 
         */
        public List selMapCustomer() {
            Session session = HibernateSessionFactory.getSession();
            List list = session.createQuery("select new map(cus.name,cus.phone) from bean.Customer cus").list();
            return list;
        }
    }

    六、测试类:

    package demo;
    
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    
    import bean.Customer;
    import bean.dao.CustomerManager;
    
    //根据以下查询,基本上变化的是查询的for里面转化上有区别,而与之关联的管理查询类,变化上就是Query的对象设置以及HQL语句的变化,然后查询的时候根据需要使用for。
    public class Demo {
        @SuppressWarnings("unchecked")
        public static void main(String[] args) {
            CustomerManager manager = new CustomerManager();
            //测试条件查询的方法,同时理解foreach的用法
            List<Customer> lists = manager.selConditionCustomer();
            System.out.println("---------分界线,selConditionCustomer()以下是条件查询--------");
            for (Customer customer : lists) {
                System.out.println(customer.getName()+customer.getPhone());
            }
            System.out.println("---------分界线,selLimitCustomerScore()以下是测试限制查询结果与起始记录数--------");
            //测试限制查询结果记录数与起始记录
            List<Customer> customers = manager.selLimitCustomerScore();
            for (Customer customer : customers) {
                System.err.println(customer.getName()+customer.getPhone());
            }
            System.out.println("--------------分界线,selListCustomer()集合装部分列--------------------");
            List lists2 = manager.selListCustomer();//集合部装,没有使用到Customer
            for (int i = 0; i < lists2.size(); i++) {
                List temp = (List)lists2.get(i);
                System.out.println(temp.get(0)+"  "+temp.get(1));//0是索引,集合部装,根据索引,打印该索引对应的那一列全部记录
            }
            System.out.println("--------------分界线,selMapCustomer()集合部装列--------------------");
            List list =manager.selMapCustomer();
            for (int i = 0; i < list.size(); i++) {
                Map tmp = (Map)list.get(i);
                System.out.println(tmp.get("0")+" "+tmp.get("1"));//0是key,1是key,2也是key,以此类推,其实与java对象查询相关,HQL里:new map(cus.name,cus.phone),表示只查询key为0和1两个值
            }
            System.out.println("--------------分界线,selOneCustomer(),查询单个属性--------------------");
            List cnames = manager.selOneCustomer();
            for(int i=0;i<cnames.size();i++){ 
                Customer customer = (Customer)cnames.get(i); 
                System.out.println(customer.getName()); 
            }
            System.out.println("--------------分界线,selMoreCustomer()多个属性的查询,使用对象数组--------------------");
            List list2 = manager.selMoreCustomer();
            for (int i = 0; i < list2.size(); i++) {
                Object[] obj = (Object[])list2.get(i);//多个属性的查询,使用对象数组,指这里开始
                System.out.println(obj[0]+","+obj[1]);
            }
        }
    }

    记录这些例子,更好的是为后续纠错等能够快速定位,也同时使自己记忆深刻。理解。

    既然闲着,那就“闲着”。

  • 相关阅读:
    dotnet 控制台读写 Sqlite 提示 no such table 找不到文件
    dotnet 控制台读写 Sqlite 提示 no such table 找不到文件
    dotnet 控制台 Hangfire 后台定时任务
    dotnet 控制台 Hangfire 后台定时任务
    dotnet 获取指定进程的输入命令行
    dotnet 获取指定进程的输入命令行
    PHP sqrt() 函数
    PHP sinh() 函数
    PHP sin() 函数
    PHP round() 函数
  • 原文地址:https://www.cnblogs.com/ciscolee/p/10954535.html
Copyright © 2011-2022 走看看