dljd_056_hibernate_单表查询_命名查询

一、命名查询

package edu.aeon.hibernate.test;

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

import edu.aeon.aeonutils.hibernate.getsessionutil.GetSessionUtil;
import edu.aeon.beans.Student;
/**    
 * [说明]:命名查询
 * @author aeon
 *
 */
public class TestQuery {
    @Test
    public  void testQueryById() {
        Session session=null;
        Transaction transaction=null;
        try {
            session = GetSessionUtil.getSession();
            transaction=session.getTransaction();
            transaction.begin();
            Student student = (Student) session.getNamedQuery("queryStudentById").setInteger("stuid", 1).uniqueResult();
            System.out.println(student);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
            transaction.rollback();
        }finally {
            if(null!=session){
                session.close();
            }
        }
    }
}

  使用命名查询必须将sql语句配置到sql文件中、比如配置到Student.hbm.xml中,但是此处我将该sql抽取到了一个sqlMapping.xml文件中。然后注册到主配置文件(hibernate.cfg.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>
    <query name="queryStudentById">from Student where stuid=:stuid</query>
</hibernate-mapping>

数据库数据信息截图:

  

执行结果截图:

  

猜你喜欢

转载自www.cnblogs.com/aeon/p/10113823.html