hibernate学习(一)

一.准备工作:导入jar包

  1.hibernate的jar包

    位置:

       hibernate-release-5.0.2.Finalhibernate-release-5.0.2.Finallib
equired

    包名:

            antlr-2.7.7.jar

       dom4j-1.6.1.jar

       hibernate-commons-annotations-5.0.0.Final.jar

       hibernate-core-5.0.2.Final.jar

       hibernate-jpa-2.0-api-1.0.1.Final.jar

       javassist-3.18.1-GA.jar

       jboss-logging-3.3.0.GA.jar

       jboss-transaction-api_1.1_spec-1.0.1.Final.jar                                 

  

  2.jdbc的jar包

    

       mysql-connector-java-5.1.7.jar

  3.新建数据库:hibernate5

    hibernate5会根据关系映射文件自动创建你配置的数据表  但前提是你的数据库必须存在 不然会抛异常

  

二.编写hibernate配置文件准备工

  1.创建hibernate配置文件:src -> new hibernate Configure XML -> next ->finish。 结束后配置文件的名字就是hibernate.cfg.xml

  2.为了开发方便,可以关联DTD 文件。这样配置时会有相应的提示。   

      a) windows -> preference -> XML-> XML Catalog -> Add

      b) 把"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"(不带双引号复制到Add窗口的key这一项。

       修改keyType为URL


      c) location:       hibernate-release-5.0.2.Finalprojecthibernate-coresrcmain esourcesorghibernate

               这个文件夹下就有 hibernate-configuration-3.0.dtd 和 hibernate-mapping-3.0.dtd 连个文件

      d)点击ok,关联成功

三.开始编写hibernate配置文件

  

<?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">000000</property>
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql:///hibernate5</property>
    
      <!-- 配置hibernate的基本信息 -->
      <!-- hibernate所使用的数据库方言 告诉hibernate使用的是那种数据库,当然不告诉hibernate也可以根据数据库驱动去猜,但是版本也会所区别 -->
      
      <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    
      <!-- 是否在console打印sql语句 -->
      <property name= "show_sql">true</property>
    
      <!-- 是否格式化sql语句,意思就是遇到where order by 等语句会换行 控制台打印出的sql语句读起来就比较好读 -->
      <property name="format_sql">true</property>
    
      <!-- 指定自动生成数据表的策略 -->
      <property name="hbm2ddl.auto">update</property>
    
      <!--指定关联的 .hbm.xml 文件 是一个目录结构 -->
      <mapping resource="com/hjj/hibernate/helloword/News.hbm.xml"/>
     </session-factory>
</hibernate-configuration>

    备注:在这里配置hibernate所使用的数据库方言

      hibernate-release-5.0.2.Finalprojectetc 里的文件hibernate.properties 的mysql数据库方言对应的属性值,一共有三个:

         hibernate.dialect org.hibernate.dialect.MySQLDialect

        hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect  

           hibernate.dialect org.hibernate.dialect.MySQLMyISAMDia

      本来我用的是MySQLInnoDBDialect,但是表格是无法自动创建的,会抛出异常。

       主要信息为: org.hibernate.tool.schema.spi.SchemaManagementException:

              Unable to execute schema management to JDBC target [create table NEWS (ID integer not null auto_increment, TITLE varchar(255), AUTHOR varchar(255), DATE date, primary key (ID)) type=InnoDB]

    然后改了这个值为org.hibernate.dialect.MySQL5InnoDBDialect就可以了

       

四 . 创建持久化类

   

 1 package com.hjj.hibernate.helloword;
 2 import java.sql.Date;
 3 //一般的 javabean 
 4 public class News {
 5     private Integer id;
 6     private String title;
 7     private String author;
 8     private Date date;
 9     
10     public News(){
11         
12     }
13 
14     public News(String title, String author, Date date) {
15         super();
16         this.title = title;
17         this.author = author;
18         this.date = date;
19     }
20 
21     public Integer getId() {
22         return id;
23     }
24 
25     public void setId(Integer id) {
26         this.id = id;
27     }
28 
29     public String getTitle() {
30         return title;
31     }
32     public void setTitle(String title) {
33         this.title = title;
34     }
35 
36     public String getAuthor() {
37         return author;
38     }
39     public void setAuthor(String author) {
40         this.author = author;
41     }
42     
43     public Date getDate() {
44         return date;
45     }
46     public void setDate(Date date) {
47         this.date = date;
48     }
49 
50     @Override
51     public String toString() {
52         return "News [id=" + id + ", title=" + title + ", author=" + author + ", date=" + date + "]";
53     }
54 
55 }

五.创建对象关系映射文件 

  位置:和持久化类(News)位于一个包底下    com.hjj.hibernate.helloworld.News.hbm.xml   

  创建方法:右键->New ->Other ->hiberante XML Mapping file,然后选择News类,映射文件就成功了.

  这个方法是自动生成映射文件,也可以自己写.

  具体代码如下:

<?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 2016-3-7 19:05:44 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.hjj.hibernate.helloword.News" table="NEWS"> 
        <!-- name :类的属性名 -->
        <id name="id" type="java.lang.Integer">
            <!-- column:数据库字段名 -->
            <column name="ID" />
            <!-- 指定主键的生成方式,native:使用数据库本地的生成方式 不同数据库自动主键的方式不同 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.sql.Date">
            <column name="DATE" />
        </property>
    </class>
</hibernate-mapping>

六.通过Hibernate API 编写访问数据库的代码

  创建一个单元测试类

  

package com.hjj.hibernate.helloword;
import static org.junit.Assert.*;
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.junit.Test;

public class HibernateTest {

    @Test
    public void test() {
        //1. 创建一个 SessionFactory对象   SessionFactory 是一个接口
            SessionFactory sessionFactory = null;
            
            //1)创建Configuration 对象 :对应 hibernate的基本配置信息和对象关系映射
            Configuration configuration = new Configuration().configure();
            sessionFactory = configuration.buildSessionFactory();            
        
        //2.创建一个 Session 对象
        Session session = sessionFactory.openSession();
        
        //3.开启事务
        Transaction transaction = session.beginTransaction();

        //4.执行保存操作
        News news = new News("java","HJJ",new Date(new java.util.Date().getTime()));
        session.save(news);
        
        //5.提交事务
        transaction.commit();
        
        //6.关闭session
        session.close();
        
        //7.关闭SessionFactory对象
        sessionFactory.close();
    }

}

七.运行单元测试类

  控制台:

  Hibernate: 

      insert 

      into

        NEWS

        (TITLE, AUTHOR, DATE) 

      values

         (?, ?, ?)

    

    

八.数据库

  自动创建news表格,并且成功插入一条记录

  news表格

    

原文地址:https://www.cnblogs.com/HouJiao/p/5313343.html