一、環境準備
下載hibernate-distribution-3.3.2.GA-dist
下載hibernate-annotations-3[1].4.0.GA
二、創建第一個Hibernate程序
1)新建一個javaproject,導入hibernate需要的jar包:
i. hibernate core
ii. /required
iii. slf4j-nop jar(注意要和/required目錄下的slf4j-api版本相對應 )
2)引入MySQL的JDBC驅動,在mysql中建立對應的數據庫以及表
a) create database hibernate;
b) use hibernate;
create table Student (id int primary key,namevarchar(20), age int);
3)建立hibernate配置文件hibernate.cfg.xml
在hibernate的文檔中有對應的模版,將其複製下來,並修改成如下配置:
<?xmlversion='1.0'encoding='utf-8'?>
<!DOCTYPEhibernate-configurationPUBLIC
"-//Hibernate/Hibernate Configuration DTD3.0//EN"
"http://hibernate.sourceforge.NET/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<propertyname="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<propertyname="connection.url">
jdbc:mysql://localhost/hibernate
</property>
<propertyname="connection.username">root</property>
<propertyname="connection.password">123</property>
<!-- JDBC connection pool (use thebuilt-in) -->
<!-- <propertyname="connection.pool_size">1</property> -->
<!-- SQL dialect -->
<propertyname="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automaticsession context management -->
<!-- <propertyname="current_session_context_class">thread</property>-->
<!-- Disable the second-level cache -->
<propertyname="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Echo all executed SQL to stdout -->
<propertyname="show_sql">true</property>
<!-- Drop and re-create the databaseschema on startup -->
<!-- <propertyname="hbm2ddl.auto">create</property> -->
<!-- <propertyname="myeclipse.connection.profile"></property> -->
<mappingresource="com/xuhaibin/hibernate/model/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<mapping> 要設置成對應的映射文件
4)建立Student的映射文件student.hbm.xml
參考文檔中的示例映射文件,修改成如下內容:
<?xmlversion="1.0"?>
<!DOCTYPEhibernate-mappingPUBLIC
"-//Hibernate/Hibernate Mapping DTD3.0//EN"
"http://hibernate.sourceforge.Net/hibernate-mapping-3.0.dtd">
<hibernate-mappingpackage="com.xuhaibin.hibernate.model">
<classname="Student">
<idname="id"/>
<propertyname="name"/>
<propertyname="age"/>
</class>
</hibernate-mapping>
5)在com.xuhaibin.hibernate.model包下建立相應的Student類,生成get,set方法
6)建立測試類StudentTest內容如下:
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import com.xuhaibin.hibernate.model.Student;
- public class StudentTest {
- public static voidmain(String[] args){
- Student s = new Student();
- s.setId(1);
- s.setName("s1");
- s.setAge(1);
- Configuration cfg = newConfiguration();
- SessionFactory sf =cfg.configure().buildSessionFactory();
- Session session =sf.openSession();
- session.beginTransaction();
- session.save(s);
- session.getTransaction().commit();
- session.close();
- sf.close();
- }
- }
三、使用annotation建立Teacher類,@Entity註解實體,@id註解主鍵