hibernate-命名查询

命名查询语句是在映射文件中定义字符串形 式的查询语句

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="entity.Emp" table="EMP" schema="RENT" >
        <id name="empno" type="java.lang.Short">
            <column name="EMPNO" precision="4" scale="0" />
            <generator class="assigned" />
        </id>
        <!-- 一方有多方的对象 --><!--inverse=false默认false,是关联关系的主动方  -->
        <many-to-one name="dept" class="entity.Dept" fetch="select" >
            <column name="DEPTNO" precision="2" scale="0" />
        </many-to-one>
        <property name="ename" type="java.lang.String">
            <column name="ENAME" length="10" />
        </property>
        <property name="job" type="java.lang.String">
            <column name="JOB" length="9" />
        </property>
        <property name="mgr" type="java.lang.Short">
            <column name="MGR" precision="4" scale="0" />
        </property>
        <property name="hiredate" type="java.util.Date">
            <column name="HIREDATE" length="7" />
        </property>
        <property name="sal" type="java.lang.Double">
            <column name="SAL" precision="7" />
        </property>
        <property name="comm" type="java.lang.Double">
            <column name="COMM" precision="7" />
        </property>
    </class>
    <query name="findEmpByJob">
    <![CDATA[
        from Emp e where e.job = :job
    ]]>
    </query>
    <!-- <sql-query name="selectEmpByJob">
        <return alias="e" class="entity2.Emp"/>
        select {e.*} from EMP e where e.job = :job
    </sql-query>
    <sql-query name="selectEmpByJobJoinDept">
        <return alias="e" class="entity2.Emp"/>
        <return-join alias="d" property="e.dept"></return-join>
            select {e.*},{d.*} from EMP e join DEPT d on d.DEPTNO=e.DEPTNO where e.JOB = :job
    </sql-query> -->
</hibernate-mapping>
package Test;

import static org.junit.Assert.*;

import java.util.List;

import org.hibernate.Session;
import org.junit.Test;

import entity.Emp;

import util.HibernateSessionFactory;

public class NamedQuery {

    @Test
    public void test() {
        Session session=HibernateSessionFactory.getSession();
        try {
            List<Emp> list = session.getNamedQuery("findEmpByJob").setParameter("job", "SALESMAN").list();
            for (Emp emp : list) {
                System.out.println(emp.getEname()+"\t"+emp.getDept().getDname());
            }
        } catch (Exception e) {
            e.printStackTrace();
            
        }finally{
            session.close();
        }
        
    }

}

 

posted @ 2016-11-06 20:10  sincoolvip  阅读(1088)  评论(0编辑  收藏  举报