吴裕雄--天生自然轻量级JAVA EE企业应用开发Struts2Sping4Hibernate整合开发学习笔记:Hibernate_native_sql

<?xml version="1.0" encoding="GBK"?>
<project name="hibernate" basedir="." default="">
    <property name="src" value="src"/>
    <property name="dest" value="classes"/>

    <path id="classpath">
        <fileset dir="../../lib">
            <include name="**/*.jar"/>
        </fileset>
        <pathelement path="${dest}"/>
    </path>

    <target name="compile" description="Compile all source code">
        <delete dir="${dest}"/>
        <mkdir dir="${dest}"/>
        <copy todir="${dest}">
            <fileset dir="${src}">
                <exclude name="**/*.java"/>
            </fileset>        
        </copy>
        <javac destdir="${dest}" debug="true" includeantruntime="yes"
            deprecation="false" optimize="false" failonerror="true">
            <src path="${src}"/>
            <classpath refid="classpath"/>
            <compilerarg value="-Xlint:deprecation"/>
        </javac>
    </target>

    <target name="run" description="Run the main class" depends="compile">
        <java classname="lee.NativeSQLTest" fork="yes" failonerror="true">
            <classpath refid="classpath"/>
        </java>
    </target>

</project>
drop database if exists hibernate;

create database hibernate;

use hibernate;

CREATE TABLE course_inf (
  course_code varchar(255) NOT NULL,
  name varchar(255) default NULL,
  PRIMARY KEY  (course_code)
);

INSERT INTO course_inf VALUES 
('001','疯狂Java讲义'),
('002','轻量级Java EE企业应用实战'),
('003','疯狂Android讲义');

CREATE TABLE student_inf (
  student_id int NOT NULL,
  name varchar(255) NOT NULL,
  PRIMARY KEY  (student_id)
);

INSERT INTO student_inf VALUES
(20050231,'孙悟空'),
(20050232,'猪八戒'),
(20050233,'牛魔王');



CREATE TABLE enrolment_inf (
  enrolment_id int(11) NOT NULL auto_increment,
  semester int(11) NOT NULL,
  year int(11) NOT NULL,
  student_id int default NULL,
  course_code varchar(255) default NULL,
  PRIMARY KEY  (enrolment_id),
  KEY FKEB4882C47EDE09EE (course_code),
  KEY FKEB4882C4109881D8 (student_id),
  FOREIGN KEY (student_id) REFERENCES student_inf (student_id),
  FOREIGN KEY (course_code) REFERENCES course_inf (course_code)
);

INSERT INTO enrolment_inf VALUES
(1,3,2005,20050232,'001'),
(2,2,2005,20050232,'003'),
(3,2,2005,20050233,'002'),
(4,3,2005,20050233,'003'),
(5,1,2005,20050231,'002');
<?xml version="1.0" encoding="GBK"?>
<!-- 指定Hibernate配置文件的DTD信息 -->
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- hibernate-configuration是配置文件的根元素 -->
<hibernate-configuration>
    <session-factory>
        <!-- 指定连接数据库所用的驱动 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
        <!-- 指定连接数据库的用户名 -->
        <property name="connection.username">root</property>
        <!-- 指定连接数据库的密码 -->
        <property name="connection.password">32147</property>
        <!-- 指定连接池里最大连接数 -->
        <property name="hibernate.c3p0.max_size">20</property>
        <!-- 指定连接池里最小连接数 -->
        <property name="hibernate.c3p0.min_size">1</property>
        <!-- 指定连接池里连接的超时时长 -->
        <property name="hibernate.c3p0.timeout">5000</property>
        <!-- 指定连接池里最大缓存多少个Statement对象 -->
        <property name="hibernate.c3p0.max_statements">100</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        <property name="hibernate.c3p0.acquire_increment">2</property>
        <property name="hibernate.c3p0.validate">true</property>
        <!-- 指定数据库方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <!-- 根据需要自动创建数据库 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 显示Hibernate持久化操作所生成的SQL -->
        <property name="show_sql">true</property>
        <!-- 将SQL脚本进行格式化后再输出 -->
        <property name="hibernate.format_sql">true</property>
        <!-- 罗列所有持久化类的类名 -->
        <mapping class="org.crazyit.app.domain.Enrolment"/>
        <mapping class="org.crazyit.app.domain.Student"/>
        <mapping class="org.crazyit.app.domain.Course"/>
    </session-factory>
</hibernate-configuration>
package lee;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
public class HibernateUtil
{
    public static final SessionFactory sessionFactory;

    static
    {
        try
        {
            // 使用默认的hibernate.cfg.xml配置文件创建Configuration实例
            Configuration cfg = new Configuration()
                .configure();
            // 以Configuration实例来创建SessionFactory实例
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).build();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        }
        catch (Throwable ex)
        {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    // ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
    public static final ThreadLocal<Session> session
        = new ThreadLocal<Session>();

    public static Session currentSession()
        throws HibernateException
    {
        Session s = session.get();
        // 如果该线程还没有Session,则创建一个新的Session
        if (s == null)
        {
            s = sessionFactory.openSession();
            // 将获得的Session变量存储在ThreadLocal变量session里
            session.set(s);
        }
        return s;
    }

    public static void closeSession()
        throws HibernateException
    {
        Session s = session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}
package lee;

import org.hibernate.*;
import org.hibernate.transform.*;
import org.hibernate.type.*;

import java.util.*;

import org.crazyit.app.domain.*;
import org.crazyit.app.vo.*;

/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
public class NativeSQLTest
{
    public static void main(String[] args)
    {
        NativeSQLTest test = new NativeSQLTest();
//        test.scalarQuery();
//        test.entityQuery();
//        test.multiEntityQuery();
        test.beanQuery();
//        test.joinQuery();
        HibernateUtil.sessionFactory.close();
    }
    // 执行标量查询
    public void scalarQuery()
    {
        // 打开Session和事务
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        String sqlString = "select stu.* from student_inf as stu";
        List list = session.createSQLQuery(sqlString)
            // 指定查询name和student_id两个数据列
            .addScalar("name" , StandardBasicTypes.STRING)
            .addScalar("student_id" , StandardBasicTypes.INTEGER)
            // 返回标量值列表
            .list();
        for (Object ele : list)
        {
            // 每个集合元素都是一个数组,数组元素是name、student_id两列值
            Object[] row = (Object[])ele;
            System.out.println(row[0] + "	" + row[1]);
        }
        tx.commit();
        HibernateUtil.closeSession();
    }

    // 执行实体SQL查询
    public void entityQuery()
    {
        // 打开Session和事务
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        String sqlString = "select * from enrolment_inf where year=?1";
        List list = session.createSQLQuery(sqlString)
            // 指定将查询的记录行转换成Student实体
            .addEntity(Enrolment.class)
            // 为SQL字符串的参数设置值
            .setInteger("1" , 2005)
            .list();
        for (Object ele : list)
        {
            // 每个集合元素都是一个Enrolment对象
            Enrolment e = (Enrolment)ele;
            System.out.println(e.getStudent().getName()
                + "	" + e.getCourse().getName());
        }
        tx.commit();
        HibernateUtil.closeSession();
    }

    // 执行返回多个实体的SQL查询
    public void multiEntityQuery()
    {
        // 打开Session和事务
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        String sqlString = "select s.*,e.*,c.* "
            + "from student_inf s,enrolment_inf e,course_inf c "
            + "where s.student_id = e.student_id "
            + "and e.course_code = c.course_code";
        List list = session.createSQLQuery(sqlString)
            // 指定将从s表查询得到的记录行转换成Student实体
            .addEntity("s", Student.class)
            // 指定将从e表查询得到的记录行转换成Enrolment实体
            .addEntity("e", Enrolment.class)
            // 指定将从c表查询得到的记录行转换成Course实体
            .addEntity("c", Course.class)
            .list();
        // 提交事务,关闭Session
        tx.commit();
        HibernateUtil.closeSession();
        // 因为数据已经全部被选出,故程序可以遍历列表中的数据
        for (Object ele : list)
        {
            // 每个集合元素都是Student、Enrolment
            // 和Course所组成的数组
            Object[] objs = (Object[])ele;
            Student s = (Student)objs[0];
            Enrolment e = (Enrolment)objs[1];
            Course c = (Course)objs[2];
            System.out.println(s.getName() + "	"
                + e.getYear() + "	" + e.getSemester()
                + "	" + c.getName());
        }
    }

    // 执行返回普通JavaBean的SQL查询
    public void beanQuery()
    {
        // 打开Session和事务
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        String sqlString = "select s.name stuName, c.name courseName "
            + "from student_inf s,enrolment_inf e,course_inf c "
            + "where s.student_id = e.student_id "
            + "and e.course_code = c.course_code ";
        List list = session.createSQLQuery(sqlString)
            // 指定将查询的记录行转换成StudentCourse对象
            .setResultTransformer(Transformers
                .aliasToBean(StudentCourse.class))
            .list();
        // 提交事务,关闭Session
        tx.commit();
        HibernateUtil.closeSession();
        // 因为数据已经全部被选出,故程序可以遍历列表中的数据
        for (Object ele : list)
        {
            // 每个集合元素都是StudentCourse对象
            StudentCourse sc = (StudentCourse)ele;
            System.out.println(sc.getStuName() + "	"
                + sc.getCourseName());
        }
    }

// 使用关联的原生SQL查询
public void joinQuery()
{
    // 打开Session和事务
    Session session = HibernateUtil.currentSession();
    Transaction tx = session.beginTransaction();
    String sqlString = "select s.* , e.* from student_inf s , "
        + "enrolment_inf e where s.student_id=e.student_id";
    List list = session.createSQLQuery(sqlString)
        .addEntity("s", Student.class)
        .addJoin("e" , "s.enrolments")
        .list();
    // 提交事务,关闭Session
    tx.commit();
    HibernateUtil.closeSession();
    // 因为数据已经全部被选出,故程序可以遍历列表中的数据
    for (Object ele : list)
    {
        // 每个集合元素都是Student、Enrolment组成的数组
        Object[] objs = (Object[])ele;
        Student s = (Student)objs[0];
        Enrolment e = (Enrolment)objs[1];
        System.out.println(s.getName() + "	" + e.getYear());
    }
}
}
package org.crazyit.app.domain;

import javax.persistence.*;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
@Entity
@Table(name="course_inf")
public class Course
{
    // 代表课程编号的成员变量,将作为标识属性
    @Id @Column(name="course_code")
    private String courseCode;
    // 代表课程名成员变量
    private String name;

    // 无参数的构造器
    public Course()
    {
    }
    // 初始化全部成员变量的构造器
    public Course(String courseCode , String name)
    {
        this.courseCode = courseCode;
        this.name = name;
    }

    // courseCode的setter和getter方法
    public void setCourseCode(String courseCode)
    {
        this.courseCode = courseCode;
    }
    public String getCourseCode()
    {
        return this.courseCode;
    }

    // name的setter和getter方法
    public void setName(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return this.name;
    }

}
package org.crazyit.app.domain;

import javax.persistence.*;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
@Entity
@Table(name="enrolment_inf")
public class Enrolment

{
    // 定义标识属性
    @Id @Column(name="enrolment_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer enrolmentId;
    // 定义选课记录所属的学年
    private int year;
    
// 定义选课记录所属的学期
    private int semester;
    // 定义选课记录关联的学生实体
    @ManyToOne(targetEntity=Student.class)
    @JoinColumn(name="student_id")
    private Student student;
    // 定义选课记录关联的课程实体
    @ManyToOne(targetEntity=Course.class)
    @JoinColumn(name="course_code")
    private Course course;

    // enrolmentId的setter和getter方法
    public void setEnrolmentId(Integer enrolmentId)
    {
        this.enrolmentId = enrolmentId;
    }
    public Integer getEnrolmentId()
    {
        return this.enrolmentId;
    }

    // year的setter和getter方法
    public void setYear(int year)
    {
        this.year = year;
    }
    public int getYear()
    {
        return this.year;
    }

    // semester的setter和getter方法
    public void setSemester(int semester)
    {
        this.semester = semester;
    }
    public int getSemester()
    {
        return this.semester;
    }

    // student的setter和getter方法
    public void setStudent(Student student)
    {
        this.student = student;
    }
    public Student getStudent()
    {
        return this.student;
    }

    // course的setter和getter方法
    public void setCourse(Course course)
    {
        this.course = course;
    }
    public Course getCourse()
    {
        return this.course;
    }
}
package org.crazyit.app.domain;

import java.util.*;
import javax.persistence.*;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
@Entity
@Table(name="student_inf")
public class Student
{
    // 代表学生学号的成员变量,将作为标识属性
    @Id @Column(name="student_id")
    private Integer studentNumber;
    // 代表学生姓名的成员变量
    private String name;
    // 该学生的所有选课记录对应的关联实体
    @OneToMany(targetEntity=Enrolment.class
        , mappedBy="student" , cascade=CascadeType.REMOVE)
    private Set<Enrolment> enrolments
        = new HashSet<>();

    // 无参数的构造器
    public Student()
    {
    }
    // 初始化全部成员变量的构造器
    public Student(Integer studentNumber , String name)
    {
        this.studentNumber = studentNumber;
        this.name = name;
    }

    // studentNumber的setter和getter方法
    public void setStudentNumber(Integer studentNumber)
    {
        this.studentNumber = studentNumber;
    }
    public Integer getStudentNumber()
    {
        return this.studentNumber;
    }

    // name的setter和getter方法
    public void setName(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return this.name;
    }

    // enrolments的setter和getter方法
    public void setEnrolments(Set<Enrolment> enrolments)
    {
        this.enrolments = enrolments;
    }
    public Set<Enrolment> getEnrolments()
    {
        return this.enrolments;
    }
}
package org.crazyit.app.vo;

/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
public class StudentCourse
{
    private String stuName;
    private String courseName;

    // stuName的setter和getter方法
    public void setStuName(String stuName)
    {
        this.stuName = stuName;
    }
    public String getStuName()
    {
        return this.stuName;
    }

    // courseName的setter和getter方法
    public void setCourseName(String courseName)
    {
        this.courseName = courseName;
    }
    public String getCourseName()
    {
        return this.courseName;
    }
}
原文地址:https://www.cnblogs.com/tszr/p/12370057.html