HQL动态,分页查询及关联查询多对一单向

来源:互联网 发布:汽车电气设计软件 编辑:程序博客网 时间:2024/06/09 23:41

            Threadlocal:保证线程变量

            Threadlocal 保证  openSession( )从Connection Pool取到的连接是与当前线程绑定的,因此Threadlocal有两个方法。

            一个是get( ):从线程中获取对象        set( ):给线程变量赋值/设置值

            Threadlocal类为每一个线程都维护了自己独有的变量贝。每一个线程都拥有自己独立的一个变量

            执行HQL的几个步骤: (1)获取Session对象    (2)编写HQL语句    (3)创建Query对象   (4)执行查询,得到查询结果

            HQL投影查询是查询一个持久化类的一个或多个属性值。

            将每条查询结果通过构造函数封成对象

            将每条查询结果封装成Object对象/数组.

            分页:    setFirstResult( )设置从第几条记录开始显示

                           setMaxResult( )每页显示几条记录

        创建Emp实体类并写上属性值 ,将其进行封装            

    private Integer empno;    private String ename;    private String job;    private Integer mgr;//经理    private Date hiredate;    private Integer sal;    private Integer comm;    private Integer deptno;
   创建Empter类,写属性将其进行封装  
    private String job;    private Integer sal;    private Date fromhiredate;    private Date endhiredate;  
    书写小配置,映射文件Emp.hbm.xml
<?xml version="1.0"?>        <!DOCTYPE hibernate-mapping PUBLIC                "-//Hibernate/Hibernate Mapping DTD 3.0//EN"                "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.happy.Hqldongtai"><class name="Emp" table="Emp" schema="scott">    <id name="empno" column="empno">        <generator class="native"></generator>    </id>    <property name="ename"/>    <property name="job"/>    <property name="mgr"/>    <property name="hiredate"/>    <property name="sal"/>    <property name="comm"/>    <property name="deptno"/></class></hibernate-mapping>  
  测试类:
    Configuration cfg;    Session session;    Transaction tx;    SessionFactory factory;    @Before    public void MyBefor(){        //创建配置对象        cfg=new Configuration().configure();        //根据配置对象创建SessionFactory        factory=cfg.buildSessionFactory();        //根据SessionFactory去创建Session        session=factory.openSession();        //在session创建后开启事务        tx=session.beginTransaction();    }
//实现动态查询
@Test
    public void selectDynameimSelect() throws ParseException {   
    String  hql="from Emp where 1=1";    
    Empter cond=new Empter();     
    cond.setSal(1000);     
    cond.setJob("CLERK");  
    SimpleDateFormat  sdf=new SimpleDateFormat("yyyy-mm-dd");    
    Date  dordate=sdf.parse("1981-04-01");     
    cond.setFromhiredate(dordate);    
    Date  todate=sdf.parse("1985-09-09");    
    cond.setEndhiredate(todate);     
    StringBuffer buffer=new StringBuffer(hql);   
     if(cond.getJob()!=null){   
         buffer.append(" and job=:job");   
     }    
    if(cond.getSal()!=null){     
       buffer.append(" and sal>:sal");   
     }    
    if(cond.getFromhiredate()!=null){   
         buffer.append(" and hiredate>=:fromhiredate");   
     }     
   if(cond.getEndhiredate()!=null){  
          buffer.append(" and hiredate<=:endhiredate");  
      }   
     Query query=session.createQuery(buffer.toString());    
    query.setProperties(cond);   
     List<Emp> list=query.list();  
      for (Emp emp:list) {   
         System.out.println(emp.getEname());  
      }    }
---------------------------------------------------
//查询4-6的记录数  分页查询@Testpublic  void  selectPageList(){    String  hql="from Emp order by empno";    Query query=session.createQuery(hql);    int pageIndex=2;    int pageSize=3;    query.setFirstResult((pageIndex-1)*pageSize); //启示记录数 0 2   3 5   6 8    query.setMaxResults(pageSize);    List<Emp> list=query.list();    for (Emp emp:list) {        System.out.println(emp.getEname());    }}
-----------------------关联,多对一单向查询---------------------------------------
先创建Dept实体类,写上属性并将其进行封装:

    private Integer pid;
    private String pname;
   然后创建Emp实体类,写上属性并将其进行封装 
   private Integer eid;   private String ename;   private Dapt dapt=new Dapt();
  书写小配置,映射文件
    Dept.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.happy.liancha">    <class name="Dapt" table="Dapt" schema="happyy2165">        <id name="pid" column="pid">            <generator class="native"></generator>        </id>        <property name="pname"/>    </class></hibernate-mapping>
Emp.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.happy.liancha">    <class name="Emp" table="Emp" schema="happyy2165">        <id name="eid" column="eid">            <generator class="native"></generator>        </id>        <property name="ename"/>        <!--多对一-->        <many-to-one name="dapt" column="pid" class="Dapt"></many-to-one>    </class></hibernate-mapping>
 测试类:
 Configuration cfg;    Session session;    Transaction tx;    SessionFactory factory;    @Before    public void MyBefor(){        //创建配置对象        cfg=new Configuration().configure();        //根据配置对象创建SessionFactory        factory=cfg.buildSessionFactory();        //根据SessionFactory去创建Session        session=factory.openSession();        //在session创建后开启事务        tx=session.beginTransaction();    }    //关联查询,多对一单向@Test    public void testManyOneSingle(){        //提供一个员工的编号        Emp emp=session.get(Emp.class,1);        System.out.println(emp.getEname());        //隶属的部门        System.out.println(emp.getDapt().getPname());    }
大配置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="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>    <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>    <property name="connection.username">happyy2165</property>    <property name="connection.password">happyy2165</property>    <!-- SQL dialect SQL方言 -->    <property name="dialect">  org.hibernate.dialect.Oracle10gDialect</property>    <!-- Enable Hibernate's automatic session context management session和当前线程绑定-->    <property name="current_session_context_class">thread</property>    <!--打印sql 控制台-->    <property name="show_sql">true</property>    <!--格式化SQL-->    <property name="format_sql">true</property>    <!--自动构建表结构   create 先delete表结构 再创建,update直接更新表结构-->    <property name="hbm2ddl.auto">update</property>   <!-- <mapping resource="cn/happy/entity/Dept.hbm.xml"/>-->  <!--  <mapping resource="cn/happy/Hqldongtai/Emp.hbm.xml"/>-->     <!--关联 多对一-->  <!--  <mapping resource="cn/happy/liancha/Emp.hbm.xml"/>    <mapping resource="cn/happy/liancha/Dapt.hbm.xml"/>-->    <mapping resource="cn/happy/first/fir.hbm.xml"/></session-factory></hibernate-configuration>  
--------------------util工具类-------------------------  
public class HibernateUtil {   private  static ThreadLocal<Session> tl;   private static Configuration cfg;   private static SessionFactory factory;   static {       tl=new ThreadLocal<Session>();       cfg=new Configuration().configure();       factory=cfg.buildSessionFactory();   }   public static Session getSession(){       //尝试从线程查看有没有线程变量       Session session=tl.get();       if(session==null){           //线程中没有session对象,创建一个           session=factory.openSession();           tl.set(session);       }       return session; //没有和当前线程绑定   }    public static void closeSession(){        Session session = tl.get();        tl.set(null);        session.close();    }}

原创粉丝点击