`
jiagou
  • 浏览: 2534613 次
文章分类
社区版块
存档分类
最新评论

Hibernate 之 How

 
阅读更多

    在上一篇文章Hibernate 之 Why? 中对Hibernate有了一个初步的了解.接下来我们将从How的角度,也就是如何使用Hibernate来进行学习.

    • Hibernate是一个开源框架,而我们在项目中使用框架的时候都要对所使用的框架进行相关的环境搭建,下面的步骤便是.
      • 创建一个Java项目Hibernate_first
      • 创建User Library,Hibernate核心文件中加入依赖包.
        • HIBERNATE_HOME/lib/*.jar
        • HIBERNATE_HOME/hibernate3.jar
        • 加入数据库驱动(此例子中用mysql驱动)

    UserLiberty部分截图

    计算机生成了可选文字: .以HIBERNATE3卜函ant一i.6.sjar一〔:\Web开发\55日\t001,卜函ant一antlr一l.6.sjar一E:\Web开发\SSH卜函ant一unit一i.6.sjar一E:\We匕开发\55日,。函ant一launcher一l.6.sjar一E:\Web开发\:卜函antlr一2.7.6.jar一〔:\web开发\SSH\t00卜函ant一swing一i.6.sjar一〔:\Web开发\ssf卜函asmjar一〔:\web开发\55日\t0015\动夕卜函asm一attrs.jar一E:\We匕开发\55日\tool卜量c3po一o.9.o.jarE:\Web开发\55日\toc卜困cgli卜2.i.3jar一〔:\Web开发\55日\toc卜函chec七tyle一alljar一〔:\Web开发\55日\卜函cleanimports.ja卜〔:\We匕开发\SSH\·卜函commons一collections一2.i.ijar一〔:助卜最commons一logging一1.0.4.jar一E:\We七卜量concurrent一i.3.2jar一〔:\we匕开发\55卜困connector.jar一〔:\we匕开发\55日\too卜函dom4)一1.6.ijar一〔:\Web开发\55日\t(卜函ehcache一i.Zjar一〔:\Web开发\55日\t(卜函jaas.jar一〔:\web开发\55日\t0015\动夕

    • 创建核心配置文件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.driver_class">com.mysql.jdbc.Driver</property>
     				<!-- 数据库名称地址 -->
     				<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
     				<!-- 数据库用户名 -->
     				<property name="hibernate.connection.username">root</property>
     				<!-- 数据库密码 -->
     				<property name="hibernate.connection.password">root</property>
     				<!-- 配置数据库适配器.可以直接使用相关数据库的相关特点-->
     				<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
     				<!-- 打印sql语句到控制台 -->
     				<property name="hibernate.show_sql">true</property>
     				<!-- 对打印的Sql语句进行格式化 -->
     				<property name="hibernate.format_sql">true</property>
     				
     				<!-- 对资源进行映射 -->
     				<mapping resource="com/tgb/hibernate/User.hbm.xml"/>
     			</session-factory>
     		</hibernate-configuration>
     

    • 环境搭建完毕之后,接下来我们将会用面相对象的思想来完成对数据库表的创建.和我们以前的先建表有所不同,Hibernate是将类映射到关系库数据中的表.接下来建立User.

    	package com.tgb.hibernate;
     	
     	import java.util.Date;
     	
     	/**
     	 * 
     	 * @title    创建User类   
     	 * @author   jnqqls
     	 * @group    TGB
     	 * @version  1.0
     	 * @datetime 2012-11-30上午10:15:25
     	 * @comments
     	 */
     	public class User {
     		//编号
     		private String id;
     		//姓名
     		private String name;
     		//密码
     		private String password;
     		//创建时间
     		private Date createTime;
     		//失效时间
     		private Date expireTime;
     	
     		public String getId() {
     			return id;
     		}
     	
     		public void setId(String 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 Date getCreateTime() {
     			return createTime;
     		}
     	
     		public void setCreateTime(Date createTime) {
     			this.createTime = createTime;
     		}
     	
     		public Date getExpireTime() {
     			return expireTime;
     		}
     	
     		public void setExpireTime(Date expireTime) {
     			this.expireTime = expireTime;
     		}
     	
     	}
     


    • 接下来是Hibernate中核心的地方:建立映射文件User.hbm.xml.如何将一个类映射成数据库中的一个表?它们之间的映射模型如下
      • 映射模型
        • 计算机生成了可选文字: User类右ser表
      • 创建映射文件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标签表示所要映射的java类,而table属性可以更改它在数据库中表的名字,默认是类名 -->
     			<class name="com.tgb.hibernate.User" >
     			     <!-- 表的主键,有着不同的生存策略 -->
     			    <id name="id">
     			        <generator class="uuid"></generator>
     			    </id>
     			    <!-- 以下内容是对类的属性进行映射 -->
     			   	<property name="name"/>
     			   	<property name="password"/>
     			   	<property name="createTime"/>
     			   	<property name="expireTime"/>
     			</class>
     		</hibernate-mapping>
     

    • 类建好,映射也完成,那么如何将类转化成数据库中的实际表呢?接下来我们将会把User类导入数据库表
      • 为了让Hibernate识别实体类.需要将User.htm.xml加入核心配置文件Hibernate.cfg.xml.
        • <mapping resource="com/bjpowernode/hibernate/User.hbm.xml"/>
      • 编写工具栏ExportDB.java,将我们描述的htm文件生成ddl.也就是hbm2ddl
      • 		package com.tgb.hibernate;
         		
         		import org.hibernate.cfg.Configuration;
         		import org.hibernate.tool.hbm2ddl.SchemaExport;
         		/**
         		 * 
         		 * @title   将hbm生成ddl 将我们描述的htm文件生成ddl.也就是hbm2ddl
         		 * @author   jnqqls
         		 * @group    TGB
         		 * @version  1.0
         		 * @datetime 2012-11-30上午10:35:54
         		 * @comments
         		 */
         		public class ExportDB {
         		
         			/**
         			 * @param args
         			 */
         			public static void main(String[] args) {
         				// TODO Auto-generated method stub
         				
         				//读取配置文件上面的信息
         				Configuration cfg = new Configuration().configure();
         				
         				//将配置文件写成ddl.
         				SchemaExport export = new SchemaExport(cfg);
         				
         				//将ddl打印大控制台并写入数据库中.
         				export.create(true, true);
         			}
         		
         		}
         


      • 测试打印数据:

      log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

      log4j:WARN Please initialize the log4j system properly.

      drop table if exists User

      create table User (id varchar(255) not null, name varchar(255), password varchar(255), createTime datetime, expireTime datetime, primary key (id))

      • 查看数据库中的表:
        • 计算机生成了可选文字: nlgsql>ShO目tablos;+~~~~~~~~~~~~~~~~~~.~~~~~~~~+1Tablos_in_hibornat。_firstl+~~~~~~~~~~~~~~~~~~~~~~~~~~~+!usor!+~~~~~~~~~~~~~~~~~~~~~~~~~~一宁1ro目insot(0.05soc)mgsql>doscusor;FIOld!Tgp。NUllDef己UltEXtr己!id!!nam。!1pass目ordl!croatoTim。!1oxpiroTimoluarchar(255uarchar(255uarchar(255)1NO)1VES)1VES!VES1VESKegpRId己tetillled己totilllO1NULL1NULL1NULL1NULL1NULL5ro目5insot(0.07soc)
      • 建立客户端Client,添加用户数据到Mysql.
        • 建立client

      		package com.tgb.hibernate;
       		
       		import java.util.Date;
       		import org.hibernate.Session;
       		import org.hibernate.SessionFactory;
       		import org.hibernate.cfg.Configuration;
       		
       		/**
       		 * 客户端程序
       		 * @author   jnqqls
       		 * @group    TGB
       		 * @version  1.0
       		 * @datetime 2012-11-27上午9:31:32
       		 * @comments
       		 */
       		
       		public class Client {
       		
       		/**
       		 * @param args
       		 */
       		public static void main(String[] args) {
       		// 读取hibernate.cfg.xml文件
       		Configuration cfg = new Configuration().configure();
       		
       		// 建立SessionFactory,对应一个数据库的镜像.
       		SessionFactory factory = cfg.buildSessionFactory();
       		
       		// 获得session
       		Session session = null;
       		
       		try {
       		// 工厂创建session,并获得.
       		session = factory.openSession();
       		
       		// 手动开启事务
       		session.beginTransaction();
       		
       					    // 创建User实体
       		User user = new User();
       		user.setName("jnqqls");
       		user.setPassword("jnqqls");
       		user.setCreateTime(new Date());
       		user.setExpireTime(new Date());
       		
       		// 保存user对象
       		session.save(user);
       		
       		// 提交事务
       		session.getTransaction().commit();
       		} catch (Exception e) {
       		// 这里只是简单打印一下堆栈,用于测试
       		e.printStackTrace();
       					    //事务回滚.
       		session.getTransaction().rollback();
       		} finally {
       		
       		// session是否为null
       		if (session != null) {
       		
       		// session是否打开
       		if (session.isOpen()) {
       		
       		// 关闭session
       		session.close();
       		}
       		}
       		}
       		
       


        • 执行客户端程序.
          • console上打印的内容如下:

        Hibernate:
             insert
             into
                 User
                 (name, password, createTime, expireTime, id)
             values
                 (?, ?, ?, ?, ?)


        • 查看数据库
          • 计算机生成了可选文字: mgsql>select袄fromUSer;name1pass目ord1createTime1expireTime卜~~~~~~~~~~~12012一11一30拜02898al3b拜f32cd013b拜f32ce8600011jnqqls1jnqqls2012一11一3010:协3:勺710:勺3:勺71ro"inset(0.00导ec)



        总结:使用Hibernate可以让我们通过面向对象的思维来操作关系型数据库.并且在此文的实例中也有体现出在上一篇文章所谈到的Hibernate优点,例如原来插入数据的insert语句(console所打印的语句)现在只需要一句session.save(user)变能完成相同的功能.至此本文从Hibernate如何使用的角度介绍完毕,在接下来的文章中会继续对Hibernate中的内容进行学习和分享.

        分享到:
        评论

        相关推荐

          Hibernate Search In Action

          Then you will learn how to start with Hibernate Search, how to prepare and index your domain model, how to query your data. We will explore advanced concepts like typo recovery, phonetic ...

          How to Use Hibernate JPA

          How to use JPA with Hibernate provider in Eclipse 3.4

          java persistence with hibernate

          In addition, the new and significantly improved EJB 3.0 Java Persistence standard, and how Hibernate implements it, is covered completely. All possible basic and advanced Hibernate mappings are shown...

          Hibernate Recipes(Apress,2ed,2015)

          Hibernate Recipes, 2nd Edition contains a collection of code recipes and templates for learning and building Hibernate solutions for you and your clients, including how to work with the Spring ...

          Beginning Hibernate, 3rd Edition

          What you’ll learn How to build enterprise Java-based transaction-type applications that access complex data with Hibernate How to work with Hibernate 4 Where to integrate into the persistence life ...

          Beginning Hibernate: For Hibernate 5

          Get started with the Hibernate 5 ...Experienced Java developers interested in learning how to use and apply object-relational persistence in Java and who are new to the Hibernate persistence framework.

          Spring.Persistence.with.Hibernate.2nd.Edition.1484202694

          Learn how to use the core Hibernate APIs and tools as part of the Spring Framework. This book illustrates how these two frameworks can be best utilized. Other persistence solutions available in Spring...

          Java.Persistence.with.Hibernate.2nd.Edition

          write transactional applications, and how Hibernate can load data from the database most efficiently. With part 4, “Writing queries,” we introduce the data query features and cover query languages ...

          Hibernate Recipes A Problem-Solution Approach

          The basics of object-relational mapping and how Hibernate is best suited for it How to do various mappings, including one-to-one mapping, many-to-one mapping, collection mapping, component mapping, ...

          hibernate.CHM

          a book about how to use the hibernate API

          blog(guice+hibernate+warp)

          A sample Java web application that demonstrates how &lt;br&gt;Deployment : * Install Dekoh desktop * Start dekoh in interactive mode by executing dekoh_shell.bat / dekoh_shell.sh in directory C:...

          Beginning.Hibernate.For.Hibernate.5.4th.Edition

          Experienced Java developers interested in learning how to use and apply object-relational persistence in Java and who are new to the Hibernate persistence framework. Table of Contents Chapter 1: An ...

          hibernate-shards.jar

          GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 ... 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies ...

          Spring Persistence with Hibernate (2016) 代码

          Learn how to use the core Hibernate APIs and tools as part of the Spring Framework. This book illustrates how these two frameworks can be best utilized. Other persistence solutions available in Spring...

          Hibernate_A Developers Notebook

          Hibernate: A Developer's Notebook shows you how to use Hibernate to automate persistence: you write natural Java objects and some simple configuration files, and Hibernate automates all the ...

          MyEclipse Hibernate Spring 例子

          Welcome to the MyEclipse Hibernate and Spring tutorial. This tutorial is meant to be a quick overview of how using both Hibernate and Spring in the same project works in MyEclipse.

          Hibernate3详解

          What is hibernate Why hibernate How to build a sample The 3 states of PO What hide behind the operation Flush and clear Cache Associations Annotation

          Hibernate基础

          http://how2j.cn/k/hibernate/hibernate-tutorial/31.html学习网址

          hibernate说明文档

          How This API Document Is Organized This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows. Overview The Overview page ...

          How to solve the hibernate N+1 problem?

          NULL 博文链接:https://samueli.iteye.com/blog/287194

        Global site tag (gtag.js) - Google Analytics