<?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.HqlQuery" fork="yes" failonerror="true"> <classpath refid="classpath"/> </java> </target> </project>
drop database if exists hibernate; create database hibernate; use hibernate; CREATE TABLE event_inf ( event_id int(11) NOT NULL auto_increment, happenDate date default NULL, title varchar(255) default NULL, PRIMARY KEY (event_id) ); INSERT INTO event_inf VALUES (1,'2004-10-03','很高兴的事情'), (2,'2005-10-03','很普通的事情'), (3,'2004-10-04','疯狂Java筹备中'), (4,'2005-10-05','疯狂Java开始培训'); CREATE TABLE person_inf ( person_id int(11) NOT NULL auto_increment, name varchar(255) default NULL, age int(11) default NULL, event_id int(11), PRIMARY KEY (person_id), FOREIGN KEY (event_id) REFERENCES event_inf(event_id) ); INSERT INTO person_inf VALUES (1,'crazyit.org',30 , 1), (2,'老朱',30 , 1); CREATE TABLE person_email ( person_id int(11) NOT NULL, email varchar(255) default NULL, KEY FKECD3B632CC53FFDC (person_id), FOREIGN KEY (person_id) REFERENCES person_inf (person_id) ); INSERT INTO person_email VALUES (1,'crazyit@crazyit.org'), (1,'crazyit@fkit.com'), (2,'dddd@163.com'), (2,'vvvvvv@163.com');
<?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.Person"/> <mapping class="org.crazyit.app.domain.MyEvent"/> </session-factory> </hibernate-configuration>
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="event_inf") public class MyEvent { // 定义标识属性 @Id @Column(name="event_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; // 定义事件名称的成员变量 private String title; // 定义事件发生时间的成员变量 private Date happenDate; // 定义该MyEvent实体关联的所有Person实体 @ManyToMany(targetEntity=Person.class , mappedBy="myEvent") private Set<Person> actors = new HashSet<>(); // id的setter和getter方法 public void setId(Integer id) { this.id = id; } public Integer getId() { return this.id; } // title的setter和getter方法 public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } // happenDate的setter和getter方法 public void setHappenDate(Date happenDate) { this.happenDate = happenDate; } public Date getHappenDate() { return this.happenDate; } // actors的setter和getter方法 public void setActors(Set<Person> actors) { this.actors = actors; } public Set<Person> getActors() { return this.actors; } }
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 = "person_inf") public class Person { // 定义标识属性 @Id @Column(name = "person_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; // 定义Person实例的name成员变量 private String name; // 定义Person实例的age成员变量 private int age; // 定义该Person实体关联的MyEvent实体 @ManyToOne(targetEntity=MyEvent.class) @JoinColumn(name = "event_id" , referencedColumnName="event_id") private MyEvent myEvent; // 定义一个集合属性 // 集合属性,保留该对象关联的学校 @ElementCollection(targetClass=String.class) @CollectionTable(name="person_email_inf", joinColumns=@JoinColumn(name="person_id" , nullable=false)) @Column(name="email_detail" , nullable=false) private Set<String> emails = new HashSet<>(); // id的setter和getter方法 public void setId(Integer id) { this.id = id; } public Integer getId() { return this.id; } // name的setter和getter方法 public void setName(String name) { this.name = name; } public String getName() { return this.name; } // age的setter和getter方法 public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } // myEvent的setter和getter方法 public void setMyEvent(MyEvent myEvent) { this.myEvent = myEvent; } public MyEvent getMyEvent() { return this.myEvent; } // emails的setter和getter方法 public void setEmails(Set<String> emails) { this.emails = emails; } public Set<String> getEmails() { return this.emails; } }
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.Transaction; import org.hibernate.Session; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import org.crazyit.app.domain.*; /** * 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 HqlQuery { public static void main(String[] args) throws Exception { HqlQuery mgr = new HqlQuery(); // 调用查询方法 mgr.findPersons(); // 调用第二个查询方法 mgr.findPersonsByHappenDate(); mgr.findPersonsFetchMyEvent(); } //c第一个查询方法 private void findPersons() { // 获得Hibernate Session Session sess = HibernateUtil.currentSession(); // 开始事务 Transaction tx = sess.beginTransaction(); // 以HQL语句创建Query对象,HQL语句使用隐式连接 List pl = sess.createQuery("from Person p where p.myEvent.title > :title") // 执行setString()方法为HQL语句的参数赋值 .setString("title", " ") //Query调用list()方法访问查询的全部实例 .list(); // 遍历查询的全部结果 for (Object ele : pl) { Person p = (Person)ele; System.out.println(p.getName()); } // 提交事务 tx.commit(); HibernateUtil.closeSession(); } // 第二个查询方法 private void findPersonsByHappenDate()throws Exception { // 获得Hibernate Session对象 Session sess = HibernateUtil.currentSession(); Transaction tx = sess.beginTransaction(); System.out.println("====开始通过日期查找人===="); // 以HQL语句创建Query对象,HQL语句使用显式连接 // 因为没有使用fetch关键字,所以返回List集合元素是被查询实体 List pl = sess.createQuery("select p from Person p left join " + "p.myEvent event where event.happenDate < :endDate") .setDate("endDate",new Date()) .list(); // 遍历结果集 for (Object ele : pl) { Person p = (Person)ele; System.out.println(p.getName()); // 因为执行HQL时没有使用fetch, // 所以只能在Session没有关闭时访问Person关联实体的属性 System.out.println(p.getMyEvent().getTitle()); } tx.commit(); HibernateUtil.closeSession(); } // 第三个查询方法,测试fetch关键字 private void findPersonsFetchMyEvent()throws Exception { // 获得Hibernate Session对象 Session sess = HibernateUtil.currentSession(); Transaction tx = sess.beginTransaction(); System.out.println("====测试fetch查询===="); // 以HQL语句创建Query对象,HQL语句使用显式连接 // 因为使用了fetch关键字,所以返回结果中已有包含关联实体 List pl = sess.createQuery("from Person p left join fetch " + "p.myEvent event where event.happenDate < :endDate") .setDate("endDate",new Date()) .list(); tx.commit(); HibernateUtil.closeSession(); // 遍历结果集 for (Object ele : pl) { Person p = (Person)ele; System.out.println(p.getName()); // 因为HQL语句中使用了fecth关键字 // 所以可以在Session关闭后访问Person关联实体的属性 System.out.println(p.getMyEvent().getTitle()); } } }