在Hibernate中也可以使用标准SQL查询数据,格式如下:

SQLQuerysqlQuery=session.createSQLQuery("SQL语句");

hibernate.cfg.xml:

<?xmlversion='1.0'encoding='UTF-8'?>

<!DOCTYPEhibernate-configurationPUBLIC

"-//Hibernate/HibernateConfigurationDTD3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!--GeneratedbyMyEclipseHibernateTools.-->

<hibernate-configuration>

<session-factory>

<propertyname="connection.username">scott</property>

<propertyname="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:MGC</property>

<propertyname="dialect">org.hibernate.dialect.Oracle9Dialect</property>

<propertyname="myeclipse.connection.profile">MGC</property>

<propertyname="connection.password">tiger</property>

<propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

<propertyname="show_sql">true</property>

<mappingresource="cn/edu/ahau/mgc/hibernate/pojo/Student.hbm.xml"/>

<mappingresource="cn/edu/ahau/mgc/hibernate/pojo/Classes.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Student.java:

packagecn.edu.ahau.mgc.hibernate.pojo;

publicclassStudent{

privatelongid;

privateStringname;

privateClassesclasses;

publicClassesgetClasses(){

returnclasses;

}

publicvoidsetClasses(Classesclasses){

this.classes=classes;

}

publiclonggetId(){

returnid;

}

publicvoidsetId(longid){

this.id=id;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

}

}

Classes.java:

packagecn.edu.ahau.mgc.hibernate.pojo;

importjava.util.Set;

publicclassClasses{

privatelongid;

privateStringname;

privateSet<Student>students;

publiclonggetId(){

returnid;

}

publicvoidsetId(longid){

this.id=id;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

}

publicSet<Student>getStudents(){

returnstudents;

}

publicvoidsetStudents(Set<Student>students){

this.students=students;

}

}

Student.hbm.xml:

<?xmlversion="1.0"encoding="utf-8"?>

<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--

MappingfileautogeneratedbyMyEclipsePersistenceTools

-->

<hibernate-mapping>

<classname="cn.edu.ahau.mgc.hibernate.pojo.Classes"table="HQL_CLASSES"schema="SCOTT">

<idname="id"type="java.lang.Long">

<columnname="ID"precision="22"scale="0"/>

<generatorclass="native"/>

</id>

<propertyname="name"type="java.lang.String">

<columnname="NAME"length="20"not-null="true"/>

</property>

<setname="students"inverse="true">

<keycolumn="CLASSID"/>

<one-to-manyclass="cn.edu.ahau.mgc.hibernate.pojo.Student"/>

</set>

</class>

</hibernate-mapping>

Classes.hbm.xml:

<?xmlversion="1.0"encoding="utf-8"?>

<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--

MappingfileautogeneratedbyMyEclipsePersistenceTools

-->

<hibernate-mapping>

<classname="cn.edu.ahau.mgc.hibernate.pojo.Student"table="HQL_STUDENT"schema="SCOTT">

<idname="id"type="java.lang.Long">

<columnname="ID"precision="22"scale="0"/>

<generatorclass="native"/>

</id>

<propertyname="name"type="java.lang.String">

<columnname="NAME"length="20"not-null="true"/>

</property>

<many-to-onename="classes"column="CLASSID"/>

</class>

</hibernate-mapping>

HibernateSessionFactory.java:

packagecn.edu.ahau.mgc.hibernate.many2one.factory;

importorg.hibernate.HibernateException;

importorg.hibernate.Session;

importorg.hibernate.cfg.Configuration;

/**

*ConfiguresandprovidesaccesstoHibernatesessions,tiedtothe

*currentthreadofexecution.FollowstheThreadLocalSession

*pattern,see{@linkhttp://hibernate.org/42.html}.

*/

publicclassHibernateSessionFactory{

/**

*Locationofhibernate.cfg.xmlfile.

*LocationshouldbeontheclasspathasHibernateuses

*#resourceAsStreamstylelookupforitsconfigurationfile.

*Thedefaultclasspathlocationofthehibernateconfigfileis

*inthedefaultpackage.Use#setConfigFile()toupdate

*thelocationoftheconfigurationfileforthecurrentsession.

*/

privatestaticStringCONFIG_FILE_LOCATION="/hibernate.cfg.xml";

privatestaticfinalThreadLocal<Session>threadLocal=newThreadLocal<Session>();

privatestaticConfigurationconfiguration=newConfiguration();

privatestaticorg.hibernate.SessionFactorysessionFactory;

privatestaticStringconfigFile=CONFIG_FILE_LOCATION;

static{

try{

configuration.configure(configFile);

sessionFactory=configuration.buildSessionFactory();

}catch(Exceptione){

System.err

.println("%%%%ErrorCreatingSessionFactory%%%%");

e.printStackTrace();

}

}

privateHibernateSessionFactory(){

}

/**

*ReturnstheThreadLocalSessioninstance.Lazyinitialize

*the<code>SessionFactory</code>ifneeded.

*

*@returnSession

*@throwsHibernateException

*/

publicstaticSessiongetSession()throwsHibernateException{

Sessionsession=(Session)threadLocal.get();

if(session==null||!session.isOpen()){

if(sessionFactory==null){

rebuildSessionFactory();

}

session=(sessionFactory!=null)?sessionFactory.openSession()

:null;

threadLocal.set(session);

}

returnsession;

}

/**

*Rebuildhibernatesessionfactory

*

*/

publicstaticvoidrebuildSessionFactory(){

try{

configuration.configure(configFile);

sessionFactory=configuration.buildSessionFactory();

}catch(Exceptione){

System.err

.println("%%%%ErrorCreatingSessionFactory%%%%");

e.printStackTrace();

}

}

/**

*Closethesinglehibernatesessioninstance.

*

*@throwsHibernateException

*/

publicstaticvoidcloseSession()throwsHibernateException{

Sessionsession=(Session)threadLocal.get();

threadLocal.set(null);

if(session!=null){

session.close();

}

}

/**

*returnsessionfactory

*

*/

publicstaticorg.hibernate.SessionFactorygetSessionFactory(){

returnsessionFactory;

}

/**

*returnsessionfactory

*

*sessionfactorywillberebuildedinthenextcall

*/

publicstaticvoidsetConfigFile(StringconfigFile){

HibernateSessionFactory.configFile=configFile;

sessionFactory=null;

}

/**

*returnhibernateconfiguration

*

*/

publicstaticConfigurationgetConfiguration(){

returnconfiguration;

}

}

ExportToDBCreate.java:

packagecn.edu.ahau.mgc.hibernate.export;

importorg.hibernate.cfg.Configuration;

importorg.hibernate.tool.hbm2ddl.SchemaExport;

publicclassExportToDBCreate{

publicstaticvoidmain(String[]args){

Configurationcfg=newConfiguration().configure();

SchemaExportexport=newSchemaExport(cfg);

export.create(true,true);

}

}

InitData.java:

packagecn.edu.ahau.mgc.hibernate.export;

importorg.hibernate.Session;

importcn.edu.ahau.mgc.hibernate.factory.HibernateSessionFactory;

importcn.edu.ahau.mgc.hibernate.pojo.Classes;

importcn.edu.ahau.mgc.hibernate.pojo.Student;

publicclassInitData{

publicstaticvoidmain(String[]args){

Sessionsession=HibernateSessionFactory.getSession();

session.beginTransaction();

for(inti=0;i<3;i++){

Classesclasses=newClasses();

classes.setName("Class_"+i);

session.save(classes);

for(intj=0;j<3;j++){

Studentstudent=newStudent();

student.setName("Class_"+i+"-Student_"+j);

student.setClasses(classes);

session.save(student);

}

}

for(inti=0;i<3;i++){

Classesclasses=newClasses();

classes.setName("NoStudent-Class_"+i);

session.save(classes);

}

for(inti=0;i<3;i++){

Studentstudent=newStudent();

student.setName("NoClass-Student_"+i);

session.save(student);

}

session.getTransaction().commit();

HibernateSessionFactory.closeSession();

}

}

TestQueryBySQL.java:

packagecn.edu.ahau.mgc.hibernate.pojo;

importjava.util.Iterator;

importjava.util.List;

importjunit.framework.TestCase;

importorg.hibernate.Query;

importorg.hibernate.SQLQuery;

importorg.hibernate.Session;

importcn.edu.ahau.mgc.hibernate.factory.HibernateSessionFactory;

publicclassTestQueryBySQLextendsTestCase{

publicvoidtestSQL(){

Sessionsession=null;

try{

session=HibernateSessionFactory.getSession();

SQLQuerysqlQuery=session.createSQLQuery("select*fromHQL_STUDENT");

List<Object[]>students=sqlQuery.list();

System.out.println("--TEST1:");

for(Iterator<Object[]>iterator=students.iterator();iterator.hasNext();){

Object[]student=iterator.next();

System.out.println("----id:"+student[0]+";name:"+student[1]);

}

}catch(Exceptione){

e.printStackTrace();

}finally{

HibernateSessionFactory.closeSession();

}

}

}