通過hibernate訪問postgreSQL的搭建過程

來源:互聯網
上載者:User

標籤:dea   lis   檔案   startup   exce   resources   org   depend   查詢語句   

  1. 環境:win7,Intellij IDEA
  2. postgreSQL的安裝:
    1. 安裝包下載:https://www.postgresql.org/download/ 去官網下載postgresql-9.1.3-1-windows.exe(46M)
    2. 傻瓜式安裝,跟著安裝引導走,一路next,使用者名稱預設為 postgres,密碼*****,連接埠預設5432
    3. 啟動服務,開啟services.msc,如果postgre沒有啟動則手動啟動
  3. postgreSQL客戶的工具的安裝:目前有多種客戶工具,我用的是navicat for postgreSQL,去官網下載https://www.navicat.com/download/navicat-for-postgresql
    1. 解壓壓縮包,點擊navicat.ext啟動
    2. 雙擊串連->填寫使用者名稱,密碼,連接埠,串連名,建立串連
    3. 右鍵點擊串連名稱,建立資料庫
    4. 建立模式,(postgre的資料結構多了一層模式的結構,資料庫>模式>表>欄位),資料庫建立時有預設的模式為public,右鍵資料庫名,建立模式myschema
    5. 建立表,右鍵表,建立表,填寫欄位(user_id,username,password);
  4. 搭建hibernate環境:
    1. 用Intellij 建立javaWeb項目
    2. 引入jar包:
      1.   hibernate jar包 在pom.xml寫依賴:
        <!--hibernate--> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --> <dependency>   <groupId>org.hibernate</groupId>   <artifactId>hibernate-core</artifactId>   <version>5.1.2.Final</version> </dependency>
      2. postgreSQL jdbc jar包引入   在pom.xml中寫依賴:
        <dependency>   <groupId>postgresql</groupId>   <artifactId>postgresql</artifactId>   <version>9.1-901-1.jdbc4</version> </dependency>
    3. 配置hibernate設定檔,項目由maven管理,在resources目錄下加入hibernate.cfg.xml檔案,該設定檔主要記錄了資料庫的有戶名,ip,密碼,連接埠,所用jdbc驅動等資訊內容如下:
      <?xml version=‘1.0‘ encoding=‘utf-8‘?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "src/resource/schema/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>        <!-- Database connection settings -->        <!-- Database connection settings -->        <property name="connection.driver_class">            org.postgresql.Driver        </property>        <property name="connection.url">            jdbc:postgresql://10.21.132.19:5432/test        </property>        <property name="connection.username">postgres</property>        <property name="connection.password">88075998</property>        <!-- JDBC connection pool (use the built-in) -->        <property name="connection.pool_size">1</property>        <!-- SQL dialect -->        <property name="dialect">            org.hibernate.dialect.PostgreSQLDialect        </property>        <!-- Enable Hibernate‘s automatic session context management -->        <property name="current_session_context_class">thread</property>        <!-- Disable the second-level cache          <property name="cache.provider_class">            org.hibernate.cache.internal.NoCacheProvider        </property>-->        <!-- Echo all executed SQL to stdout -->        <property name="show_sql">false</property>        <!-- Drop and re-create the database schema on startup -->        <!-- <property name="hbm2ddl.auto">update</property> -->        <!-- <mapping resource="com/hik/gss/sys/domain/User.hbm.xml" />-->                <mapping class="model.User"></mapping>    </session-factory></hibernate-configuration>

       

  5. hibernate的查詢語句,hibernate的操作有兩種1.xml檔案配置2.註解,這裡用的是註解法,圖個方便.
    1. 實體類的定義,如下:
      package model;import org.hibernate.annotations.GenericGenerator;import javax.persistence.*;@Entity@Table(name="public.user")public class User {    private Integer userId;    private String userName;    private String passWord;    @Id    @GeneratedValue(generator="increment")    @GenericGenerator(name="increment", strategy = "increment")    @Column(name = "user_id")    public Integer getUserId() {        return userId;    }    public void setUserId(Integer userId) {        this.userId = userId;    }    @Column(name = "username")    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    @Column(name = "password")    public String getPassWord() {        return passWord;    }    public void setPassWord(String passWord) {        this.passWord = passWord;    }}


      註解說明:@Entity實體類標註,    @Table標註表名,注意表名前面要寫入模式名(public),被坑過.   @Id 表示主鍵   @Column列名  

    2. 查詢資料庫代碼Demo:
              final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()                .configure()                 .build();         SessionFactory sessionFactory = null;        try {            sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();        } catch (Exception e) {            // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory            // so destroy it manually.            StandardServiceRegistryBuilder.destroy( registry );        }        Session session = sessionFactory.openSession();        session.beginTransaction();        List result = session.createQuery( "from model.User" ).list();        for ( User user : (List<User>) result ) {            System.out.println( "User (" + user.getUserName() + ") : " + user.getPassWord() );            if (this.passWord.equals(user.getPassWord()) && this.userName.equals(user.getUserName())) {                return "SUCCESS";            }        }        session.getTransaction().commit();        session.close();


      總結一下查詢的步驟:

      1. 註冊
      2. 建立會話工廠
      3. 會話工廠生產會話
      4. 建立查詢語句
      5. 會話執行查詢語句
      6. 擷取結果

 

  

 

通過hibernate訪問postgreSQL的搭建過程

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.