• 攻城狮在路上(壹) Hibernate(二)--- 第一个hibernate程序


    1、直接通过JDBC API持久化实体域对象

      A、java.sql常用接口和类:

        DriverManager:驱动程序管理器,负责创建数据库连接。

        Connection:代表数据库连接。

        Statement:负责执行SQL语句。

        PreparedStatement:负责执行SQL语句,具有预定义SQL语句的功能。

        ResultSet:代码SQL查询语句的查询结果集。

     2、常用的ORM中间件

      HibernateMybatisToplinkTorqueObjectRelationBridgeFrontierSuiteCastorFreeFROMExpressoJRelationFrameworkVBSFJgrinder

    3、Hibernate 核心接口

      A、Configuration类:用来读取Hibernate配置文件,并生成SessionFactory对象。在Hibernate 的启动过程中,Configuration 类的实例首先定位映射文档的位置,读取这些配置,然后创建一个SessionFactory对象。 
      B、SessionFactory接口:产生Session实例工厂。SessionFactory在Hibernate中实际起到了一个缓冲区的作用,它缓冲了Hibernate自动生成的SQL语句和一些其它的映射数据,还缓冲了一些将来有可能重复利用的数据。 
      C、Session接口:用来操作PO。它有get(),load(),save(),update()和delete()等方法用来对PO进行加载,保存,更新及删除等操作。它是Hibernate的核心接口。Session 对象是非线程安全的,因此在你的设计中,最好是一个线程只创建一个Session对象。 
      D、Query接口:来对PO进行查询操。它可以从Session的createQuery()方法生成。Query接口让你方便地对数据库及持久对象进行查询,它可以有两种表达方式:HQL语言或本地数据库的SQL语句。Query经常被用来绑定查询参数、限制查询记录数量,并最终执行查询操作。

      E、Criteria接口Criteria接口与Query接口非常类似,它允许你创建并执行面向对象的标准化查询。
      F、Transaction接口:用来管理Hibernate事务,它主要方法有commit()和rollback(),可以从Session的beginTrancation()方法生成。

      G、Callback 接口当一些有用的事件发生时――例如持久对象的载入、存储、删除时,Callback 接口会通知Hibernate去接收一个通知消息。Interceptor,Lifecycle,和Validatable接口。

      H、策略接口当你感觉到Hibernate 的某些功能不足,或者有某些缺陷时,你可以开发一个自己的策略来替换它,而你所要做的仅仅只是继承它的某个策略接口,然后实现你的新策略就可以了

        主键的生成 (IdentifierGenerator 接口)
        本地SQL语言支持 (Dialect 抽象类)
        缓冲机制 (Cache 和CacheProvider 接口)
        JDBC 连接管理 (ConnectionProvider接口)
        事务管理 (TransactionFactory, Transaction, 和 TransactionManagerLookup 接口)
        ORM 策略 (ClassPersister 接口)
        属性访问策略 (PropertyAccessor 接口)
        代理对象的创建 (ProxyFactory接口)

      I、用于扩展Hibernate的功能的接口:UserType,CompositeUserType

     四、使用hibernate的一般步骤

      A、创建hibernate的配置文件。

      B、创建持久化类。

      C、创建对象-关系映射文件。

      D、通过hibernate API编写访问数据库的代码。

    五、第一个hibernate程序

        A、hibernate.properties:

    hibernate.dialect=org.hibernate.dialect.MySQLDialect
    hibernate.connection.driver_class=com.mysql.jdbc.Driver
    hibernate.connection.url=jdbc:mysql://localhost:3306/SAMPLEDB
    hibernate.connection.username=root
    hibernate.connection.password=root
    hibernate.show_sql=true

      B、创建持久化类

    package justTest;
    
    public class Customer {
        ...
    }
    

      

      C、创建对象-关系映射文件

    <?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="mypack.Customer" table="CUSTOMERS">
         
      
        <id name="id" column="ID" type="long">
          <generator class="increment"/>
        </id>
        <property name="name"  column="NAME"  type="string" not-null="true" />  
        <property name="email"     column="EMAIL"     type="string" not-null="true" /> 
        <property name="password"  column="PASSWORD"  type="string" not-null="true"/> 
        <property name="phone"     column="PHONE"     type="int" /> 
        <property name="address"   column="ADDRESS"   type="string" /> 
        <property name="sex"       column="SEX"       type="character"/>  
        <property name="married"   column="IS_MARRIED"  type="boolean"/>      
        <property name="description"   column="DESCRIPTION"  type="text"/>      
        <property name="image"         column="IMAGE"        type="binary"/>
        <property name="birthday"      column="BIRTHDAY"     type="date"/>
        <property name="registeredTime" column="REGISTERED_TIME"  type="timestamp"/>  
    
      </class>
    
    </hibernate-mapping>

      D、通过hibernate API编写访问数据库的代码

    package justTest;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateUtils {
    	
    	private static SessionFactory sessionFactory;
    	
    	static {
            try {
            	/*
            	 * Configuration是hibernate的入口,
            	 * 在新建一个Configuration的实例的时候,hibernate会在classpath里面查找hibernate.properties文件,
            	 * 如果该文件存在,则将该文件的内容加载到一个Properties的实例GLOBAL_PROPERTIES里面;
            	 * 如果不存在,将打印信息hibernate.propertiesnotfound.
            	 */
            	Configuration cfg = new Configuration();
            	
            	/*
            	 * configure()方法默认会在classpath下面寻找hibernate.cfg.xml文件,
            	 * 如果没有找到该文件,系统会打印如下信息并抛出HibernateException异常:hibernate.cfg.xmlnotfound
            	 * 
            	 * hibernate.cfg.xml里面的配置信息可以覆盖hibernate.properties的配置信息。
            	 * 
            	 */
            	//cfg.configure();

              //加载Customer类的对象-关系映射文件:

              //本例中使用hibernate.properties,属性配置文件没有mapping这个属性,所以必须采用硬编码的方式对要加载的映射文件进行声明

              cfg.addClass(Customer.class);

            	sessionFactory = cfg.buildSessionFactory();
            	
            	//手动指定
            	//Configuration cfg = newConfiguration().configure("myexample.xml");
            	//Configuration cfg = newConfiguration().setProperties(properties).configure();
            	//Configuration cfg = newConfiguration().addURL(Configuration.class.getResource("Cat.hbm.xml"));
            	//Configuration cfg = newConfiguration().addFile("Cat.hbm.xml");
            	//Configuration cfg = newConfiguration().addClass(Cat.class);
            	/*
            	 * addClass: String mappingResourceName = persistentClass.getName().replace( '.', '/' ) + ".hbm.xml";
            	 * 会在该类的同目录下查找同名的.hbm.xml文件
            	 */
            	
            } catch (Throwable ex) {
                throw new ExceptionInInitializerError(ex);
            }
        }
    	
    	
    	/**
    	 * 保存对象,其余的API类似
    	 * @param bean
    	 */
    	public void saveCustomer(Customer bean){
    	    Session session = sessionFactory.openSession();
    	    Transaction tx = null;
    	    try {
    	      tx = session.beginTransaction();
    	      session.save(bean);
    	      tx.commit();
    	    }catch (RuntimeException e) {
    	      if (tx != null) {
    	        tx.rollback();
    	      }
    	      throw e;
    	    } finally {
    	      session.close();
    	    }
    	  }
    	
    	/*
    	 * 查询
    	 * Query query = session.createQuery("from Customer as c order by c.name asc");
    	 * List customers = query.list();
    	 * 
    	 * Customer c = (Customer)session.get(Customer.class,customer_id);
    	 * 
    	 * 删除
    	 * session.delete(customer);
    	 * 
    	 */
    
    	public static void setSessionFactory(SessionFactory sessionFactory) {
    		HibernateUtils.sessionFactory = sessionFactory;
    	}
    
    	public static SessionFactory getSessionFactory() {
    		return sessionFactory;
    	}
    	
    }
    

      PS:上述代码的实现仅为演示效果,至于线程安全等问题未加考虑,希望不要对其他人产生误导


    声明:该文所有内容均来自《精通Hibernate:Java对象持久化技术详解》[孙卫琴 电子工业出版社] 一书。该文的目的仅仅作为学习笔记。若需要转载,请注明原书相关信息。

  • 相关阅读:
    webapp开发绝对定位引发的问题
    git下配置github sshkey
    html5 filereader读取流注意事项
    神奇的负Margin
    泪奔的ie
    第二次作业-实践一 网络攻防环境的搭建
    20199115 2019-2020-2 《网络攻防实践》第一周作业
    《网络攻防实践》寒假作业
    C++中cin、cin.get()、cin.getline()、getline()、gets()等函数的用法
    getline()函数
  • 原文地址:https://www.cnblogs.com/tq03/p/3740177.html
Copyright © 2020-2023  润新知