hibernate基本介绍及基本配置(一)

来源:互联网 发布:一建二建难度知乎 编辑:程序博客网 时间:2024/06/05 18:41

hibernate是一个orm框架,orm:对象关系映射。其实,一个项目追溯到最底层的内容,无非就是完成和数据库的交互,这时候,jdbc技术出现了,他更是一种规范,但是,我们完成最基本的增删改查操作都会浪费我们很多时间,我们本应该将更多的精力放在业务逻辑上,hibernate就是包装了jdbc的一个持久化orm框架,我们通过它,可以更简单的完成和数据库的交互。

上面提到了两个地方,一:持久化,何为持久化,就是把对象保存起来,让他一直存在,我们要用时就去取;二:orm思想:对象关系映射,java是一个面向对象的语言,《java编程思想》中提到过Everything is an object,面向对象中,我们关心类,对象,属性;而我们操作的数据库,现在较流行的数据库,如mysql,oracle,都是关系型数据库,也就是说他们是面向关系的,面向关系中,我们关系,表,表的行(记录),表的列(字段);orm的出现正是解决这个思想不统一的矛盾,将表中的记录用对象的形式展开,我们对记录的操作也就转变为对对象的操作,orm采用元数据的方式描述映射细节,常用的就是xml格式的文件;

hibernate的开发步骤:

1.编写hibernate的配置文件,hibernate.cfg.xml

2.编写持久化类

3.编写对象关系映射文件,*.hbm.xml

4.编写hibernate访问数据库的代码

第一步:编写hibernate的配置文件,hibernate.cfg.xml,我们应该从这个配置文件中得到一些基本的信息,如数据库的访问url,username,password一些基本的连接信息以及hibernate配置的相关信息

<span style="font-size:24px;"><?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">c##scott</property><property name="connection.password">tiger</property><property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property><property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <!-- 配置hibernate的基本信息 --><!-- hibernate所使用的数据库方言 --><property name="dialect">org.hibernate.dialect.Oracle10gDialect</property><!-- 执行操作时,是否在数据台打印sql语句 --><property name="show_sql">true</property><!-- 是否对sql进行格式化 --><property name="format_sql">true</property><!-- 指定生成数据表的策略 --><property name="hbm2ddl.auto">update</property><!-- 指定关联的对象关系映射文件 --><mapping resource="com/jiangtao/hibernate/helloworld/News.hbm.xml"/>    </session-factory></hibernate-configuration></span>
第二步:编写持久化类

①提供一个无参的构造器(无参那一定是用到反射喽)

②提供一个表示字段OID,一般映射为数据库中的主键

③提供字段的访问方法(get/set)

④不能声明为final类:在运行时生成代理是hibernate重要的一个功能,如果持久化类没有实现任何接口,自动是使用CGLIB生成代理,如果声明为final类,将无法使用CGLIB生成代理

⑤重写equals和hashCode方法,如果要把持久化类实例放到set中(关联映射时),需要重写

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


<span style="font-size:24px;">package com.jiangtao.hibernate.helloworld;import java.sql.Date;public class News {private int 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;}@Overridepublic String toString() {return "News [id=" + id + ", title=" + title + ", author=" + author+ ", date=" + date + "]";}public int getId() {return id;}public void setId(int 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;}}</span>

第三步:编写对象关系映射文件,*.hbm.xml :安装hibernate-update-tools工具会自动生成

<span style="font-size:24px;"><?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-7-20 9:50:00 by Hibernate Tools 3.4.0.CR1 --><hibernate-mapping>    <class name="com.jiangtao.hibernate.helloworld.News" table="NEWS">            <id name="id" type="int">            <column name="ID" />            <!-- 指定生成OID 的方法  nativa为数据库本地的生成方法-->            <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="DATES" />        </property>            </class></hibernate-mapping></span>
第四步:编写hibernate访问数据库的代码

①获取 Configuration 对象
②获取 SessionFactory 对象
③获取 Session,打开事务
④用面向对象的方式操作数据库
⑤关闭事务,关闭 Session


<span style="font-size:24px;">package com.jiangtao.hibernate.helloworld;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.Service;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;public class HibernateTest {public static void main(String[] args) {new HibernateTest().test();}public void test() {//1.创建sessionFactorySessionFactory sessionFactory = null; //1)创建configurationConfiguration configuration = new Configuration().configure(); //4.0֮可以直接创建sessionFactory //sessionFactory = configuration.buildSessionFactory(); //5.0版本是这样创建的/*ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); */ //2).4.x要先创建一个serviceRegister,他需要传入configuration.getProperties()ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); //3).传入一个serviceRegister来创建sessionFactorysessionFactory = configuration.buildSessionFactory(serviceRegistry);//2.获取sessionSession session = sessionFactory.openSession();//3.开启事务Transaction transaction = session.beginTransaction();//4.ִ创建持久化类对象News news = new News("JAVA", "jiangtao", new Date(new java.util.Date().getTime()));//保存操作session.save(news);//5.关闭事务transaction.commit();//6.关闭sessionsession.close();//7.关闭sessionFactorysessionFactory.close();}}</span>
运行程序,我们会发现数据库中表已经建好了,数据也插入进去了,当然这是正向工程,我们也可以使用逆向工程,通过表来生成域模型和对象的映射文件。


1 0