hibernate架構搭建與使用

來源:互聯網
上載者:User

標籤:個數   顯示   get   建議   logs   sql   blog   查詢   nat   

一、匯入jar包。
1.hibernate的jar包,hibernate-release-5.2.6.Final\lib\required中所有的jar

2.jdbc的jar包,用那個資料庫就使用哪個資料庫的jar包,這裡使用的是mysql資料庫

 

二、配置Hibernate。建立hibernate.cfg.xml檔案

1.hibernate.cfg.xml -- 包所在的檔案夾的project裡去搜尋複製

2.每個配置項的值:project/etc/hibernate.properties中搜尋

<hibernate-configuration>    <session-factory>        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>   <!-- mysql的方言 -->        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>        <property name="hibernate.connection.username">root</property>        <property name="hibernate.connection.password"></property>        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=GBK</property>        <property name="show_sql">true</property>     <!-- 是否在控制台列印sql語句 -->        <!-- 表映射載入 -->        <mapping resource="com/itnba/maya/bean/Fruit.hbm.xml"/>    </session-factory></hibernate-configuration>

三、準備資料庫(relation關係型資料庫),這裡在mysql資料庫中用mydb資料庫中Fruit表。

四、準備實體(object記憶體中的對象,建議使用:參考型別。建議類名屬性名稱與列名一致),建立一個類Fruit,產生get,set方法。

 

五、準備對應檔(mapping映射) 實體類名.hbm.xml 例:Fruit.hbm.xml ,一個實體類對應一個對應檔。
方法:從project檔案夾中搜尋hbm.xml。複製改

完成對應檔後,記住!!在hibernate.cfg.xml下,加上<mapping resouse="對應檔路徑"/>映射

六、寫代碼
說明:這裡的session不是web中的session.
web中的session代表的是用戶端與web伺服器之間的會話
這裡的session指的是程式與資料庫之前的會話,它是由hibernate進行管理的。

在控制台列印一下,測試是否成功,顯示true則成功。

 

串連成功後就可以進行增刪改查的操作

一、添加

  

結果顯示:

 

在資料庫中查看:

 二、查詢

1.查詢單個

結果顯示:第一行是執行sql的,第二行是查詢的內容

2.查所有的

結果顯示:

 3.刪除

執行完語句,在去資料庫查看,

原本f001西瓜 那一條資料已經刪除

4.修改

執行完語句後去資料庫查看

聖女果的price和numbers分別改為了1和500

 

hibernate架構搭建與使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.