Hibernate HQL示例一:基本配置及测试查询
Hibernate Hql查询:
大小写敏感,如:from Student 指的是从Student对象中查询。
示例:
第一步创建数据库hibernate
第二步运行ExportDB.java生成表结构。
第三步运行InitData.java生成数据。
第四步进行其它测试。
工具类代码:
package com.bjsxt.hibernate; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class ExportDB { public static void main(String[] args) { //读取配置文件 Configuration cfg = new Configuration().configure(); //创建SchemaExport对象 SchemaExport export = new SchemaExport(cfg); //创建数据库表 export.create(true,true); } }
package com.bjsxt.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtils { private static SessionFactory factory; private HibernateUtils() {} static { Configuration cfg = new Configuration().configure(); factory = cfg.buildSessionFactory(); } public static SessionFactory getSessionFactory() { return factory; } public static Session getSession() { return factory.openSession(); } public static void closeSession(Session session) { if (session != null) { if (session.isOpen()) { session.close(); } } } }
package com.bjsxt.hibernate; import java.util.Set; public class Classes { private int id; private String name; private Set students; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getStudents() { return students; } public void setStudents(Set students) { this.students = students; } }
package com.bjsxt.hibernate; import java.util.Date; public class Student { private int id; private String name; private Date createTime; private Classes classes; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Classes getClasses() { return classes; } public void setClasses(Classes classes) { this.classes = classes; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
Classes.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="com.bjsxt.hibernate.Classes" table="t_classes"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <!-- <set name="students" cascade="all" order-by="id"> --> <set name="students" inverse="true"> <key column="classid"/> <one-to-many class="com.bjsxt.hibernate.Student"/> </set> </class> </hibernate-mapping>
Student.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="com.bjsxt.hibernate.Student" table="t_student"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <property name="createTime"/> <many-to-one name="classes" column="classid"/> <filter name="idfilter" condition="id < :myid"/> </class> <query name="searchStudents"><![CDATA[ select s from Student s where s.id < ? ]]> </query> <filter-def name="idfilter"> <filter-param name="myid" type="integer"/> </filter-def> </hibernate-mapping>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.url"> jdbc:mysql://127.0.0.1/hibernate </property> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">super</property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="show_sql">true</property> <mapping resource="com/bjsxt/hibernate/Classes.hbm.xml"/> <mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/> </session-factory> </hibernate-configuration>
上面文件创建完成之后,运行ExportDB.java
数据库中创建两个表格:t_classes,t_student
表结构如下:
mysql> desc t_classes; +-------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | YES | | NULL | | +-------+--------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql> desc t_student; +------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | YES | | NULL | | | createTime | datetime | YES | | NULL | | | classid | int(11) | YES | MUL | NULL | | +------------+--------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec)
为了作测试生成数据类InitData.java如下:
package com.bjsxt.hibernate; import java.text.SimpleDateFormat; import java.util.Date; import org.hibernate.Session; public class InitData { public static void main(String[] args) { Session session = HibernateUtils.getSession(); try { session.beginTransaction(); for(int i=0; i<10; i++){ Classes classes = new Classes(); classes.setName("班级"+i); session.save(classes); for(int j=0; j<10; j++){ Student student = new Student(); student.setName("班级"+i+"的学生"+j); student.setCreateTime(randomDate("2007-01-01","2007-03-01")); //在内存中建立由student指向classes的引用 student.setClasses(classes); session.save(student); } } for(int i=0; i<5; i++){ Classes classes = new Classes(); classes.setName("无学生班级"+i); session.save(classes); } for(int i=0; i<10; i++){ Student student = new Student(); student.setName("无业游民"+i); session.save(student); } session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } finally{ HibernateUtils.closeSession(session); } } /** * 获取随机日期 * @param beginDate 起始日期,格式为:yyyy-MM-dd * @param endDate 结束日期,格式为:yyyy-MM-dd * @return */ private static Date randomDate(String beginDate,String endDate){ try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date start = format.parse(beginDate); Date end = format.parse(endDate); if(start.getTime() >= end.getTime()){ return null; } long date = random(start.getTime(),end.getTime()); return new Date(date); } catch (Exception e) { e.printStackTrace(); } return null; } private static long random(long begin,long end){ long rtn = begin + (long)(Math.random() * (end - begin)); if(rtn == begin || rtn == end){ return random(begin,end); } return rtn; } }
以下开始做测试:
测试类1:SimpleObjectQueryTest.java
package com.bjsxt.hibernate; import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import junit.framework.TestCase; /** * 对象查询的基本测试 * @author Administrator * */ public class SimpleObjectQueryTest extends TestCase { public void testQuery1() { Session session = null; try { session = HibernateUtils.getSession(); //可以忽略select语句 List students = session.createQuery("from Student").list(); for (Iterator iter = students.iterator();iter.hasNext();) { //返回值是Student对象 Student student = (Student)iter.next(); System.out.println(student.getName()); } }catch(Exception e) { e.printStackTrace(); }finally { HibernateUtils.closeSession(session); } } public void testQuery2() { Session session = null; try { session = HibernateUtils.getSession(); //可以忽略select语句,表可以加别名 List students = session.createQuery("from Student s").list(); for (Iterator iter = students.iterator();iter.hasNext();) { //返回值是Student对象 Student student = (Student)iter.next(); System.out.println(student.getName()); } }catch(Exception e) { e.printStackTrace(); }finally { HibernateUtils.closeSession(session); } } public void testQuery3() { Session session = null; try { session = HibernateUtils.getSession(); //可以忽略select语句,表可以加别名 List students = session.createQuery("from Student as s").list(); for (Iterator iter = students.iterator();iter.hasNext();) { //返回值是Student对象 Student student = (Student)iter.next(); System.out.println(student.getName()); } }catch(Exception e) { e.printStackTrace(); }finally { HibernateUtils.closeSession(session); } } public void testQuery4() { Session session = null; try { session = HibernateUtils.getSession(); //使用select关键字时,必须定义别名 List students = session.createQuery("select s from Student s").list(); for (Iterator iter = students.iterator();iter.hasNext();) { //返回值是Student对象 Student student = (Student)iter.next(); System.out.println(student.getName()); } }catch(Exception e) { e.printStackTrace(); }finally { HibernateUtils.closeSession(session); } } public void testQuery5() { Session session = null; try { session = HibernateUtils.getSession(); //不支持select * ....这样的HQL查询语句 List students = session.createQuery("select * from Student").list(); for (Iterator iter = students.iterator();iter.hasNext();) { //返回值是Student对象 Student student = (Student)iter.next(); System.out.println(student.getName()); } }catch(Exception e) { e.printStackTrace(); }finally { HibernateUtils.closeSession(session); } } }
上面测试中得到的结论:
做查询时,可以忽略select语句; 表可以加别名; 使用select关键字时,必须定义别名; 不支持select * ....这样的HQL查询语句