一、Hibernate 概述
1.Hibernate 是一个持久化框架
(1)从狭义的角度来讲,“持久化” 仅仅指把内存中的对象永久的保存到硬盘中的数据库中。
(2)从广义的角度来讲,“持久化” 包括和数据库相关的各种操作。如:CRUD。
2.Hibernate 是一个 ORM 框架
ORM:对象关系映射。O 面向对象:类、对象、属性。R 面向关系:表、行(记录)、列(字段)。M 映射。
ORM 思想:关系数据库中的 行(记录)映射一个对象,程序员可以把对数据库的操作转化为对对象的操作。
在 Hibernate 中,存在 对象关系映射文件用来描述对象与表记录之间的映射关系。
3.Hibernate 配置文件:hibernate.cfg.xml ,配置数据库连接、Hibernate 本身的一些信息、对象关系映射。
4.Entity.hbm.xml 配置文件:对象关系映射文件。
5.Session 接口:Session 是应用程序与数据库之间交互操作的一个单线程对象,是 Hibernate 运作的中心。Session 有一个一级缓存,相当于 JDBC 中的 Connection。
6.SessionFactory 接口:根据配置生成 Session 的工厂。
7.Transaction :事务,可以通过 Session 来开启事务。
二、HelloWorld
(1)在 Intellij Idea 下新建 hibernate.cfg.xml 和根据表创建 实体和 Entity.hbm.xml 文件已经在前一篇文章中讲过了。
(2)生成的 hibernate.cfg.xml 文件。
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 配置连接数据库的基本信息 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property> <!-- 配置 Hibernate 的基本信息 --> <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- 指定自动生成数据表的策略 --> <property name="hbm2ddl.auto">update</property> <mapping resource="com/nucsoft/hibernate/News.hbm.xml"/> </session-factory> </hibernate-configuration>
(2)创建的 news 表。
(3)生成的 News 实体和 News.hbm.xml 文件。
/** * @author solverpeng * @create 2016-09-28-19:36 */ public class News { private int id; private String title; private String author; private 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; } @Override public boolean equals(Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } News news = (News) o; if(id != news.id) { return false; } if(title != null ? !title.equals(news.title) : news.title != null) { return false; } if(author != null ? !author.equals(news.author) : news.author != null) { return false; } if(date != null ? !date.equals(news.date) : news.date != null) { return false; } return true; } @Override public int hashCode() { int result = id; result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (author != null ? author.hashCode() : 0); result = 31 * result + (date != null ? date.hashCode() : 0); return result; } }