zoukankan      html  css  js  c++  java
  • 新手上路之Hibernate:第一个Hibernate例子

    一、Hibernate概述

    (一)什么是Hibernate?

    Hibernate核心内容是ORM(关系对象模型)。可以将对象自动的生成数据库中的信息,使得开发更加的面向对象。这样作为程序员就可以使用面向对象的思想来操作数据库,而不用关心繁琐的JDBC。所以,Hibernate处于三层架构中的D层(持久层)。

    (二)使用Hibernate的优点

    1、Hibernate可以使用在java的任何项目中,不一定非要使用在java web项目中。因为Hibernate不需要类似于tomact这些容器的支持,可以直接通过一个main方法进行测试。

    2、通过下面的实例,可以发现使用Hibernate可以大大减少代码量。

    3、由于使用了Hibernate,代码中不涉及具体的JDBC语句,所以就方便了代码的可移植性。

    二、Hibernate开发的环境搭建

    (一)Hibernate的环境搭建非常简单,只需要引入Hibernate核心包(单击下载)以及Hibernate依赖包(单击下载)即可。
    (二)加入数据库驱动。下面的例子中主要是采用Mysql数据库来演示的,所以在这里引入MysqL的JDBC驱动(点击下载)。
    (三)提供核心配置文件hibernate.cfg.xml文件(在src文件夹下即可)。其中的配置如下(针对mysql)
    1. <!DOCTYPE hibernate-configuration PUBLIC
    2. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    3. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    4. <hibernate-configuration>
    5. <session-factory >
    6. <!-- mysql数据库驱动 -->
    7. <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    8. <!-- mysql数据库名称 -->
    9. <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
    10. <!-- 数据库的登陆用户名 -->
    11. <property name="hibernate.connection.username">root</property>
    12. <!-- 数据库的登陆密码 -->
    13. <property name="hibernate.connection.password">root</property>
    14. <!-- 方言:为每一种数据库提供适配器,方便转换 -->
    15. <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    16. </session-factory>
    17. </hibernate-configuration>
    <!DOCTYPE hibernate-configuration PUBLIC
    	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
    	<session-factory >
    		<!-- mysql数据库驱动 -->
    		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    		<!-- mysql数据库名称 -->
    		<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>
    		
    	</session-factory>
    </hibernate-configuration>

    三、HIbernate第一个实例

    该实例的目录结构如下
    说明:最后一个HIBERNATE3里面包含了所有的需要引用的jar包

    1、新建一个普通的java项目,按照上面的步骤引入相关的jar包和配置文件

    2、建立User实体类
    1. import java.util.Date;
    2. public class User {
    3. private String id;
    4. private String username;
    5. private String password;
    6. private Date createTime;
    7. private Date expireTime;
    8. public String getId() {
    9. return id;
    10. }
    11. public void setId(String id) {
    12. this.id = id;
    13. }
    14. public String getUsername() {
    15. return username;
    16. }
    17. public void setUsername(String userName) {
    18. this.username = userName;
    19. }
    20. public String getPassword() {
    21. return password;
    22. }
    23. public void setPassword(String password) {
    24. this.password = password;
    25. }
    26. public Date getCreateTime() {
    27. return createTime;
    28. }
    29. public void setCreateTime(Date createTime) {
    30. this.createTime = createTime;
    31. }
    32. public Date getExpireTime() {
    33. return expireTime;
    34. }
    35. public void setExpireTime(Date expireTime) {
    36. this.expireTime = expireTime;
    37. }
    38. }
    import java.util.Date;
    
    public class User {
    	private String id;
    	private String username;
    	private String password;
    	private Date createTime;
    	private Date expireTime;
    	
    	public String getId() {
    		return id;
    	}
    	public void setId(String id) {
    		this.id = id;
    	}
    	public String getUsername() {
    		return username;
    	}
    	public void setUsername(String userName) {
    		this.username = userName;
    	}
    	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;
    	}
    }
    2、提供User.hbm.xml文件,完成实体类的映射
    1. <?xml version="1.0"?>
    2. <!DOCTYPE hibernate-mapping PUBLIC
    3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    5. <hibernate-mapping>
    6. <class name="com.example.hibernate.User">
    7. <id name="id">
    8. <generator class="uuid"/>
    9. </id>
    10. <property name="username"/>
    11. <property name="password"/>
    12. <property name="createTime"/>
    13. <property name="expireTime"/>
    14. </class>
    15. </hibernate-mapping>
    <?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.example.hibernate.User">
    		<id name="id">
    			<generator class="uuid"/>
    		</id>
    		<property name="username"/>
    		<property name="password"/>
    		<property name="createTime"/>
    		<property name="expireTime"/>
    	</class>
    </hibernate-mapping>
    其中的property标签是将要生成是数据库表中的字段,在这里不用关心各个字段是什么类型的。因为Hibernate会根据上面的实体类中属性的类型来决定将来表中字段的类型

    3、配置hibernate.cfg.xml文件
    1. <hibernate-configuration>
    2. <session-factory >
    3. <!-- mysql数据库驱动 -->
    4. <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    5. <!-- mysql数据库名称 -->
    6. <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
    7. <!-- 数据库的登陆用户名 -->
    8. <property name="hibernate.connection.username">root</property>
    9. <!-- 数据库的登陆密码 -->
    10. <property name="hibernate.connection.password">root</property>
    11. <!-- 方言:为每一种数据库提供适配器,方便转换 -->
    12. <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    13. <SPAN style="COLOR: #ff0000"><mapping resource="com/example/hibernate/User.hbm.xml"/></SPAN>
    14. </session-factory>
    15. </hibernate-configuration>
    <hibernate-configuration>
    	<session-factory >
    		<!-- mysql数据库驱动 -->
    		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    		<!-- mysql数据库名称 -->
    		<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>
    		
    		<mapping resource="com/example/hibernate/User.hbm.xml"/>
    	</session-factory>
    </hibernate-configuration>
    注意:必须是“/”而不能是“.”。
     
    4、生成表:编写工具类ExoprtDB.java,将hbm生成ddl
    1. import org.hibernate.cfg.Configuration;
    2. import org.hibernate.tool.hbm2ddl.SchemaExport;
    3. /**
    4. * 将hbm生成ddl
    5. * @author BCH
    6. *
    7. */
    8. public class ExoprtDB {
    9. public static void main(String[] args) {
    10. //默认读取hibernate.cfg.xml文件
    11. Configuration cfr = new Configuration().configure();
    12. SchemaExport export = new SchemaExport(cfr);
    13. export.create(true, true);
    14. }
    15. }
    import org.hibernate.cfg.Configuration;
    import org.hibernate.tool.hbm2ddl.SchemaExport;
    /**
     * 将hbm生成ddl
     * @author BCH
     *
     */
    public class ExoprtDB {
    
    	public static void main(String[] args) {
    		//默认读取hibernate.cfg.xml文件
    		Configuration cfr = new Configuration().configure();
    		
    		SchemaExport export = new SchemaExport(cfr);
    		export.create(true, true);
    	}
    }
    
    到这里就可以生成User表了,但是如果直接运行ExoprtDB.java文件是不能生成User表的。因为在mysql数据中还没有建立数据库Hibernate-first。所以在mysql控制台中通过create database hibernate-first; use hibernate-first;之后再执行ExoprtDB.java文件就可以生成表了。

    5、向表中添加数据
    1. import java.util.Date;
    2. import org.hibernate.Session;
    3. import org.hibernate.SessionFactory;
    4. import org.hibernate.cfg.Configuration;
    5. public class Client {
    6. public static void main(String[] args) {
    7. //读取配置文件
    8. Configuration cfg = new Configuration().configure();
    9. SessionFactory factory = cfg.buildSessionFactory();
    10. Session session = null;
    11. try{
    12. session = factory.openSession();
    13. //开启事务
    14. session.beginTransaction();
    15. User user = new User();
    16. user.setUsername("用户名");
    17. user.setPassword("123");
    18. user.setCreateTime(new Date());
    19. user.setExpireTime(new Date());
    20. session.save(user);
    21. //提交事务
    22. session.getTransaction().commit();
    23. }catch(Exception e){
    24. e.printStackTrace();
    25. //回滚事务
    26. session.getTransaction().rollback();
    27. }finally{
    28. if(session != null){
    29. if(session.isOpen()){
    30. //关闭session
    31. session.close();
    32. }
    33. }
    34. }
    35. }
    36. }
    import java.util.Date;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class Client {
    	public static void main(String[] args) {
    		//读取配置文件
    		Configuration cfg = new Configuration().configure();
    		
    		SessionFactory factory = cfg.buildSessionFactory();
    		
    		Session session = null;
    		try{
    			session = factory.openSession();
    			//开启事务
    			session.beginTransaction();
    			
    			User user = new User();
    			user.setUsername("用户名");
    			user.setPassword("123");
    			user.setCreateTime(new Date());
    			user.setExpireTime(new Date());
    			
    			session.save(user);
    			//提交事务
    			session.getTransaction().commit();
    			
    		}catch(Exception e){
    			e.printStackTrace();
    			//回滚事务
    			session.getTransaction().rollback();
    		}finally{
    			if(session != null){
    				if(session.isOpen()){
    					//关闭session
    					session.close();
    				}
    			}
    		}
    	}
    }
    执行该java文件就可以完成向表中增加数据了,效果如下


    (四)总结

    通过上面的代码我们可以看出,在代码中没有涉及到任何有关JDBC的代码,作为开发人员只需要写好相应的实体类,然后通过配置就可以实现了表的建立以及向表中实现数据的插入。
    在代码中有许多Hibernate的核心对象,例如Configuration、SessionFactory、Session等等。这些内容将在以后介绍。
     
  • 相关阅读:
    linux上java和golang环境变量的设置
    MySQL踩坑及MySQL解压版安装
    Mysql踩坑 自动更新的时间只允许有一个
    从零开始学习PYTHON3讲义(十五)让画面动起来
    从零开始学习PYTHON3讲义(十四)写一个mp3播放器
    从零开始学习PYTHON3讲义(十三)记事本的升级版:网络记事本
    从零开始学习PYTHON3讲义(十二)画一颗心送给你
    从零开始学习PYTHON3讲义(十一)计算器升级啦
    从零开始学习PYTHON3讲义(十)自己做一个“电子记事本”
    从零开始学习PYTHON3讲义(九)字典类型和插入排序
  • 原文地址:https://www.cnblogs.com/husam/p/3854031.html
Copyright © 2011-2022 走看看