【筆記——hibernate】關於Hibernate 4.3.5的初步認識

來源:互聯網
上載者:User

標籤:android   style   class   c   java   ext   

串連資料庫的一個架構,Orm架構的一種。

一、下載:http://hibernate.org/

二、配置:

1、匯入必須的包

hibernate-release-4.3.5.Final\lib\required(必須的jar)

 

如果需要時用annotataion的話,匯入:

hibernate-release-4.3.5.Final\lib\jpa(jap相關的jar)

hibernate-release-4.3.5.Final\lib\jpa-metamodel-generator(jpa產生器)

 

javaWeb放到WebContent\WEB-INF\lib目錄。

javaSe放到任意檔案夾,然後匯入構建路徑。

         2、配置hibernate.cfg.xml

                   放到src的根目錄,基本內容如下

                  

                  <?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

           <session-factory>

            <!-- JDBC串連設定 -->

            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

            <property name="connection.url">jdbc:mysql://localhost/dinnersystem</property>

            <property name="connection.username">root</property>

            <property name="connection.password">303269789</property>

            <!-- 串連池配置,使用c3p0串連池 -->

            <property name="hibernate.c3p0.max_size">20</property>

            <property name="hibernate.c3p0.min_size">1</property>

            <property name="hibernate.c3p0.timeout">1800</property>

           <property name="hibernate.c3p0.max_statements">50</property>

            <property name="hibernate.c3p0.idle_test_period">3000</property>

            <!-- 資料庫語言 -->

            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

            <!-- sql設定 -->

            <property name="show_sql">true</property>

            <property name="format_sql">true</property>

            <!-- 持久類設定所有需要持久的類要在這裡標明,以下是針對annotation注釋的類 -->

            <mapping class="com.kirning.android.entity.Test" />

            </session-factory>

</hibernate-configuration>

 

 

                   3、配置持久類

 

只存在屬性和getter/setter方法的類,其中需要在類名上加Annatation標示@Entity表示這是一個持久類。以及在id上添加@Entity,標示這是一個id對應資料庫中的關鍵字,每一個持久類都必須在hibernate.cfg.xml中進行備案,否則拋出異常,無法使用。

@Entity

public class Test {

   

           private int id;

           private String name;

           private String pass;

   

           @Id

           public int getId() {

               return id;

           }

           public void setId(int id) {

               this.id = id;

           }

           public String getName() {

              return name;

           }

           public void setName(String name) {

              this.name = name;

           }

           public String getPass() {

               return pass;

           }

           public void setPass(String pass) {

              this.pass = pass;

           }

}

 

4、如需使用log4j,則下載

apache-log4j-1.2.17         http://pan.baidu.com/share/link?shareid=121565833&uk=2047106924

slf4j-1.7.7                            http://pan.baidu.com/share/link?shareid=123250651&uk=2047106924

apache-log4j-1.2.17/log4j-1.2.17.jar

slf4j-1.7.7/slf4j-log4j12-1.7.7.jar

進入hibernate-release-4.3.5.Final\project\etc把

log4j.properties放到src根目錄即可。

三、使用

         1、擷取Session

public class HibernateUtil {

 

    private static final SessionFactory sessionFactory = buildSessionFactory();

 

    private static SessionFactory buildSessionFactory() {

       try {

 

           // 載入設定

           Configuration configuration = new Configuration().configure();

           // 建立serviceRegistry

           ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()

                  .applySettings(configuration.getProperties()).build();

           // 擷取sessionFactory

           SessionFactory sessionFactory = configuration

                  .buildSessionFactory(serviceRegistry);

           return sessionFactory;

       } catch (Throwable ex) {

           System.err.println("Initial SessionFactory creation failed." + ex);

           throw new ExceptionInInitializerError(ex);

       }

    }

 

    public static SessionFactory getSessionFactory() {

       return sessionFactory;

    }

 

}

 

                   可建立一個這樣的工具類,方便擷取Session 這是根據4.3.5官方文檔中的案例以及網上的查詢得來的結果,不知道為什麼官方的用不了,有錯誤。

         Session裡封裝著hibernate對資料庫訪問的方法,所有必需要獲得Session。

         1、儲存:

                   首先,需要執行個體化一個持久類。並使用Setter方法把資料放進去。然後調用session的save方法。

e.g:

         public class TestPost {

   

    public void test(){

       Test test = new Test();

       test.setName("test");

       test.setPass("test");

      

       //獲得Session

       Session se = HibernateUtil.getSessionFactory().openSession();

       //開始交易處理

       se.beginTransaction();

       //儲存到資料庫

       se.save(test);

       //提交事務

       se.getTransaction().commit();

    }

}

    2、查詢:

       a)、根據關鍵字查詢:

           public class TestPost {

   

    public void test(){ 

      

       //獲得Session

       Session se = HibernateUtil.getSessionFactory().openSession();

       //開始交易處理

       se.beginTransaction();

       //0是id,hibernate會根據id把資料拿出來並填充到Test類的各個屬性返回一個Object對象,強轉即可。

       Test test = (Test)se.get(Test.class, 0);

       //提交事務

       se.getTransaction().commit();

        }

}

    b)、根據關鍵字查詢

       public class TestPost {

   

        public void test(){ 

      

       //獲得Session

       Session se = HibernateUtil.getSessionFactory().openSession();     

       //關鍵字

       String key = "tom";

       //開始交易處理

       se.beginTransaction();

       //建立Criteria對象    

       Criteria cr = se.createCriteria(Test.class);

       //添加條件

       cr.add(Restrictions.eq("name", key));

       //返回結果集

       List<Test> list = cr.list();

       //提交事務

       se.getTransaction().commit();

        }

}

    c)擷取前10條資料

       public class TestPost {

   

    public void test(){ 

      

       //獲得Session

       Session se = HibernateUtil.getSessionFactory().openSession();     

       //開始交易處理

       se.beginTransaction();

       //建立Criteria對象    

       Criteria cr = se.createCriteria(Test.class);

       //這裡使用了HQL語句

       Query query = se.createQuery("from MenuTable order by id");

       query.setFirstResult(0);

       query.setMaxResults(10);

       //返回結果集

       List<Test> list = cr.list();

       //提交事務

       se.getTransaction().commit();

      

 

        }

}

 

    3、修改資料

       這個的話……先查詢出來,在儲存進去就好(*^__^*) !

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.