hibernate是一個開源的對象關係映射架構,它對jdbc進行了輕量級的對象封裝,使用它我們可以使用對象編程思想來操作資料庫,事實上,在java世界,它已成了ORM架構的代表。下面就一起來學習下hibernate。
一、擷取hibernate。從https://www.hibernate.org/網站上可以擷取到最新版本的hibernate和相關文檔,筆記的例子使用了3.2.5。
二、快速上手。
1、開啟myEclipse,建立一個java project,匯入hibernate及JDBC相關jar包,就可以配置開發hibernate應用了。註:JDBC包是必需的,且需與資料對應,筆者使用的是mysql5.0資料庫。
2、配置hibernte。在src目錄下建立一個xml檔案,名稱為hibernate.cfg.xml(當然,你也可以不叫這個名稱,不過在代碼中要作相應的修改),拷貝如下內容:
代碼<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory >
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="com/eja/hibernate/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3、建立一個實體類,User.java.為了方便,只有一個屬性,就是name,如:
代碼package com.eja.hibernate.domain;
import java.util.Date;
public class User {
private int id;
private String name;
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;
}
}
4、建立好實體類後,配置對應的xml檔案。如下:
代碼<?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.eja.hibernate.domain">
<class name="User" >
<id name="id">
<generator class="native" />
</id>
<property name="name"/>
</class>
</hibernate-mapping>
好。配置已經好了。測試一下效果。增加junit,編寫如下測試類別。
代碼package com.eja.hibernate.Test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.eja.hibernate.domain.User;
public class TestUser {
@Test
public void addUser() {
try {
Configuration cfg = new Configuration();
cfg.configure(); //如果配置的不是hibernate.cfg.xml。則需在此方法中引入
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = sessionFactory.openSession();
User user = new User();
user.setName("name");
session.save(user);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
點擊jnuit就可以測試了。