zoukankan      html  css  js  c++  java
  • hibernate 02之helloworld

    1、安装插件

    安装方法说明(hibernatetools-4.1.1.Final):
    Help --> Install New Software...
    Click Add... 
    In dialog Add Site dialog, click Archive... 
    Navigate to hibernatetools-Update-4.1.1.Final_2013-12-08_01-06-33-B605.zip  and click  Open 
    Clicking OK in the Add Site dialog will bring you back to the dialog 'Install' 
    Select the Jboss Tools hibernatetools Nightly Build Update Site that has appeared 
    Click Next  and then Finish 
    Approve the license 
    Restart eclipse when that is asked

    2、导入 Hibernate 必须的 jar 包:

    加入数据库驱动的 jar 包:

    3、Hibernate开发步骤

    代码结构如下:

    1、创建 Hibernate 配置文如下:hibernate.cfg.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!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="connection.username">root</property>
            <property name="connection.password">123456</property>
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.url">jdbc:mysql:///hibernate5</property>
            
            <!-- 配置 hibernate 的基本信息 -->
            <!-- hibernate 所使用的数据库方言 (方言就是地方话如北京话,东北话)以下是MySQLDialect和MySQLInnoDBDialect的区别:MySQLDialect:表名不存在下使用。MySQLInnoDBDialect:表名存在的情况下使用-->
            <property name="dialect">org.hibernate.dialect.MySQLDialect </property>        
            
            <!-- 执行操作时是否在控制台打印 SQL -->
            <property name="show_sql">true</property>
        
            <!-- 是否对 SQL 进行格式化 -->
            <property name="format_sql">true</property>
        
            <!-- 指定自动生成数据表的策略 -->
            <property name="hbm2ddl.auto">update</property>
            
            <!-- 指定关联的 .hbm.xml 文件 -->
         
            <mapping resource="com/atguigu/hibernate/helloworld/News.hbm.xml"/>
        
        </session-factory>
    
    </hibernate-configuration>

    2、创建持久化 Java 类

    注意:Hibernate 不要求持久化类继承任何父类或实现接口,这可以保证代码不被污染。这就是Hibernate被称为低侵入式设计的原因

    1、提供一个无参的构造器:使Hibernate可以使用

    2、Constructor.newInstance() 来实例化持久化类

    3、提供一个标识属性(identifier property): 通常映射为数据库表的主键字段. 如果没有该属性,一些功能将不起作用,如:Session.saveOrUpdate()

    4、为类的持久化类字段声明访问方法(get/set): Hibernate对JavaBeans 风格的属性实行持久化。

    5、使用非 final 类: 在运行时生成代理是 Hibernate 的一个重要的功能. 如果持久化类没有实现任何接口, Hibnernate 使用 CGLIB 生成代理. 如果使用的是 final 类, 则无法生成 CGLIB 代理.

    重写 eqauls 和 hashCode 方法: 如果需要把持久化类的实例放到 Set 中(当需要进行关联映射时), 则应该重写这两个方法  

    实体类代码如下:

    package com.atguigu.hibernate.helloworld;
    
    
    import java.util.Date;
    //2创建持久化类
    public class News {
        
        private Integer id; //field
        private String title;
        private String author;
        
        private Date date;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getAuthor() {
            return author;
        }
    
        public void setAuthor(String author) {
            this.author = author;
        }
    
        public Date getDate() {
            return date;
        }
    
        public void setDate(Date date) {
            this.date = date;
        }
      //带参数的构造器为了构建对象方便
        public News(String title, String author, Date date) {
            super();
            this.title = title;
            this.author = author;
            this.date = date;
        }
        
       public News(){
           
       }
    
    @Override
    public String toString() {
        return "News [id=" + id + ", title=" + title + ", author=" + author + ", date=" + date + "]";
    }
       
       
        
        
    }

    3. 创建对象-关系映射文件-News.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">
    <!-- Generated 2018-2-22 19:06:12 by Hibernate Tools 3.5.0.Final -->
    <hibernate-mapping>
        <class name="com.atguigu.hibernate.helloworld.News" table="NEWS">
            <id name="id" type="java.lang.Integer">
                <column name="ID" />
                 <!-- 指定主键的生成方式, native: 使用数据库本地方式 -->
                <generator class="native" />
            </id>
            <property name="title" type="java.lang.String">
                <column name="TITLE" />
            </property>
            <property name="author" type="java.lang.String">
                <column name="AUTHOR" />
            </property>
            <property name="date" type="java.util.Date">
                <column name="DATE" />
            </property>
        </class>
    </hibernate-mapping>

    4. 通过 Hibernate API 编写访问数据库的代码HibernateTest.java

    package com.atguigu.hibernate.helloworld;
    
    import java.sql.Date;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    import org.hibernate.service.ServiceRegistryBuilder;
    import org.junit.Test;
    
    public class HibernateTest {
    
        @Test
        public void test() {
            
            System.out.println("test...");
            
            //1. 创建一个 SessionFactory 对象
            SessionFactory sessionFactory = null;
            
            //1). 创建 Configuration 对象: 对应 hibernate 的基本配置信息和 对象关系映射信息
            Configuration configuration = new Configuration().configure();
            
            //4.0 之前这样创建
    //        sessionFactory = configuration.buildSessionFactory();
            
            //2). 创建一个 ServiceRegistry 对象: hibernate 4.x 新添加的对象
            //hibernate 的任何配置和服务都需要在该对象中注册后才能有效.
            ServiceRegistry serviceRegistry = 
                    new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                                                .buildServiceRegistry();
            
            //3).
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            
            //2. 创建一个 Session 对象
            Session session = sessionFactory.openSession();
            
            //3. 开启事务
            Transaction transaction = session.beginTransaction();
            
            //4. 执行保存操作
            News news = new News("Java12345", "ATGUIGU", new Date(new java.util.Date().getTime()));
            session.save(news);
            
            //5. 提交事务 
            transaction.commit();
            
            //6. 关闭 Session
            session.close();
            
            //7. 关闭 SessionFactory 对象
            sessionFactory.close();
        }
        
    }

    运行测试类控制台输出

    NFO: HHH000262: Table not found: NEWS
    二月 22, 2018 7:19:33 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    INFO: HHH000232: Schema update complete
    Hibernate: 
        insert 
        into
            NEWS
            (TITLE, AUTHOR, DATE) 
        values
            (?, ?, ?)
  • 相关阅读:
    dxCalloutPopup 简单使用教程
    Delphi INI文件保存与读取
    AlertWindowManager 弹出提示窗口使用帮助(下)
    AlertWindowManager 弹出提示窗口使用帮助(上)
    可输入弹出窗口-[POPUP_GET_VALUES_USER_HELP]
    [BAPI]采购申请PR审批-BAPI_REQUISITION_RELEASE_GEN
    如何取域值 (当一些业务需要的值只有数字或者字母时 ,汉字描述在域里面)
    采购订单、采购申请审批策略相关表
    [BAPI]如何修改工单状态-BAPI_ALM_ORDER_MAINTAIN
    [函数]读取采购订单、采购申请更改历史-ME_CHANGEDOC_READ2
  • 原文地址:https://www.cnblogs.com/a8457013/p/8460108.html
Copyright © 2011-2022 走看看