hibernate連接數據庫的步驟


三個准備


一.導包   mysql
二.在默認src下創建hibernate.cfg.xml  

1.創建xml文件,命名為hibernate.cfg.xml

2.添加約束
   (在org.hibernate/hibernate-configuration-3.0.dtd中)

1   <!DOCTYPE hibernate-configuration PUBLIC
2   "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
3   "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 

<hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/houserentsys</property> <!-- houserentsys是數據庫名稱 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="show_sql">true</property> <property name="format_sql">false</property> <!-- 設置為false就會不換行 --> <property name="hbm2ddl.auto">update</property> <!-- 進行操作時不會刪除重建--> <!--hbm2ddl.auto屬性:
   
create:表示啟動的時候先drop,再create
   c
reate-drop: 也表示創建,只不過再系統關閉前執行一下drop
   
update: 這個操作啟動的時候會去檢查schema是否一致,如果不一致會做scheme更新
   
validate: 啟動時驗證現有schema與你配置的hibernate是否一致,如果不一致就拋出異常,並不做更新
-->
<mapping resource="edu/tsinghua/entity/mapping/district.xml"/> <mapping resource="edu/tsinghua/entity/mapping/street.xml"/> </session-factory> </hibernate-configuration>

 

  hbm2ddl.auto屬性:
   create:表示啟動的時候先drop,再create
   create-drop: 也表示創建,只不過再系統關閉前執行一下drop
   update: 這個操作啟動的時候會去檢查schema是否一致,如果不一致會做scheme更新
   validate: 啟動時驗證現有schema與你配置的hibernate是否一致,如果不一致就拋出異常,並不做更新

三.實體  實現序列化接口  封裝屬性和構造方法    實體.xml  位置隨意
   (在org.hibernate/hibernate-mapping-3.0.dtd中)
   <!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     在hibernate.cfg.xml 添加 映射文件的引用
   <mapping resource="edu.tsinghua.entity.mapping.district"/>
七個步驟(在新建的執行文件Test.java中)
  //1.加載配置文件
  Configuration cfg=new Configuration().configure();
  //2.獲得sessionfactory
  ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
  SessionFactory sf=cfg.buildSessionFactory(serviceRegistry);
  //3.創建session
  Session session=sf.openSession();
  //4.創建事務
  Transaction tx=session.beginTransaction();
  //5.操作
  District dis=new District(100,"海淀區");
  session.save(dis);
  //6.提交 回滾
  tx.commit();//tx.rollback();
  //7.釋放資源
  session.close();
  sf.close();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM