ok,從這篇開始himi将與大家一起進入hibernate架構的學習啦,新手新手的說,希望大家多多指教;
對于hibernate概述一下:
” hibernate是一個開放源代碼的對象關系映射架構,它對jdbc進行了非常輕量級的對象封裝,使得java程式員可以随心所欲的使用對象程式設計思維來操縱資料庫。 hibernate可以應用在任何使用jdbc的場合,既可以在java的用戶端程式使用,也可以在servlet/jsp的web應用中使用,最具革命意義的是,hibernate可以在應用ejb的j2ee架構中取代cmp,完成資料持久化的重任。 ”
本篇則簡單介紹大家如何配置我們的第一個hibernate架構環境和第一個項目,hellohibernate;
——
準備工作:
1. himi這裡使用的一些開發資源如下:
1.1 hibernate-distribution-3.3.2.ga (hibernate核心包)
1.2 hibernate-annotations-3.4.0.ga (annotations核心包)
1.3 slf4j-1.5.8 (slf4j 實作庫,雖然hibernate核心包中有slf4j的jar包,但是隻是api包沒有實作)
1.4 mysql-connector-java-3.1.14 (mysql 驅動)
ok了,關于資源下載下傳,大家百度下,當然himi這裡用的不是最新的,剛上手怕最新的自己玩不轉~咳咳、
elipse 中user lib 配置工作:(這裡himi用的mac的eclipse)
我們添加到建立的一個 java project裡,這裡himi建立的java項目名:hellohibernate;
打開你的eclipse-偏好設定-user libraries中:
點選 new… 建立,然後輸入自定義名稱,然後添加hibernate所需的jar包,jar包一共8個如下:
1
2
3
4
5
/hibernatesoftware/hibernate-distribution-3.3.2.ga/hibernate3.jar
/hibernatesoftware/hibernate-distribution-3.3.2.ga/required/lib 下的6個jar包
/slf4j-1.5.8/slf4j-1.5.8/slf4j-nop-1.5.8.jar
如下圖:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5SOxYDe0IDMx0ichp2LcRDMvwlMxAjMvw1ckF2bsBXdvwFduVGdu92YtA3dvwVbvNmLl1WYnlWbphmL3d3dvw1LcpDc0RHaiojIsJye.png)
ok,搞定之後,然後右鍵你的項目,然後->build path->add libraries ->user library->選擇你建立的包含hibernate8個jar包的library即可;
繼續右鍵你的項目build path->add external archives 将 mysql-connector-java-3.1.14, mysql驅動導入項目中;
mysql 準備工作:
這裡himi建立一個資料庫“hibernate”,建立表“teacher”;對于mysql不太了解的,請移步到himi本部落格的mysql相關博文中學習下吧,這裡himi不再贅述了;這裡為了後續講述便于了解,himi将建立好的show出來讓大家過目下;
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
mysql> show databases;
+--------------------+
| database |
| information_schema |
| hellohibernate |
| hibernate |
| himidb |
| mysql |
| people |
| performance_schema |
| test |
8 rows in set (0.00 sec)
mysql> use hibernate;
database changed
mysql> describe teacher;
+-------+-------------+------+-----+---------+-------+
| field | type | null | key | default | extra |
| id | int(11) | no | pri | null | |
| name | varchar(20) | yes | | null | |
| age | int(11) | yes | | null | |
| gold | int(11) | yes | | null | |
4 rows in set (0.07 sec)
其中 id himi将其設定為 primary key ;
準備工作完成後,我們首先建立兩個類,一個入口函數類:
maintest:
import org.hibernate.session;
import org.hibernate.sessionfactory;
import org.hibernate.cfg.configuration;
import com.himi.teacher;
public class maintest {
/**
* @param args
*/
public static void main(string[] args) {
}
再建立一個teacher類:( pojo)ps. 不太了解pojo的請百度下先~
28
29
30
31
32
33
package com.himi;
public class teacher {
private int id;
private string name;
private int age;
private int gold;
public int getid() {
return id;
public void setid(int id) {
this.id = id;
public string getname() {
return name;
public void setname(string name) {
this.name = name;
public int getage() {
return age;
public void setage(int age) {
this.age = age;
public int getgold() {
return gold;
public void setgold(int gold) {
this.gold = gold;
整個項目目錄如下圖所示:
大家先不要在意, hibernate.cfg.xml 和 teacher.hbm.xml 這兩個檔案,下面再詳細介紹;
首先我們使用hibernate就應該先建立hibernate的配置檔案:(這裡himi采用預設此配置名為hibernate.cfg.xml,當然這個配置檔案可以自定義名但是這個名字是否采用預設将影響後面我們使用的不同,這個後面将會詳細講解到)
下面是 hibernate.cfg.xml中的内容:
34
35
36
37
38
<?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>
<!-- database connection settings 資料庫的配置 -->
<property name="connection.driver_class">com.mysql.jdbc.driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">himi</property>
<!-- jdbc connection pool (use the built-in) hibernate自帶連接配接池,暫不使用 -->
<!-- <property name="connection.pool_size">1</property> -->
<!-- sql dialect 資料庫方言,這裡我們才愛用mysql-->
<property name="dialect">org.hibernate.dialect.mysqldialect</property>
<!-- enable hibernate's automatic session context management 新功能,暫不使用 -->
<!-- <property name="current_session_context_class">thread</property> -->
<!-- disable the second-level cache 二級緩存,放置不管 -->
<property name="cache.provider_class">org.hibernate.cache.nocacheprovider</property>
<!-- echo all executed sql to stdout 設定show_sql為true表示讓hibernate将生成sql語句在控制台列印出來 -->
<property name="show_sql">true</property>
<!-- drop and re-create the database schema on startup 是否讓hibernate自動為我們建立表 -->
<!-- <property name="hbm2ddl.auto">update</property> -->
<mapping resource="com/himi/teacher.hbm.xml"/> <!-- 這裡是将需要mapping的檔案進行再次聲明 -->
</session-factory>
</hibernate-configuration>
這個配置檔案我們不要自己寫噢,去hibernate的api文檔中找到copy,然後簡單針對項目進行設定即可;
ok,配置好這個檔案其實就是對hibrenate進行的一些配置而已;
下面我們來看teacher.hbm.xml檔案:
這個檔案的目錄與teacher.java預設放置同一級目錄,約定俗成沒有什麼why;那麼這個檔案是個映射檔案,它的主要作用是告訴hibernate我們teacher類中的屬性與資料庫的哪些字段比對;ok,看下其中的内容;
(注意這個檔案,在hibernate文檔中也有例子,我們copy過來進行修改不要自己寫!)
<?xml version="1.0"?>
<!doctype hibernate-mapping public
"-//hibernate/hibernate mapping dtd 3.0//en"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.himi"><!-- 路徑 -->
<class name="teacher"> <!-- 映射的類名 -->
<id name ="id"/> <!-- 映射的資料庫primary key -->
<!-- 下面都是映射我們的其他屬性,如果你的資料庫中的字段名相同則使用以下形式-->
<property name="name"/>
<property name="age"/>
<property name="gold"/>
<!--如果你的資料庫中的字段名不相同則使用以下形式,例如:class 中 name, 資料庫為 _name
那麼書寫形式如下:
<property name="name" column="_name" />
-->
</class>
</hibernate-mapping>
ok, 映射檔案寫完之後記得要在hibernate的配置檔案(hibernate.cfg.xml)中進行聲明:
<mapping resource="com/himi/teacher.hbm.xml"/>
ok,下面我們來測試使用,打開我們的maintest.java檔案,添加内容如下:
teacher teacher = new teacher();//建立我們需要存儲的類對象,并且設定其對象的一些屬性
teacher.setid(1);
teacher.setname("himi");
teacher.setage(22);
teacher.setgold(123);
//configuration主要用以讀取配置檔案
configuration cfg = new configuration();
sessionfactory sf = cfg.configure().buildsessionfactory();
//這裡注意了,cfg.configure()讀取配置檔案的時候,如果你的hibernate的檔案名不采用預設的“hibernate.cfg.xml”的話,那麼這裡傳入你定義的配置檔案路徑
//buildsessionfactory();得到一個建立session的工場
session ss = sf.opensession();//這裡的session導入import org.hibernate.session;不要使用class經典的,因為可能會過時
ss.begintransaction();//ok,将操作放入事務中
ss.save(teacher);//儲存你的對象
ss.gettransaction().commit();//得到事務并送出
ss.close();//session關閉
sf.close();//工廠關閉
ok,運作你的man函數類,運作結果:
hibernate: insert into teacher (name, age, gold, id) values (?, ?, ?, ?)
然後檢驗一下資料庫中是否正常存入了一條資料:
mysql> select *from teacher;
+----+------+------+------+
| id | name | age | gold |
| 1 | himi | 22 | 123 |
1 row in set (0.00 sec)
噢,哈哈,看到一條 himi 資料正常添加了哈哈~
那麼這裡再說兩點:這裡給出3個運作時出現的問題;
1. 出現 “host” ‘xxx.xxx.x.xxx’ is not allowed to connect to this mysql server錯誤;
解決方法:
允許使用者從ip為192.168.1.6的主機連接配接到mysql伺服器,并使用mypassword作為密碼
grant all privileges on dk.* to 'myuser'@'192.168.1.3' identified by
'mypassword' with grant option;
flush privileges;
2. 出現 ‘xxx.xxx.x.xxx’ (using password:yes) 錯誤;
mysql中執行:
grant all on *.* to [email protected] identified by 'himi'
注意這裡by 後單引号内是電腦的user的名字;
3.可能有童鞋第一次運作正常,但是第二次運作則出現 duplicate entry ‘1’ for key ‘primary’ 錯誤;
這個問題是主健重複了的錯誤~ 因為主鍵限制: 主鍵不能為空,也不能重複 !
如果對mysql不了解的,可以先采用從mysql ,truncate 掉你table的資料,再運作就好了!或者将teacher對象的id不要與已存在資料庫中的主建id重複即可;