代码:
1.Hibernate框架配置文件
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">
- <!-- Generated by MyEclipse Hibernate Tools. -->
- <hibernate-configuration>
- <session-factory>
- <property name="show_sql">true</property>
- <property name="myeclipse.connection.profile">bookshop</property>
- <property name="connection.url">
- jdbc:MysqL://localhost:3306/bookshop
- </property>
- <property name="connection.username">root</property>
- <property name="connection.password">1234</property>
- <property name="connection.driver_class">
- com.MysqL.jdbc.Driver
- </property>
- <property name="dialect">
- org.hibernate.dialect.MysqLDialect
- </property>
- <mapping resource="com/hibtest2/entity/Users.hbm.xml" />
- <mapping resource="com/hibtest2/entity/Books.hbm.xml" />
- <mapping resource="com/hibtest2/entity/Publishers.hbm.xml" />
- <mapping resource="com/hibtest2/entity/Student.hbm.xml" />
- <mapping resource="com/hibtest2/entity/Course.hbm.xml" />
- </session-factory>
- </hibernate-configuration>
2.基类
BaseHibernateDAO.java
- package com.hibtest2.dao;
- import java.io.Serializable;
- import java.util.List;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.Transaction;
- import org.hibernate.criterion.Example;
- import com.hibtest2.HibernateSessionFactory;
- public abstract class BaseHibernateDAO {
- /*
- * 添加数据
- */
- protected void add(Object object){
- Transaction tran=null;
- //获取session
- Session session=HibernateSessionFactory.getSession();
- try{
- //开始事务
- tran=session.beginTransaction();
- //持久化操作
- session.save(object);
- //提交事务
- tran.commit();
- }catch (Exception e) {
- if(tran!=null){
- //事务回滚
- tran.rollback();
- }
- e.printStackTrace();
- }finally{
- //关闭session
- session.close();
- }
- }
- /*
- * 加载数据
- */
- protected Object get(Class cla,Serializable id){
- Object object=null;
- Session session=HibernateSessionFactory.getSession();
- try {
- object=session.get(cla,id);
- } catch (HibernateException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- finally {
- session.close();
- }
- return object;
- }
- /*
- * 删除数据
- */
- protected void delete(Object object){
- Transaction tran=null;
- Session session=HibernateSessionFactory.getSession();
- try {
- tran=session.beginTransaction();
- session.delete(object);
- tran.commit();
- } catch (HibernateException e) {
- // TODO Auto-generated catch block
- if(tran!=null){
- tran.rollback();
- }
- e.printStackTrace();
- }
- finally {
- session.close();
- }
- }
- /*
- * 修改数据
- */
- protected void update(Object object){
- Transaction tran=null;
- Session session=HibernateSessionFactory.getSession();
- try {
- tran=session.beginTransaction();
- session.update(object);
- tran.commit();
- } catch (HibernateException e) {
- // TODO Auto-generated catch block
- if(tran!=null){
- tran.rollback();
- }
- e.printStackTrace();
- }
- finally {
- session.close();
- }
- }
- /*
- * 查询数据
- */
- protected List search(Class cla,Object condition){
- Session session=null;
- List list=null;
- try {
- session=HibernateSessionFactory.getSession();
- list=session.createCriteria(cla).add(Example.create(condition)).list();
- } catch (Exception e) {
- // TODO: handle exception
- } finally{
- session.close();
- }
- return list;
- }
- }
3.实体类
Users.java
- package com.hibtest2.entity;
- /**
- * Users entity. @author MyEclipse Persistence Tools
- */
- public class Users implements java.io.Serializable {
- // Fields
- private Integer id;
- private String loginName;
- private String loginPwd;
- // Constructors
- /** default constructor */
- public Users() {
- }
- /** full constructor */
- public Users(String loginName,String loginPwd) {
- this.loginName = loginName;
- this.loginPwd = loginPwd;
- }
- // Property accessors
- public Integer getId() {
- return this.id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getLoginName() {
- return this.loginName;
- }
- public void setLoginName(String loginName) {
- this.loginName = loginName;
- }
- public String getLoginPwd() {
- return this.loginPwd;
- }
- public void setLoginPwd(String loginPwd) {
- this.loginPwd = loginPwd;
- }
- }
Student.java
- package com.hibtest2.entity;
- import java.util.HashSet;
- import java.util.Set;
- /**
- * Student entity. @author MyEclipse Persistence Tools
- */
- public class Student implements java.io.Serializable {
- // Fields
- private Integer studentId;
- private String studentName;
- private Set courses=new HashSet();
- // Constructors
- public Set getCourses() {
- return courses;
- }
- public void setCourses(Set courses) {
- this.courses = courses;
- }
- /** default constructor */
- public Student() {
- }
- /** full constructor */
- public Student(String studentName) {
- this.studentName = studentName;
- }
- // Property accessors
- public Integer getStudentId() {
- return this.studentId;
- }
- public void setStudentId(Integer studentId) {
- this.studentId = studentId;
- }
- public String getStudentName() {
- return this.studentName;
- }
- public void setStudentName(String studentName) {
- this.studentName = studentName;
- }
- }
Publishers.java
- package com.hibtest2.entity;
- import java.util.HashSet;
- import java.util.Set;
- /**
- * Publishers entity. @author MyEclipse Persistence Tools
- */
- public class Publishers implements java.io.Serializable {
- // Fields
- private Integer id;
- private String name;
- private Set bks=new HashSet();
- // Constructors
- public Set getBks() {
- return bks;
- }
- public void setBks(Set bks) {
- this.bks = bks;
- }
- /** default constructor */
- public Publishers() {
- }
- /** full constructor */
- public Publishers(String name) {
- this.name = name;
- }
- // Property accessors
- public Integer getId() {
- return this.id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
Course.java
- package com.hibtest2.entity;
- import java.util.HashSet;
- import java.util.Set;
- /**
- * Course entity. @author MyEclipse Persistence Tools
- */
- public class Course implements java.io.Serializable {
- // Fields
- private Integer courseId;
- private String courseName;
- private Set students=new HashSet();
- // Constructors
- public Set getStudents() {
- return students;
- }
- public void setStudents(Set students) {
- this.students = students;
- }
- /** default constructor */
- public Course() {
- }
- /** full constructor */
- public Course(String courseName) {
- this.courseName = courseName;
- }
- // Property accessors
- public Integer getCourseId() {
- return this.courseId;
- }
- public void setCourseId(Integer courseId) {
- this.courseId = courseId;
- }
- public String getCourseName() {
- return this.courseName;
- }
- public void setCourseName(String courseName) {
- this.courseName = courseName;
- }
- }
Books.java
- package com.hibtest2.entity;
- /**
- * Books entity. @author MyEclipse Persistence Tools
- */
- public class Books implements java.io.Serializable {
- // Fields
- private Integer id;
- private String title;
- private String author;
- //private Integer publisherId;
- private Publishers publishers;
- public Publishers getPublishers() {
- return publishers;
- }
- public void setPublishers(Publishers publishers) {
- this.publishers = publishers;
- }
- private Integer publisherDate;
- private String isbn;
- private Integer wordsCount;
- private Integer unitPrice;
- private String contentDescription;
- // Constructors
- /** default constructor */
- public Books() {
- }
- /** minimal constructor */
- public Books(String title,String author,Integer publisherId) {
- this.title = title;
- this.author = author;
- //this.publisherId = publisherId;
- }
- /** full constructor */
- public Books(String title,Integer publisherId,Integer publisherDate,String isbn,Integer wordsCount,Integer unitPrice,String contentDescription) {
- this.title = title;
- this.author = author;
- //this.publisherId = publisherId;
- this.publisherDate = publisherDate;
- this.isbn = isbn;
- this.wordsCount = wordsCount;
- this.unitPrice = unitPrice;
- this.contentDescription = contentDescription;
- }
- // Property accessors
- public Integer getId() {
- return this.id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getTitle() {
- return this.title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
- public String getAuthor() {
- return this.author;
- }
- public void setAuthor(String author) {
- this.author = author;
- }
- /*public Integer getPublisherId() {
- return this.publisherId;
- }
- public void setPublisherId(Integer publisherId) {
- this.publisherId = publisherId;
- }*/
- public Integer getPublisherDate() {
- return this.publisherDate;
- }
- public void setPublisherDate(Integer publisherDate) {
- this.publisherDate = publisherDate;
- }
- public String getIsbn() {
- return this.isbn;
- }
- public void setIsbn(String isbn) {
- this.isbn = isbn;
- }
- public Integer getWordsCount() {
- return this.wordsCount;
- }
- public void setWordsCount(Integer wordsCount) {
- this.wordsCount = wordsCount;
- }
- public Integer getUnitPrice() {
- return this.unitPrice;
- }
- public void setUnitPrice(Integer unitPrice) {
- this.unitPrice = unitPrice;
- }
- public String getContentDescription() {
- return this.contentDescription;
- }
- public void setContentDescription(String contentDescription) {
- this.contentDescription = contentDescription;
- }
- }
4.实体类映射文件
Users.hbm.xml
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <!--
- Mapping file autogenerated by MyEclipse Persistence Tools
- -->
- <hibernate-mapping>
- <class name="com.hibtest2.entity.Users" table="users" catalog="bookshop">
- <id name="id" type="java.lang.Integer">
- <column name="Id" />
- <generator class="native"></generator>
- </id>
- <property name="loginName" type="java.lang.String">
- <column name="LoginName" length="50" />
- </property>
- <property name="loginPwd" type="java.lang.String">
- <column name="LoginPwd" length="16" />
- </property>
- </class>
- </hibernate-mapping>
Student.hbm.xml
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <!--
- Mapping file autogenerated by MyEclipse Persistence Tools
- -->
- <hibernate-mapping>
- <class name="com.hibtest2.entity.Student" table="student" catalog="bookshop">
- <id name="studentId" type="java.lang.Integer">
- <column name="StudentId" />
- <generator class="native"></generator>
- </id>
- <property name="studentName" type="java.lang.String">
- <column name="StudentName" length="16" />
- </property>
- <set name="courses" table="sc" lazy="false" inverse="false">
- <key column="Sid" not-null="true" />
- <many-to-many column="Cid" class="com.hibtest2.entity.Course" />
- </set>
- </class>
- </hibernate-mapping>
Publishers.hbm.xml
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <!--
- Mapping file autogenerated by MyEclipse Persistence Tools
- -->
- <hibernate-mapping>
- <class name="com.hibtest2.entity.Publishers" table="publishers" catalog="bookshop">
- <id name="id" type="java.lang.Integer">
- <column name="Id" />
- <generator class="native"></generator>
- </id>
- <property name="name" type="java.lang.String">
- <column name="Name" length="16" not-null="true" />
- </property>
- <set name="bks" lazy="false" cascade="all" inverse="true">
- <key column="PublisherId" not-null="true"/>
- <one-to-many class="com.hibtest2.entity.Books"/>
- </set>
- </class>
- </hibernate-mapping>
Course.hbm.xml
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <!--
- Mapping file autogenerated by MyEclipse Persistence Tools
- -->
- <hibernate-mapping>
- <class name="com.hibtest2.entity.Course" table="course" catalog="bookshop">
- <id name="courseId" type="java.lang.Integer">
- <column name="CourseId" />
- <generator class="native"></generator>
- </id>
- <property name="courseName" type="java.lang.String">
- <column name="CourseName" length="16" />
- </property>
- <set name="students" table="sc" lazy="false" inverse="true">
- <key column="Cid" not-null="true" />
- <many-to-many column="Sid" class="com.hibtest2.entity.Student" />
- </set>
- </class>
- </hibernate-mapping>
Books.hbm.xml
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <!--
- Mapping file autogenerated by MyEclipse Persistence Tools
- -->
- <hibernate-mapping>
- <class name="com.hibtest2.entity.Books" table="books" catalog="bookshop">
- <id name="id" type="java.lang.Integer">
- <column name="Id" />
- <generator class="native"></generator>
- </id>
- <property name="title" type="java.lang.String">
- <column name="Title" length="16" not-null="true" />
- </property>
- <property name="author" type="java.lang.String">
- <column name="Author" length="16" not-null="true" />
- </property>
- <!--
- <property name="publisherId" type="java.lang.Integer">
- <column name="PublisherId" not-null="true" />
- </property>
- -->
- <many-to-one name="publishers" column="PublisherId" class="com.hibtest2.entity.Publishers" insert="true" update="true" lazy="false"/>
- <property name="publisherDate" type="java.lang.Integer">
- <column name="PublisherDate" />
- </property>
- <property name="isbn" type="java.lang.String">
- <column name="ISBN" length="16" />
- </property>
- <property name="wordsCount" type="java.lang.Integer">
- <column name="WordsCount" />
- </property>
- <property name="unitPrice" type="java.lang.Integer">
- <column name="UnitPrice" precision="8" scale="0" />
- </property>
- <property name="contentDescription" type="java.lang.String">
- <column name="ContentDescription" length="16" />
- </property>
- </class>
- </hibernate-mapping>
5.各种关联映射示例
5.1多对一映射示例
- package com.hibtest2;
- import com.hibtest2.dao.BaseHibernateDAO;
- import com.hibtest2.entity.Books;
- public class TestManyToOne extends BaseHibernateDAO {
- /**
- * @param args
- */
- public static void main(String[] args) {
- TestManyToOne mto=new TestManyToOne();
- mto.testManyToOne();
- }
- public void testManyToOne(){
- //根据id获取Books对象
- Books books=(Books) super.get(Books.class,new Integer(4947));
- //根据多对一映射,从Books对象中获取指定图书的出版社
- System.out.println("编号是4947的图书出版社是:"+books.getPublishers().getName().toString());
- }
- }
5.2一对多映射示例
- package com.hibtest2;
- import java.util.Iterator;
- import com.hibtest2.dao.BaseHibernateDAO;
- import com.hibtest2.entity.Books;
- import com.hibtest2.entity.Publishers;
- public class TestOneToMany extends BaseHibernateDAO {
- /**
- * @param args
- */
- public static void main(String[] args) {
- TestOneToMany otm=new TestOneToMany();
- otm.testOneToMany();
- }
- public void testOneToMany(){
- //根据id获取Publishers对象
- Publishers publishers=(Publishers) super.get(Publishers.class,new Integer(1));
- System.out.println(publishers.getName()+"出版社出版的图书包括:");
- //根据一对多映射,从Publishers对象中获取出版图书名称
- Iterator iter=publishers.getBks().iterator();
- while(iter.hasNext()){
- Books books=(Books)iter.next();
- System.out.println(books.getTitle());
- }
- }
- }
5.3多对多映射示例
- package com.hibtest2;
- import java.util.Iterator;
- import com.hibtest2.dao.BaseHibernateDAO;
- import com.hibtest2.entity.Course;
- import com.hibtest2.entity.Student;
- public class TestManyToMany extends BaseHibernateDAO {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- TestManyToMany m2m=new TestManyToMany();
- //m2m.testAdd_1();
- //m2m.testAdd_2();
- //m2m.testAdd_3();
- //m2m.testDelete_1();
- m2m.testDelete_2();
- }
- public void testAdd_1(){
- //创建两个Student对象
- Student s1=new Student();
- s1.setStudentName("韦小宝");
- Student s2=new Student();
- s2.setStudentName("令狐冲");
- //创建四个Course对象
- Course c1=new Course();
- c1.setCourseName("数据结构");
- Course c2=new Course();
- c2.setCourseName("操作系统");
- Course c3=new Course();
- c3.setCourseName("计算机组成原理");
- Course c4=new Course();
- c4.setCourseName("离散数学");
- //设定s1与c1和c2之间的相互关联
- s1.getCourses().add(c1);
- s1.getCourses().add(c2);
- /*c1.getStudents().add(s1);
- c2.getStudents().add(s1);*/
- //设定s2与c1、c3和c4之间的相互关联
- s2.getCourses().add(c1);
- s2.getCourses().add(c3);
- s2.getCourses().add(c4);
- /*c1.getStudents().add(s2);
- c3.getStudents().add(s2);
- c4.getStudents().add(s2);*/
- //保存c1、c2、c3和c4
- super.add(c1);
- super.add(c2);
- super.add(c3);
- super.add(c4);
- //保存s1和s2对象
- super.add(s1);
- super.add(s2);
- }
- public void testAdd_2(){
- //创建"东方不败"对象
- Student newStu=new Student();
- newStu.setStudentName("东方不败");
- //加载"计算机组成原理"对象
- Course c=(Course)super.get(Course.class,new Integer(3));
- //设置newStu和c对象之间的关联
- newStu.getCourses().add(c);
- //保存对象newStu
- super.add(newStu);
- //更新对象c
- super.update(c);
- }
- public void testAdd_3(){
- //加载"韦小宝"和"东方不败"对象
- Student wxb=(Student)super.get(Student.class,new Integer(1));
- Student dfbb=(Student)super.get(Student.class,new Integer(3));
- //创建"编译原理"课程对象
- Course byyl=new Course();
- byyl.setCourseName("编译原理");
- //设定wxb、dfbb与byyl对象之间的关联
- wxb.getCourses().add(byyl);
- dfbb.getCourses().add(byyl);
- //保存byyl对象
- super.add(byyl);
- //更新wxb和dfbb对象
- super.update(wxb);
- super.update(dfbb);
- }
- public void testDelete_1(){
- //加载"韦小宝"对象,并获得其选课集合
- Student student=(Student)super.get(Student.class,new Integer(1));
- Iterator courses=student.getCourses().iterator();
- //删除中介表sc中与"韦小宝"关联的记录
- while(courses.hasNext()){
- Course course=(Course)courses.next();
- course.getStudents().remove(student);
- }
- //将"韦小宝"对象删除
- super.delete(student);
- }
- public void testDelete_2(){
- //加载"令狐冲"对象
- Student student=(Student)super.get(Student.class,new Integer(2));
- //将"令狐冲"对象删除
- super.delete(student);
- }
- }
5.4双向关联映射示例
- package com.hibtest2;
- import com.hibtest2.dao.BaseHibernateDAO;
- import com.hibtest2.entity.Books;
- import com.hibtest2.entity.Publishers;
- public class TestM2OAndO2M extends BaseHibernateDAO {
- /**
- * 双向关联映射
- */
- public static void main(String[] args) {
- TestM2OAndO2M m2o_o2m=new TestM2OAndO2M();
- //m2o_o2m.testAdd_1();
- //m2o_o2m.testAdd_2();
- //m2o_o2m.testAdd_3();
- //m2o_o2m.testAdd_4();
- //m2o_o2m.testDelete_1();
- //m2o_o2m.testDelete_2();
- m2o_o2m.testUpdate();
- }
- public void testAdd_1(){
- //添加出版社信息
- Publishers publishers=new Publishers();
- publishers.setName("电子工业出版社");
- super.add(publishers);
- }
- public void testAdd_2(){
- //加载得到电子工业出版社实体对象
- Publishers dzgy=(Publishers)super.get(Publishers.class,new Integer(4));
- //新建图书对象
- Books book1=new Books();
- book1.setTitle("单元测试之道C#版");
- book1.setAuthor("(美)托马斯等");
- //将电子工业出版社对象设置到实体对象Books的publishers属性中
- book1.setPublishers(dzgy);
- //将图书对象保存到数据库
- super.add(book1);
- //新建图书对象
- Books book2=new Books();
- book2.setTitle("C++网络编程,卷1");
- book2.setAuthor("(美)施密特");
- //将电子工业出版社对象设置到实体对象Books的publishers属性中
- book2.setPublishers(dzgy);
- //将图书对象保存到数据库
- super.add(book2);
- }
- public void testAdd_3(){
- //创建水利水电出版社对象
- Publishers publishers=new Publishers();
- publishers.setName("水利水电出版社");
- //创建第一个Books对象
- Books book1=new Books();
- book1.setTitle("二级C语言程序设计");
- book1.setAuthor("侯东昌,宋智玲等");
- //创建第二个Book对象
- Books book2=new Books();
- book2.setTitle("Visual Basic.NET");
- book2.setAuthor("徐振明主编");
- //建立Publishers对象和Books对象的一对多双向关联关系,
- //只需从Publishers一方进行维护即可
- publishers.getBks().add(book1);
- publishers.getBks().add(book2);
- //保存Publishers对象
- super.add(publishers);
- }
- public void testAdd_4(){
- //创建一个Publishers对象
- Publishers publishers=new Publishers();
- publishers.setName("西安电子科技大学出版社");
- //创建两个Books对象
- Books book1=new Books();
- book1.setTitle("Windows CE应用程序设计");
- book1.setAuthor("张勇,许波编著");
- Books book2=new Books();
- book2.setTitle("MATLAB及其在...");
- book2.setAuthor("陈怀琛 编著");
- //由于将关联关系交给Books来维护,所以在存储时必须明确地
- //将Publishers设定给Books,即Books必须调用setPublishers()方法
- book1.setPublishers(publishers);
- book2.setPublishers(publishers);
- //建立Publishers对象和Books对象的一对多双向关联关系,并保存Publishers对象
- publishers.getBks().add(book1);
- publishers.getBks().add(book2);
- super.add(publishers);
- }
- public void testDelete_1(){
- //加载待删除的Books对象
- Books book=(Books)super.get(Books.class,new Integer(4939));
- //调用父类的delete方法删除对象
- super.delete(book);
- }
- public void testDelete_2(){
- //加载水利水电出版社对象
- Publishers publisher=(Publishers)super.get(Publishers.class,new Integer(5));
- super.delete(publisher);
- }
- public void testUpdate(){
- //加载"Windows CE应用程序设计"图书实体对象
- Books web_yykf=(Books)super.get(Books.class,new Integer(4958));
- //加载"西安电子科技大学出版社"和"机械工业出版社"两个出版社实体对象
- Publishers xadz=(Publishers)super.get(Publishers.class,new Integer(6));
- Publishers jxgy=(Publishers)super.get(Publishers.class,new Integer(3));
- //从"西安电子科技大学出版社"对象的 bks属性中删除图书"Windows CE应用程序设计",
- //并添加到"机械工业出版社"的bks属性中,同时将"机械工业出版社"设置到该图书对象中
- xadz.getBks().remove(web_yykf);
- jxgy.getBks().add(web_yykf);
- web_yykf.setPublishers(jxgy);
- //更新"Windows CE应用程序设计"图书对象
- super.update(web_yykf);
- }
- }
5.5HQL查询示例
- package com.hibtest2;
- import java.util.Iterator;
- import java.util.List;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import com.hibtest2.entity.Books;
- public class TestHQL {
- /**
- * HQL查询
- */
- public static void main(String[] args) {
- TestHQL tHql=new TestHQL();
- //tHql.testHql_1();
- //tHql.testHql_2();
- //tHql.testHql_3();
- //tHql.testHql_4();
- //tHql.testHql_5();
- //tHql.testHql_6();
- //tHql.pagedSearch(2,3);
- tHql.testHql_7();
- }
- public void testHql_1(){
- //获取session
- Session session=HibernateSessionFactory.getSession();
- //编写HQL语句
- String hql="from Books";
- //创建Query对象
- Query query=session.createQuery(hql);
- //执行查询,获得结果
- List list=query.list();
- //遍历查找结果
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- /**
- * 属性查询
- */
- public void testHql_2(){
- Session session=HibernateSessionFactory.getSession();
- //编写HQL语句,使用属性查询
- String hql="select books.title,books.author from Books as books";
- Query query=session.createQuery(hql);
- List list=query.list();
- Iterator itor=list.iterator();
- //每天记录封装成一个Object数组
- while(itor.hasNext()){
- Object[] object=(Object[])itor.next();
- System.out.println(object[0]+" "+object[1]);
- }
- }
- /**
- * 参数查询,按参数位置查询
- */
- public void testHql_3(){
- Session session=HibernateSessionFactory.getSession();
- //编写HQL语句,使用参数查询
- String hql="from Books books where books.title like ? ";
- Query query=session.createQuery(hql);
- //给HQL语句中“?”代表的参数设置值
- query.setString(0,"%C++%");
- List list=query.list();
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- /**
- * 参数查询,按参数名字查询
- */
- public void testHql_4(){
- Session session=HibernateSessionFactory.getSession();
- //通过":bookTitle"定义命名参数"bookTitle"
- String hql="from Books books where books.title=:bookTitle";
- Query query=session.createQuery(hql);
- //给命名参数设置值
- query.setString("bookTitle","C++ Primer中文版");
- List list=query.list();
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- /**
- * 连接查询
- */
- public void testHql_5(){
- Session session=HibernateSessionFactory.getSession();
- //编写HQL语句,使用连接查询
- String hql="select b from Books b,Publishers p where b.publishers=p and p.name='清华大学出版社'";
- Query query=session.createQuery(hql);
- List list=query.list();
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- /**
- * 分页查询
- */
- public void testHql_6(){
- Session session=HibernateSessionFactory.getSession();
- //按书名升序查询图书对象
- String hql="from Books b order by b.title asc";
- Query query=session.createQuery(hql);
- //从第一个对象开始查询
- query.setFirstResult(0);
- //从查询结果中一次返回3个对象
- query.setMaxResults(3);
- //执行查询
- List list=query.list();
- //遍历查询结果
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- public void pagedSearch(int pageIndex,int pageSize){
- Session session=HibernateSessionFactory.getSession();
- String hql="from Books b order by b.title asc";
- Query query=session.createQuery(hql);
- int startIndex=(pageIndex-1)*pageSize;
- query.setFirstResult(startIndex);
- query.setMaxResults(pageSize);
- List list=query.list();
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- /**
- * 聚集函数
- */
- public void testHql_7(){
- Session session=HibernateSessionFactory.getSession();
- //统计记录总数
- String hql1="select count(b) from Books b";
- Query query1=session.createQuery(hql1);
- Long count=(Long)query1.uniqueResult();
- //统计书的平均金额
- String hql2="select avg(b.unitPrice) from Books b";
- Query query2=session.createQuery(hql2);
- Double money=(Double)query2.uniqueResult();
- //统计最贵和最便宜的图书
- String hql3="select min(b.unitPrice),max(b.unitPrice) from Books b";
- Query query3=session.createQuery(hql3);
- Object[] price=(Object[])query3.uniqueResult();
- System.out.println("记录总数"+count.toString()+" 平均金额"+
- money.toString()+" 书价最低为"+price[0].toString()+
- " 书价最高为"+price[1].toString());
- }
- }
5.6Criteria查询示例
总结:通过练习,基本了解Hibernate框架的运行原理,熟练掌握Hibernate框架的基本数据库操作。
- package com.hibtest2;
- import java.util.*;
- import org.hibernate.*;
- import org.hibernate.criterion.*;
- import com.hibtest2.entity.Books;
- public class TestCriteria {
- /**
- * Criteria查询
- */
- public static void main(String[] args) {
- TestCriteria tc=new TestCriteria();
- //使用对象封装查询条件
- /*Books books=new Books();
- books.setTitle("Web应用");
- tc.testCriteria_1(books);*/
- //tc.testCriteria_2();
- //tc.testCriteria_2_1();
- //tc.testCriteria_3();
- //tc.testCriteria_4();
- tc.testDetachedCriteria();
- }
- /**
- * 使用Criteria对象进行简单查询
- * @param condition
- */
- public void testCriteria_1(Books condition){
- //获得session
- Session session=HibernateSessionFactory.getSession();
- //创建Criteria对象
- Criteria criteria=session.createCriteria(Books.class);
- //使用Restrictions对象编写查询条件,并将查询条件加入Criteria对象
- if(condition!=null){
- if(condition.getTitle()!=null && !condition.getTitle().equals("")){
- //按书名进行筛选
- criteria.add(Restrictions.like("title",condition.getTitle(),MatchMode.ANYWHERE));
- }
- if(condition.getAuthor()!=null && !condition.getAuthor().equals("")){
- //按作者进行筛选
- criteria.add(Restrictions.like("author",condition.getAuthor(),MatchMode.ANYWHERE));
- }
- }
- //排序
- criteria.addOrder(Order.asc("id"));
- //执行查询,获得结果
- List list=criteria.list();
- //遍历查询结果
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- /**
- * 使用Criterion 并通过 Restrictions 工具类,实现关联查询
- */
- public void testCriteria_2(){
- Session session=HibernateSessionFactory.getSession();
- Criteria bookCriteria=session.createCriteria(Books.class);
- //设置从Books类中查询的条件
- bookCriteria.add(Restrictions.like("title","C++",MatchMode.ANYWHERE));
- //创建一个新的Criteria实例,以引用pulishers集合中的元素
- Criteria publishersCriteria=bookCriteria.createCriteria("publishers");
- //设置从关联的Publishers类中查询的条件
- publishersCriteria.add(Restrictions.like("name","清华大学出版社"));
- List list=publishersCriteria.list();
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- /**
- * 采用方法链编程风格,使用Criteria对象进行查询
- */
- public void testCriteria_2_1(){
- Session session=HibernateSessionFactory.getSession();
- List list=session.createCriteria(Books.class)
- .add(Restrictions.like("title",MatchMode.ANYWHERE))
- .createCriteria("publishers")
- .add(Restrictions.like("name","清华大学出版社")).list();
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- /**
- * 使用Criterion 并通过 Restrictions 工具类,实现分页查询
- */
- public void testCriteria_3(){
- Session session=HibernateSessionFactory.getSession();
- Criteria criteria=session.createCriteria(Books.class);
- //从第一个对象开始查询
- criteria.setFirstResult(0);
- //每次从查询结果中返回4个对象
- criteria.setMaxResults(4);
- List list=criteria.list();
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- /**
- * 使用Expression类实现查询
- */
- public void testCriteria_4(){
- Session session=HibernateSessionFactory.getSession();
- List list=session.createCriteria(Books.class)
- //使用Expression类编写查询条件
- .add(Expression.like("title",MatchMode.ANYWHERE))
- //对查询结果进行排序
- .addOrder(Order.asc("id")).list();
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- /**
- * 使用DetachedCriteria查询
- */
- public void testDetachedCriteria(){
- //创建离线查询DetachedCriteria实例
- DetachedCriteria query=DetachedCriteria.forClass(Books.class)
- .add(Property.forName("title").eq("Web应用开发技术"));
- //创建Hibernate Session
- Session session=HibernateSessionFactory.getSession();
- //执行查询
- List list=query.getExecutableCriteria(session).list();
- Iterator itor=list.iterator();
- while(itor.hasNext()){
- Books book=(Books)itor.next();
- System.out.println(book.getTitle()+" "+book.getAuthor()+" "+book.getContentDescription());
- }
- }
- }