這里是以我的Mysql為例子
<?xml version="1.0" encoding="UTF-8"?>
<!--?* 默認(rèn)的命名規(guī)則為:實(shí)體類名.hbm.xml
? ? * 在xml配置文件中引入約束(引入的是hibernate3.0的dtd約束而线,不要引入4的約束) -->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!--?先配置SessionFactory標(biāo)簽砌梆,一個數(shù)據(jù)庫對應(yīng)一個SessionFactory標(biāo)簽 -->
????<session-factory>
????????<!--?必須配置的5個參數(shù):4個參數(shù)和1個數(shù)據(jù)庫方言-->
????????<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
????????<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_day01</property>
????????<property name="hibernate.connection.username">root</property >
????????<property name="hibernate.connection.password">123</property >
????????<!--?數(shù)據(jù)庫方言-->
????????<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
????????<!-- 可選配置-->
????????<property name="hibernate.show_sql">true</property><!-- 顯示sql語句-->
????????<property name="hibernate.format_sql"> true</property><!--格式化顯示sql語句i-->
????????<property name="hibernate.hbm2ddl.auto">update</property><!-- 如果沒有表結(jié)構(gòu)航棱,會更新(添加)數(shù)據(jù)表結(jié)構(gòu),并更新數(shù)據(jù),但不會刪除原有表結(jié)構(gòu)(只能添加/更新第岖,不能刪除); 如果有表結(jié)構(gòu),不會創(chuàng)建數(shù)據(jù)表結(jié)構(gòu)吃靠,但會添加數(shù)據(jù)
,如果要修改表結(jié)構(gòu)足淆,需要在數(shù)據(jù)庫中手動修改表結(jié)構(gòu) -->
????????<!-- 開發(fā)時巢块,update用的多 -->
????????<property name="hibernate.hbm2ddl.auto">validate</property>
????????<!--校驗(yàn)javaBean屬性與數(shù)據(jù)庫字段是否匹配 -->
????????<!-- 映射配置文件,需要引入映射的配置文件(按ctrl+左鍵點(diǎn)擊巧号,能跳轉(zhuǎn)族奢,則引入成功) -->
????????<mapping resource="domain/customer.hbm.xml" />
????</session-factory>
</hibernate-configuration>
編寫Hibernate入門代碼
/**
* 測試保存客戶
*/
@Test
public void testSave() {
// 1 先加載配置文件
//? ? ? ? Configuration config=new Configuration();
? ? ? ? // 2 默認(rèn)加載src目錄下的配置文件
//? ? ? ? config.configure();//如果使用的是xml文件,必須執(zhí)行這個方法丹鸿。如果使用的是屬性文件越走,可以不用執(zhí)行這個方法
//? ? ? ? config.addResource("domain/customer.hbm.xml");//如果xml里沒寫映射配置文件,則要手動添加映射配置文件
? ? ? ? Configuration config=new Configuration().configure();//上面幾行的簡寫代碼(方法鏈的編程)
? ? ? ? // 3 創(chuàng)建SessionFactory對象
? ? ? ? SessionFactory factory=config.buildSessionFactory();
? ? ? ? // 4 創(chuàng)建session對象
? ? ? ? Session session =factory.openSession();
? ? ? ? // 5 開啟事務(wù)
? ? ? ? Transaction tr=session.beginTransaction();
? ? ? ? // 6 編寫保存代碼
? ? ? ? Customer c=new Customer();
? ? ? ? c.setCust_name("IamCc10");
? ? ? ? c.setCust_level("10");
? ? ? ? // c.setCust_id(cust_id);? 已經(jīng)自動遞增
? ? ? ? // 7 保存客戶
? ? ? ? session.save(c);
? ? ? ? // 8 提交事務(wù)
? ? ? ? tr.commit();
? ? ? ? // 9 釋放資源
? ? ? ? session.close();
? ? ? ? factory.close();
}