Hibernate 本地SQL查询

 本地SQL查询来完善HQL不能涵盖所有的查询特性

    下面通过例子来理解本地SQL。

    例子:查询用户和租房的信息

 

1.配置文件

hibernate.cfg.xml

<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>

<hibernate-configuration>

<session-factory>

<!– Database connection settings –>
<property name=”connection.driver_class”>oracle.jdbc.driver.OracleDriver</property>
<property name=”connection.url”>jdbc:oracle:thin:@OWEYOJ5DU7AAHZZ:1521:ORCL</property>
<property name=”connection.username”>jbit</property>
<property name=”connection.password”>bdqn</property>

<!– JDBC connection pool (use the built-in) –>
<property name=”connection.pool_size”>1</property>

<!– SQL dialect –>
<property name=”dialect”>org.hibernate.dialect.OracleDialect</property>

<!– Enable Hibernate’s automatic session context management –>
<property name=”current_session_context_class”>thread</property>

<!– Disable the second-level cache –>
<!– <property name=”cache.provider_class”>org.hibernate.cache.NoCacheProvider</property> –>

<!– Echo all executed SQL to stdout –>
<property name=”show_sql”>true</property>

<!– Drop and re-create the database schema on startup –>
<property name=”hbm2ddl.auto”>update</property>

<mapping resource=”cn/jbit/hibernate/entity/User.hbm.xml” />
<mapping resource=”cn/jbit/hibernate/entity/House.hbm.xml” />
<mapping resource=”cn/jbit/hibernate/entity/Street.hbm.xml” />
<mapping resource=”cn/jbit/hibernate/entity/Type.hbm.xml” />
<mapping resource=”cn/jbit/hibernate/entity/District.hbm.xml” />

</session-factory>

</hibernate-configuration>

 

2.hibernate工具类

  HibernateUtil.java

 

package cn.jbit.hibernate.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/*
* hibernate工具类
*/
public class HibernateUtil {

private static Configuration configuration;

private static final SessionFactory sessionFactory;

static{
try {
configuration=new Configuration();
configuration.configure();
sessionFactory=configuration.buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println(“Initial SessionFactory creation failed.” + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

public Session getSession() throws HibernateException{
return getSessionFactory().getCurrentSession();
}

}

 

实体类

User,java

package cn.jbit.hibernate.entity;

import java.util.Set;

public class User implements java.io.Serializable {

private static final long serialVersionUID = 1L;

private Integer id;
private String name;
private String password;
private String telephone;
private String username;
private String isadmin;
private Set<House> house;

//get&set方法
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getIsadmin() {
return isadmin;
}
public void setIsadmin(String isadmin) {
this.isadmin = isadmin;
}
public Set<House> getHouse() {
return house;
}
public void setHouse(Set<House> house) {
this.house = house;
}
public static long getSerialversionuid() {
return serialVersionUID;
}

}

实体类

House.java

package cn.jbit.hibernate.entity;

import java.util.Date;

public class House {

private Integer id;

private Integer type_id;

private Integer user_id;

private Integer street_id;

private String description;

private Date date;

private Integer price;

private String contact;

private Integer floorage;

private String title;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Integer getType_id() {
return type_id;
}

public void setType_id(Integer type_id) {
this.type_id = type_id;
}

public Integer getUser_id() {
return user_id;
}

public void setUser_id(Integer user_id) {
this.user_id = user_id;
}

public Integer getStreet_id() {
return street_id;
}

public void setStreet_id(Integer street_id) {
this.street_id = street_id;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

public Integer getPrice() {
return price;
}

public void setPrice(Integer price) {
this.price = price;
}

public String getContact() {
return contact;
}

public void setContact(String contact) {
this.contact = contact;
}

public Integer getFloorage() {
return floorage;
}

public void setFloorage(Integer floorage) {
this.floorage = floorage;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

}

5.映射文件

House.hbm.xml

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>

<hibernate-mapping>
<class name=”cn.jbit.hibernate.entity.House” table=”House”>
<id name=”id” type=”java.lang.Integer”>
<column name=”id” />
<generator>
</generator>
</id>
<property name=”type_id” type=”java.lang.Integer”>
<column name=”type_id” length=”50″ />
</property>
<property name=”user_id” type=”java.lang.Integer”>
<column name=”user_id” length=”50″ />
</property>
<property name=”street_id” type=”java.lang.Integer”>
<column name=”street_id” length=”50″ />
</property>
<property name=”description” type=”java.lang.String”>
<column name=”description” length=”50″ />
</property>
<property name=”date” type=”java.util.Date”>
<column name=”pubdate” length=”50″ />
</property>
<property name=”price” type=”java.lang.Integer”>
<column name=”price” length=”50″/>
</property>
<property name=”contact” type=”java.lang.String”>
<column name=”contact” length=”50″/>
</property>
<property name=”floorage” type=”java.lang.Integer”>
<column name=”floorage” length=”50″/>
</property>
<property name=”title” type=”java.lang.String”>
<column name=”title” length=”50″/>
</property>

</class>
</hibernate-mapping>

 

6.映射文件

User.hbm.xml

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>

<hibernate-mapping>
<class name=”cn.jbit.hibernate.entity.User” table=”users”>
<id name=”id” type=”java.lang.Integer”>
<column name=”id” />
<generator>
<param name=”sequence”>SEQ_ID</param>
</generator>
</id>
<property name=”name” type=”java.lang.String”>
<column name=”name” length=”50″ />
</property>
<property name=”password” type=”java.lang.String”>
<column name=”password” length=”50″ />
</property>
<property name=”telephone” type=”java.lang.String”>
<column name=”telephone” length=”50″ />
</property>
<property name=”username” type=”java.lang.String”>
<column name=”username” length=”50″ />
</property>
<property name=”isadmin” type=”java.lang.String”>
<column name=”isadmin” length=”50″/>
</property>
<set name=”House” table=”house”>
<key>
<column name=”user_id”></column>
</key>
<one-to-many/>
</set>

</class>

  <!–

    使用<sql-query>元素定义本地sql查询语句,和<class>并列,与命名查询类似。使用<sql-query>元素的子元素<return>指定别名与实体类联系,其中alias属性用于

    指定别名,class属性用于指定实体类。在程序中通过Session对象的getNameQuery()方法获取该查询语句

–>
<sql-query name=”findUserHouse”>
<![CDATA[
select {u.*},{h.*} from users u,house h where u.id=h.user_id
]]>
<return alias=”u”/>
<return alias=”h”/>
</sql-query>

</hibernate-mapping>

 

测试类

Test.java

import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import cn.jbit.hibernate.entity.House;
import cn.jbit.hibernate.entity.QueryProperties;
import cn.jbit.hibernate.entity.User;
import cn.jbit.hibernate.util.HibernateUtil;

public class Test {

public static void main(String[] args) {
HibernateUtil u= new HibernateUtil();
SessionFactory sf = null;
Session session =null;
Transaction tx=null;
try{
session=u.getSession();
tx=session.beginTransaction();
         //本地SQL查询
Query query=session.getNamedQuery(“findUserHouse”);//获取本地查询语句

List result=query.list();
Iterator it=result.iterator();
while(it.hasNext()){
Object[] results=(Object[])it.next();
User user =(User)results[0];
House house=(House)results[1];
System.out.println(“用户名:”+user.getName()+”  房屋信息:”+house.getTitle()+user.getTelephone());
}
}catch(HibernateException e){
e.printStackTrace();
}

}

}

 

如果不在User.hbm.xml配置文件中添加本地sql查询语句,也可以在直接在测试类中添加。

执行本地sql查询将不是使用Query接口了,而是通过SQLQuery接口,使用Session的createSQLQuery(String sql)方法利用传入的sql参数获得SQLQuery实例

在使用这个方法时,还需要传入查询实体类,因此需要SQLQuery的addEntity(String alias,Class entityClass)方法。addEntity()方法是将别名与实体类联系在一起。

例如:

Test1.java

 

import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import cn.jbit.hibernate.entity.House;
import cn.jbit.hibernate.entity.QueryProperties;
import cn.jbit.hibernate.entity.User;
import cn.jbit.hibernate.util.HibernateUtil;

public class Test1 {

public static void main(String[] args) {
HibernateUtil u= new HibernateUtil();
SessionFactory sf = null;
Session session =null;
Transaction tx=null;
try{
session=u.getSession();
tx=session.beginTransaction();
  //本地SQL查询

          //sql语句中的u是sql中表Users表名,也是指定实体对象的别名。{}表示引用实体类的属性。
String sql=”select {u.*},{h.*} from users as u,house as h where u.id=h.user_id”;

            SQLQuery query=session.createSQLQuery(sql).addEntity(“u”,User.class).addEntity(“h”,House.class);

List result=query.list();
Iterator it=result.iterator();
while(it.hasNext()){
Object[] results=(Object[])it.next();
User user =(User)results[0];
House house=(House)results[1];
System.out.println(“用户名:”+user.getName()+”  房屋信息:”+house.getTitle()+user.getTelephone());
}
}catch(HibernateException e){
e.printStackTrace();
}

}

}

标签