Hibernate入门(IDEA下自动生成映射文件及实体类)
1.Hibernate開發(fā)步驟
1.創(chuàng)建Hibernate配置文件 2.創(chuàng)建持久化類 3.創(chuàng)建對(duì)象-關(guān)系映射文件 4.通過Hibernate API編寫訪問數(shù)據(jù)庫(kù)的代碼2.創(chuàng)建一個(gè)hibernate項(xiàng)目(IntelliJ IDEA下演示)
后續(xù)需要連接數(shù)據(jù)庫(kù),手動(dòng)導(dǎo)入這兩個(gè)包
3.配置文件
修改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> ?<!-- 配置連接數(shù)據(jù)庫(kù)的基本信息 --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property><!--數(shù)據(jù)庫(kù)用戶名配置--><property name="connection.username">root</property><!--數(shù)據(jù)庫(kù)密碼配置--><property name="connection.password">root</property> ?<!-- 配置 hibernate 的基本信息 --><!-- hibernate 所使用的數(shù)據(jù)庫(kù)方言 --><property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property><!--56--><!-- 執(zhí)行操作時(shí)是否在控制臺(tái)打印 SQL --><property name="show_sql">true</property> ?<!-- 是否對(duì) SQL 進(jìn)行格式化 --><property name="format_sql">true</property> ?<!-- 指定自動(dòng)生成數(shù)據(jù)表的策略 --><property name="hbm2ddl.auto">update</property><!-- 后面的這兩行為后續(xù)自動(dòng)生成實(shí)體類及配置文件時(shí)自動(dòng)生成的--><mapping class="com.yfy.hibernate.entity.NewsEntity"/><mapping resource="com/yfy/hibernate/entity/NewsEntity.hbm.xml"/> ?</session-factory> </hibernate-configuration>生成表的策略:
-
create:會(huì)根據(jù)*.hbm.xml文件來生成數(shù)據(jù)表,但是每次運(yùn)行都會(huì)刪除上一次的表,重新生成表
-
create-drop:會(huì)根據(jù)*.hbm.xml文件來生成數(shù)據(jù)表,但是SessionFactory一關(guān)閉,表就自動(dòng)刪除
-
update:最常用的屬性,會(huì)根據(jù)*.hbm.xml文件生成表,但若.hbm.xml文件和數(shù)據(jù)庫(kù)中對(duì)應(yīng)的數(shù)據(jù)表的結(jié)構(gòu)不同,Hibernate將更新數(shù)據(jù)表結(jié)構(gòu)
-
validate:會(huì)和數(shù)據(jù)庫(kù)中的表進(jìn)行比較,若*.hbm.xml文件中的列在數(shù)據(jù)表中不存在,則拋出異常
4.配置數(shù)據(jù)庫(kù)
(1)點(diǎn)擊Database
(2)選擇數(shù)據(jù)庫(kù)
?
(3)配置數(shù)據(jù)庫(kù)后測(cè)試連接是否成功
?
(4)表結(jié)構(gòu)如下
(5)自動(dòng)生成hibernate實(shí)體類和映射文件
?
(5)生成的實(shí)體類和配置文件如下
創(chuàng)建持久化java類
1.提供一個(gè)無參構(gòu)造器 2.提供一個(gè)標(biāo)識(shí)屬性 3.為類的持久化類字段聲明訪問方法(get/set) 4.使用非final類(在運(yùn)行時(shí)生成代理 cglib) 5.重寫equals和hashCode方法NewsEntity.java
@Entity @Table(name = "news", schema = "hibernate") public class NewsEntity { ?private int id;private String title;private String author;private Date data; ?@Id@Column(name = "id")public int getId() {return id;} ?public void setId(int id) {this.id = id;} ?@Basic@Column(name = "title")public String getTitle() {return title;} ?public void setTitle(String title) {this.title = title;} ?@Basic@Column(name = "author")public String getAuthor() {return author;} ?public void setAuthor(String author) {this.author = author;} ?@Basic@Column(name = "data")public Date getData() {return data;} ?public void setData(Date data) {this.data = data;} ?@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;NewsEntity that = (NewsEntity) o;return id == that.id &&Objects.equals(title, that.title) &&Objects.equals(author, that.author) &&Objects.equals(data, that.data);} ?@Overridepublic int hashCode() { ?return Objects.hash(id, title, author, data);} ?@Overridepublic String toString() {return "NewsEntity{" +"id=" + id +", title='" + title + '\'' +", author='" + author + '\'' +", data=" + data +'}';} }NewsEntity.hbm.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> ?<class name="com.yfy.hibernate.entity.NewsEntity" table="news" schema="hibernate"><id name="id" column="id"/><property name="title" column="title"/><property name="author" column="author"/><property name="data" column="data"/></class> </hibernate-mapping>(6)編寫測(cè)試類
HibernateTest.java
public class HibernateTest { ?private Session getSession() { ?//1. 創(chuàng)建一個(gè) SessionFactory 對(duì)象SessionFactory sessionFactory = null; ?//1). 創(chuàng)建 Configuration 對(duì)象: 對(duì)應(yīng) hibernate 的基本配置信息和 對(duì)象關(guān)系映射信息Configuration configuration = new Configuration().configure(); ?//4.0 之前這樣創(chuàng)建 // sessionFactory = configuration.buildSessionFactory(); ?//2). 創(chuàng)建一個(gè) ServiceRegistry 對(duì)象: hibernate 4.x 新添加的對(duì)象//hibernate 的任何配置和服務(wù)都需要在該對(duì)象中注冊(cè)后才能有效.ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); ?//3).sessionFactory = configuration.buildSessionFactory(serviceRegistry); ?//2. 創(chuàng)建一個(gè) Session 對(duì)象return sessionFactory.openSession();} ?@Testpublic void testGet() { ?Session session = getSession();NewsEntity newsEntity = (NewsEntity) session.get(NewsEntity.class, 2);System.out.println(newsEntity);session.close();} ?@Testpublic void testAdd() { ?Session session = getSession();//3. 開啟事務(wù)Transaction transaction = session.beginTransaction(); ?//4. 執(zhí)行保存操作NewsEntity newsEntity = new NewsEntity(); // ? ? ? newsEntity.setId(2);newsEntity.setTitle("java語(yǔ)句很強(qiáng)嗎");newsEntity.setAuthor("hello123");newsEntity.setData(new Date());session.save(newsEntity); ?//5. 提交事務(wù)transaction.commit(); ?//6. 關(guān)閉 Sessionsession.close();} }5.具體類介紹
Configuration類
負(fù)責(zé)管理Hibernate的配置信息、包括如下內(nèi)容:
-
Hibernate運(yùn)行的底層信息:數(shù)據(jù)庫(kù)的URL、用戶名、密碼、JDBC驅(qū)動(dòng)類,數(shù)據(jù)庫(kù)Dialect,數(shù)據(jù)庫(kù)連接池等(hibernate.cfg.xml)
-
持久化類與數(shù)據(jù)庫(kù)的映射關(guān)系(*.hbm.xml)
創(chuàng)建Configuration的兩種方式
//屬性文件(hibernate.properties) Configuration cfg=new Configuration(); ? //xml文件(hibernate.cfg.xml) Configuration cfg=new Configuration().configure()'//還支持帶參數(shù)的訪問 File file=new File("hibernate.xml"); Configuration cfg=new Configuration().configure(file);SessionFactory接口
-
針對(duì)單個(gè)數(shù)據(jù)庫(kù)映射關(guān)系經(jīng)過編譯后的內(nèi)存鏡像,是線程安全的
-
SessionFactory對(duì)象一旦構(gòu)造完畢,即被賦予特定的配置信息
-
SessionFactory是生成Session的工廠
-
Hibernate4新增了一個(gè)ServiceRegistry接口,所有基于Hibernate的配置或者服務(wù)都必須統(tǒng)一向這個(gè)ServiceRegisty注冊(cè)后才能生效
Session接口
Session是應(yīng)用程序與數(shù)據(jù)庫(kù)之間交互操作的一個(gè)單線程對(duì)象,是Hibernate運(yùn)作的中心,所有持久化對(duì)象都必須在session的管理下才可以進(jìn)行持久化操作。
Session對(duì)象有一個(gè)一級(jí)緩存,顯式執(zhí)行flush之前,所有的持久層操作的數(shù)據(jù)都緩存在session對(duì)象中。
總結(jié)
以上是生活随笔為你收集整理的Hibernate入门(IDEA下自动生成映射文件及实体类)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于JWT的Token认证机制实现
- 下一篇: Hibernate之Session解析