hibernate学习(一)

时间:2023-03-09 17:03:14
hibernate学习(一)

一.准备工作:导入jar包

  1.hibernate的jar包

    位置:

       hibernate-release-5.0.2.Final\hibernate-release-5.0.2.Final\lib\required\

    包名:

            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.Final\project\hibernate-core\src\main\resources\org\hibernate\

               这个文件夹下就有 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.Final\project\etc 里的文件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就可以了

       

四 . 创建持久化类

   

 package com.hjj.hibernate.helloword;
import java.sql.Date;
//一般的 javabean
public class News {
private Integer id;
private String title;
private String author;
private Date date; public News(){ } public News(String title, String author, Date date) {
super();
this.title = title;
this.author = author;
this.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;
} @Override
public String toString() {
return "News [id=" + id + ", title=" + title + ", author=" + author + ", date=" + date + "]";
} }

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

  位置:和持久化类(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表格

  hibernate学习(一)