1. 持久化
- 俠義概念:數(shù)據存儲在物理存儲介質不會丟失回窘。
- 廣義概念:也就是對數(shù)據的crud操作都叫持久化泊业。
- 加載:hibernate里的头岔,數(shù)據從數(shù)據庫中加載到session掰盘。
2. ORM(object relation mapping)
image
解決阻抗不匹配(對象和關系數(shù)據庫不匹配)問題。
沒有侵入性:在代碼中不用去繼承hibernate類或實現(xiàn)hibernate提供接口
Hibernate:是一個orm的輕量級框架矩肩;解決持久化操作现恼,使得程序員可以從編寫繁復的jdbc工作中解放出來。專注于業(yè)務蛮拔。提高程序員開發(fā)效率述暂。移植性。
image
3. 編寫配置文件hibernate.cfg.xml文件建炫,放入到項目中src下:
<hibernate-configuration>
<session-factory>
<!-- 配置數(shù)據庫連接信息 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate4</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 設置方言,hibernate會根據數(shù)據庫的類型相應生成SQL語句 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
</session-factory>
</hibernate-configuration>
4. 創(chuàng)建數(shù)據庫表疼蛾,以及對應的pojo對象
public class User {
private int id;
private String name;
private String pwd;
}
5. 編輯*.hbm.xml文件肛跌,文件名一般為pojo類的名稱User.hbm.xml,放在pojo類所在的包下
<hibernate-mapping>
<class name="cn.siggy.pojo.User" table="user">
<id name="id">
<!-- 主鍵生成策略 -->
<generator class="native"></generator>
</id>
<!-- 實體類的屬性 -->
<property name="name"/>
<property name="pwd"/>
</class>
</hibernate-mapping>
6. 測試:將*.hbm.xml配置文件加入到hibernate.cfg.xml中
public static void main(String[] args) {
//1.新建Configuration對象
Configuration cfg = new Configuration().configure();
//2.通過Configuration創(chuàng)建SessionFactory對象
//在hibernate3.x中是這種寫法
//SessionFactory sf = cfg.buildSessionFactory();
//hibernate4.3之前~hibernate4.0
// ServiceRegistry sr = new ServiceRegistryBuilder()
// .applySettings(cfg.getProperties())
// .buildServiceRegistry();
//hibernate4.3
ServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties())
.build();
SessionFactory sf = cfg.buildSessionFactory(registry);
//或者
//SessionFactory sf = cfg.buildSessionFactory();
//3.通過SessionFactory得到Session
Session session = sf.openSession();
//4.通過session對象 得到Transaction對象
//開啟事務
Transaction tx = session.beginTransaction();
//5.保存數(shù)據
User user = new User();
user.setName("張三瘋");
user.setPwd("1111");
session.save(user);
//6.提交事務
tx.commit();
//7.關閉session
session.close();
}