(1)創建一個實體類User
(2)將hibernate所需jar包構建項目中
MySQL驅動
hibernate3.jar
lib/required/所有jar文件
lib/jpa/jar文件
(3)配置文件
hibernate.cfg.xml
hibernate.properties
驅動、url、用戶名、密碼、方言、自動創建表格、將hibernate工作過程中產生的sql語句輸出
以及映射文件的位置
<hibernate-configuration>
<session-factory>
<propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<propertyname="connection.url">jdbc:mysql:///demo</property>
<propertyname="connection.username">root</property>
<propertyname="connection.password">123</property>
<propertyname="dialect">org.hibernate.dialect.MySQLDialect</property>
<propertyname="hibernate.hbm2ddl.auto">create</property>
<propertyname="hibernate.show_sql">true</property>
<mappingresource="com/hbsi/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
(4)映射文件---
User---- User.hbm.xml
<hibernate-mapping
package="com.hbsi.domain"> -----指定Java實體類的包名
<classname="User" table="user"> -----說明實體類怎樣映射成表
<idname="id">
<generatorclass="native"/>
</id>
<propertyname="name"/>
<propertyname="birthday"/>
</class>
</hibernate-mapping>
(5)寫Java代碼
Configuration cfg=new Configuration();
cfg.configure();//完成hibernate的初始化--讀取配置文件
//SessionFactory對象----DriverManager
SessionFactory sf=cfg.buildSessionFactory();
//得Session對象
Session s=sf.openSession();
Transaction tx=s.beginTransaction();
User user=new User();
user.setName("Tom");
user.setBirthday(new Date());
s.save(user);
tx.commit();
s.close();
可能出現問題:
(1)驅動找不到
(2)unknown entity:不認識User實體類。原因在配置文件沒有指明映射文件所在位置
<mappingresource="com/hbsi/domain/User.hbm.xml"/>
(3)Table“demo.user” doesnot exist:
create table user(
id int auto_increment;
name varchar(20);
birthday date;
);
在配置文件增加配置:
<propertyname="hbm2ddl.auto">create</property>
create-drop:在hibernate初始化時創建表,程序運行結束時表會被刪除
create:在hibernate初始化時會創建表格。
update:只是根據映射文件去和數據庫中的表對應起來,如果不一致就更新表結構
validate:校驗映射文件和數據庫中的表是不是能夠對應起來,不能對應不更新表,會報錯。
(4)表建好,表格中沒有記錄。
insert s.save(user)
<propertyname="show_sql">true</property>
事務
Transaction tx=s.beginTransaction();
...
tx.commit();
MyISAM
InnoDB