1. 程式人生 > >Hibernate第一個例子

Hibernate第一個例子

對象 oca hbm.xml ets form ner 讀取 連接數據庫 pass

技術分享圖片

大配置文件

<?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>
<!-- 指定數據庫所用到的驅動 -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<!-- 指定數據庫鏈接的url,hibernate鏈接的數據庫名 -->
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<!-- 指定連接數據庫的用戶名 -->
<property name="connection.username">root</property>
<!-- 指定連接數據庫的用戶口令 -->
<property name="connection.password">root</property>
<!--格式化sql -->
<property name="format_sql ">true</property>
<!-- 指定數據庫方言 -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- 根據需要自動創建數據庫表 -->
<property name="hbm2ddl.auto">update</property>
<!-- 打印sql 控制臺-->
<property name="show_sql">true</property>
<!--關聯小配置文件-->
<mapping resource="cn/sjl/entity/School.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

實體類
public class School {
private int schoolid;
private String schoolname;

public int getSchoolid() {
return schoolid;
}
public void setSchoolid(int schoolid) {this.schoolid = schoolid;}

public String getSchoolname() {
return schoolname;
}
public void setSchoolname(String schoolname) {
this.schoolname = schoolname;
}
}



小配置文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 映射文件開始 -->
<hibernate-mapping package="cn.sjl.entity">
<class name="School" table="School">
<id name="schoolid" column="schoolid">
<generator class="native"></generator>
</id>
<property name="schoolname" column="schoolname"></property>
</class>
</hibernate-mapping>


測試類
//get方法
@Test
public void test02(){
//構造Configuration對象,讀取大配置文件
Configuration cfg=new Configuration().configure();
//構造工廠
SessionFactory factory=cfg.buildSessionFactory();
//Session對象 openSession()
Session session = factory.openSession();
School school1 = session.get(School.class, 2);
System.out.println("學校名稱:"+school1.getSchoolname());
System.out.println(school1);
//關閉session
session.close();
}
 



Hibernate第一個例子