zoukankan      html  css  js  c++  java
  • hibernate(一)初识

    一.hibernate是什么

    • hibernate是一种用于数据持久化的框架,
    • 它是对jdbc的第二次封装,可以简化程序员对数据的操作,提高开发效率
    • 它是一种ORM(object relation mapping)映射工具,能够建立面向对象的域模型和关系数据模型之间的映射。

    二.hibernate的基本使用

    1. 创建hibernate配置文件
    2. 创建持久化类,也就是其实例需要保存到数据库中的类
    3. 创建对象关系映射文件
    4. 创建通过hibernate API访问数据库中的代码

    三.实例

    1. 创建hibernate配置文件:hibernate.cfg.xml(配置文件详解)
     1 <!DOCTYPE hibernate-configuration PUBLIC  
     2     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
     3     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
     4   
     5 <hibernate-configuration>  
     6     <session-factory>  
     7         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
     8         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>  //指明需要连接的数据库
     9         <property name="hibernate.connection.username">root</property>  
    10         <property name="hibernate.connection.password">root</property>  
    11         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
    12         <property name="hibernate.show_sql">true</property> 
    13          
    14         <mapping resource="com/entity/User.hbm.xml"/>  //确定hibernate需要操作的实体类
    15     </session-factory>  
    16 </hibernate-configuration> 

      主要功能是:实现具体数据库与应用程序的接通。 

    注意:实体类还需要配置到hibernate.cfg.xml中,以便Hibernate初始化实体类与数据库表的映射关系。如果只配置了映射关系,而没有配置到hibernate.cfg.xml中,Hibernate是无法解析实体类的,因为Hibernate无法自行判断哪些是实体类。

      2.创建持久化类,也就是其实例需要保存到数据库中的类:User.java(配置文件详解

     1 package com.entity;  
     2   
     3 import java.util.Date;  
     4   
     5 public class User {  
     6   
     7     private String id;    
     8     private String name;      
     9     private String password;      
    10     private Date createTime;      
    11     private Date expireTime;  
    12   
    13     public String getId() {  
    14         return id;  
    15     }  
    16     public void setId(String id) {  
    17         this.id = id;  
    18     }   
    19     public String getName() {  
    20         return name;  
    21     }   
    22     public void setName(String name) {  
    23         this.name = name;  
    24     }   
    25     public String getPassword() {  
    26         return password;  
    27     }   
    28     public void setPassword(String password) {  
    29         this.password = password;  
    30     }    
    31     public Date getCreateTime() {  
    32         return createTime;  
    33     }    
    34     public void setCreateTime(Date createTime) {  
    35         this.createTime = createTime;  
    36     }  
    37   
    38     public Date getExpireTime() {  
    39         return expireTime;  
    40     }    
    41     public void setExpireTime(Date expireTime) {  
    42         this.expireTime = expireTime;  
    43     }  
    44 }

      3.创建对象关系映射文件: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.entity.User" table = "user">  //指明该类对应的具体数据表
     7         <id name="id">  
     8             <generator class="uuid"/> //generator属性详解
     9         </id>  
    10         <property name="name"/>  
    11         <property name="password"/>  
    12         <property name="createTime"/>  
    13         <property name="expireTime"/>  
    14     </class>  
    15 </hibernate-mapping>  

       主要功能:实现数据库中表格与相应的实体类的绑定(映射)

      

      4.创建通过hibernate API访问数据库中的代码

       简单的crud操作,通过hibernateUtils类封装起来:

    public class hibernateUtils{
    
        private static SessionFactory factory;
    
        public static Session getSession() {
            return factory.openSession();
        }
    
        static { // 载入虚拟机时执行一次
            // configure默认加载hibernate.cfg.xml
            // 如果不是hibernate.cfg.xml,则指定其他名字,此文件从classpath中找
            Configuration config = new Configuration().configure();
            factory = config.buildSessionFactory();
        }
        //插入
        public static void insert() {
            // 取得session
            Session session = null;
            try {
                session = hibernateUtils.getSession();
                // 开启事务
                session.beginTransaction();
                User user = new User();
                user.setId("3");
                user.setName("jyhuang");
                user.setPassword("root");
                user.setCreateTime(new Date());
                user.setExpireTime(new Date());
                // 保存User对象
                session.save(user);
                // 提交事务
                session.getTransaction().commit();
            } catch (Exception e) {
                e.printStackTrace();
                // 回滚事务
                session.getTransaction().rollback();
            } finally {
                if (session != null) {
                    if (session.isOpen()) {
                        // 关闭session
                        session.close();
                    }
                }
            }
        }
        //更新
        public static void update(Object obj) {
            Session session = null;
            Transaction tx = null;
            try {
                session = hibernateUtils.getSession();
                tx = session.beginTransaction();
                session.update(obj);
                tx.commit();
            } catch (HibernateException e) {
                if (tx != null) { // 如果存在事务,则回滚
                    tx.rollback();
                }
                throw e; // 抛出异常
            } finally {
                if (session != null) // 如果session存在,则关闭
                    session.close();
            }
        }
        //获取
        public static Object get(Class clazz, String id) {
            Session session = null;
            try {
                session = hibernateUtils.getSession();
                Object obj = session.get(clazz, id);
                return obj;
            } finally {
                if (session != null) {
                    session.close();
                }
            }
        }
        //删除
        private static void delete(Object obj) {
            Session session = null;
            Transaction tx = null;
            try {
                session = hibernateUtils.getSession();
                tx = session.beginTransaction();
                session.delete(obj);
                tx.commit();
            } catch (HibernateException e) {
                if (tx != null) { // 如果存在事务,则回滚
                    tx.rollback();
                }
                throw e; // 抛出异常
            } finally {
                if (session != null) // 如果session存在,则关闭
                    session.close();
            }
    
        }
    }

          对应的test类

     1 public class Test {
     2     public static void main(String[] args) {
     3         // 添加
     4          hibernateUtils.insert();
     5         // 删除
     6         // User u = new User();
     7         // u.setId("1");
     8         // hibernateUtils.delete(u);
     9         // 获取
    10 //        User u = (User) hibernateUtils.get(User.class, "2");
    11 //        System.out.println("更新前:" + u.getName());
    12 //        // 更新
    13 //        u.setName("hsyang");
    14 //        hibernateUtils.update(u);
    15 //        User u1 = (User) hibernateUtils.get(User.class, "2");
    16 //        System.out.println("更新后:" + u1.getName());
    17 
    18     }
    19 }
  • 相关阅读:
    java线程安全单例
    ConcurrentHashMap 中putIfAbsent 和put的区别
    Google Guava -缓存cache简单使用
    Jstorm TimeCacheMap源代码分析
    poj 3277...离散化+线段树...
    spoj 1716...动态区间的最大连续子段和问题...点修改...
    spark
    hdu 1754...忘了个getchar(),蛋疼了半天...原来划水也有蛋疼的时候...
    hdu 1556...线段树划水...
    PHP学习笔记06——面向对象版图形计算器
  • 原文地址:https://www.cnblogs.com/studyCenter/p/6592982.html
Copyright © 2011-2022 走看看