标签:
(一)第一个例子
零、说明
这个例子参考了<Hibernate Reference Documentation 3.6.10.Final>1.1. 第一部分 - 第一个Hibernate应用程序.
一、Hibernate介绍
Hibernate项目主页:http://hibernate.org/orm/
二、环境搭建
(1)新建项目HibernateDemo,如下图所示
(2)导入相关jar包,如下图所示
(3)创建数据库和表
1 create database hibernatedemo character set gbk; 2 use hibernatedemo; 3 create table department ( 4 id int primary key, 5 parentid int, 6 name varchar(20) 7 ); 8 -- 一级部门 9 insert into department(id,parentid,name) values(1,-1,"销售部"); 10 insert into department(id,parentid,name) values(2,-1,"生产部"); 11 insert into department(id,parentid,name) values(3,-1,"质检部"); 12 insert into department(id,parentid,name) values(4,-1,"行政部"); 13 insert into department(id,parentid,name) values(5,-1,"仓库部"); 14 insert into department(id,parentid,name) values(6,-1,"配套部"); 15 insert into department(id,parentid,name) values(7,-1,"财务部");
三、使用Hibernate完成数据库查询
(1)定义数据库表对应的实体类
1 package com.cattom.domain; 2 3 /** 4 * 持久化类. 用来代表我们希望储存在数据库的对象. 5 */ 6 public class Department { 7 8 private Long id; 9 private Long parentId; 10 private String name; 11 12 // 所有的持久化类都要求有无参的构造器. 因为Hibernate必须使用Java反射机制来创建对象. 13 public Department() { 14 15 } 16 17 public Long getId() { 18 return id; 19 } 20 21 public void setId(Long id) { 22 this.id = id; 23 } 24 25 public Long getParentId() { 26 return parentId; 27 } 28 29 public void setParentId(Long parentId) { 30 this.parentId = parentId; 31 } 32 33 public String getName() { 34 return name; 35 } 36 37 public void setName(String name) { 38 this.name = name; 39 } 40 41 }
(2)定义Hibernate映射文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 3 <!-- 4 告诉Hibernate怎样加载和存储持久化类的对象. 5 映射文件告诉 Hibernate它应该访问数据库里面的哪个表及应该使用表里面的哪些字段. 6 --> 7 <hibernate-mapping package="com.cattom.domain"> 8 9 <!-- class元素的name属性告诉Hibernate用那个持久化类, table属性告诉Hibernate用数据库中那个表 --> 10 <class name="Department" table="DEPARTMENT"> 11 <!-- property元素的name属性告诉Hibernate使用哪个getter和setter方法, column属性告诉Hibernate对应数据库表的那个字段 --> 12 <id name="id" column="ID" /> <!-- id元素是对identifier属性的声明,对应数据库的primary key列 --> 13 <property name="parentId" column="PARENTID" /> 14 <property name="name" column="NAME" /> 15 </class> 16 17 </hibernate-mapping>
(3)定义Hibernate配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 3 <!-- 告诉Hibernate如何获取数据库连接 --> 4 <hibernate-configuration> 5 6 <session-factory> 7 <!-- Database connection settings --> 8 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 9 <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedemo</property> 10 <property name="connection.username">root</property> 11 <property name="connection.password">root</property> 12 13 <!-- JDBC connection pool (use the built-in) --> 14 <property name="connection.pool_size">1</property> 15 16 <!-- SQL dialect --> 17 <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 18 19 <!-- Enable Hibernate‘s automatic session context management --> 20 <property name="current_session_context_class">thread</property> 21 22 <!-- Echo all executed SQL to stdout --> 23 <property name="show_sql">true</property> 24 25 <mapping resource="com/cattom/domain/Department.hbm.xml" /> 26 </session-factory> 27 28 </hibernate-configuration>
(4)启动和辅助类
1 package com.cattom.util; 2 3 import org.hibernate.SessionFactory; 4 import org.hibernate.cfg.Configuration; 5 6 /** 7 * 启动和辅助类. 创建一个全局的SessionFactory. 这个类来自<Hibernate Reference Documentation 3.6.10.Final> 8 */ 9 public class HibernateUtil { 10 11 private static final SessionFactory sessionFactory = buildSessionFactory(); 12 13 private static SessionFactory buildSessionFactory() { 14 try { 15 return new Configuration().configure().buildSessionFactory(); 16 } catch (Throwable ex) { 17 System.err.println("Initial SessionFactory creation failed." + ex); 18 throw new ExceptionInInitializerError(); 19 } 20 } 21 22 public static SessionFactory getSessionFactory() { 23 return sessionFactory; 24 } 25 26 }
(5)编写测试代码
1 package com.cattom; 2 3 import java.util.List; 4 5 import org.hibernate.Session; 6 7 import com.cattom.domain.Department; 8 import com.cattom.util.HibernateUtil; 9 10 public class DepartmentManager { 11 12 public static void main(String[] args) { 13 DepartmentManager mgr = new DepartmentManager(); 14 15 List departments = mgr.listDepartments(); 16 for (int i = 0; i < departments.size(); i++) { 17 Department department = (Department) departments.get(i); 18 System.out.println("Id:" + department.getId() + " ParentId:" + department.getParentId() + " Name:" + department.getName()); 19 } 20 21 HibernateUtil.getSessionFactory().close(); 22 } 23 24 public List listDepartments() { 25 // SessionFactory创建并打开新的Session. 一个Session代表一个单线程的单元操作. 26 Session session = HibernateUtil.getSessionFactory().getCurrentSession(); 27 session.beginTransaction(); 28 // 用Hibernate查询语言(HQL)查询数据库 29 List result = session.createQuery("from Department").list(); 30 session.getTransaction().commit(); 31 return result; 32 } 33 34 }
(6)添加log4j的配置信息log4j.properties,这个文件来自Hibernate项目下etc目录中的log4j.properties,去掉了无关的注释行
1 ### direct log messages to stdout ### 2 log4j.appender.stdout=org.apache.log4j.ConsoleAppender 3 log4j.appender.stdout.Target=System.out 4 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 5 log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n 6 7 ### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ### 8 9 log4j.rootLogger=warn, stdout 10 11 log4j.logger.org.hibernate=debug 12 13 ### log JDBC bind parameters ### 14 log4j.logger.org.hibernate.type=info 15 16 ### log schema export/update ### 17 log4j.logger.org.hibernate.tool.hbm2ddl=debug
(7)最终的项目结构如下图
(8)运行结果
四、与MyBatis的简单对比
1.都需要一个配置文件来告诉应用程序如何获取数据连接信息.
2.都需要一个映射文件来告诉应用程序数据库表和实体类的映射关系.
3.MyBatis用原生SQL来操作数据库, Hibernate用HQL来操作数据库.
标签:
原文地址:http://www.cnblogs.com/cattom/p/4605525.html