Access to PostgreSQL's build process through hibernate

Source: Internet
Author: User
Tags postgresql

  1. Environment: Win7,intellij idea
  2. Installation of PostgreSQL:
    1. installation package Download: https://www.postgresql.org/download/to download Postgresql-9.1.3-1-windows.exe (46M)
    2. Fool installation, follow the installation guide go, all the way next, the user name defaults to postgres, password * * * *, port default 5432
    3. Start the service, open services.msc, and start manually if Postgre does not start
  3. Installation of PostgreSQL customer tools: There are a number of customer tools, I use Navicat for PostgreSQL, go to the official website to download Https://www.navicat.com/download/navicat-for-postgresql
    1. Unzip the tarball and click Navicat.ext to start
    2. Double-click Connect, fill in user name, password, port, connection name, create connection
    3. Right click on the connection name to create the database
    4. Create schema, (Postgre data structure is a layer of schema structure, database > Mode > Table > Field), the database is created with default mode of public, right-click database name, CREATE schema MySchema
    5. Create tables, right-click Tables, create tables, fill fields (User_id,username,password);
  4. Build Hibernate Environment:
    1. Create a new Javaweb project with IntelliJ
    2. To introduce a jar package:
      1. Hibernate jar package in Pom.xml write dependent:
          <groupid>org.hibernate  <artifactid>hibernate-core <version>5.1.2.final</ dependency>  
      2. The PostgreSQL JDBC Jar package introduces   write dependencies in Pom.xml:
          <groupid>postgresql  <artifactid>postgresql <version>9.1-901-1.jdbc4</ dependency>  
    3. Configure Hibernate profile, the project is managed by MAVEN, in the Resources directory to add the Hibernate.cfg.xml file, the configuration file mainly records the database of the user name, IP, password, port, the use of the JDBC driver and other information content as follows:
      <?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 -        < Propertyname= "Connection.driver_class">Org.postgresql.Driver</ Property>        < Propertyname= "Connection.url">jdbc:postgresql://10.21.132.19:5432/test</ Property>        < Propertyname= "Connection.username">Postgres</ Property>        < Propertyname= "Connection.password">88075998</ Property>        <!--JDBC Connection pool (use the built-in) -        < Propertyname= "Connection.pool_size">1</ Property>        <!--SQL dialect -        < Propertyname= "dialect">Org.hibernate.dialect.PostgreSQLDialect</ Property>        <!--Enable Hibernate ' s automatic session context management -        < Propertyname= "Current_session_context_class">Thread</ Property>        <!--Disable the Second-level cache <property name= "Cache.provider_class" > Org.hibernate.cache.i Nternal. Nocacheprovider </property> -        <!--Echo all executed SQL to stdout -        < Propertyname= "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"/> -                <Mappingclass= "model. User "></Mapping>    </session-factory></hibernate-configuration>

  5. Hibernate query statement, hibernate operation has two 1.xml file configuration 2. Note, here is the annotation method, the diagram is convenient.
    1. The definition of the entity class is as follows:
       Packagemodel;ImportOrg.hibernate.annotations.GenericGenerator;ImportJavax.persistence.*;@Entity @table (name= "Public.user") Public classUser {PrivateInteger userId; PrivateString UserName; PrivateString PassWord; @Id @GeneratedValue (Generator= "Increment") @GenericGenerator (name= "increment", strategy = "increment") @Column (name= "USER_ID")     PublicInteger getUserId () {returnuserId; }     Public voidSetuserid (Integer userId) { This. UserId =userId; } @Column (Name= "username")     PublicString GetUserName () {returnUserName; }     Public voidsetusername (String userName) { This. UserName =UserName; } @Column (Name= "Password")     PublicString GetPassword () {returnPassWord; }     Public voidSetPassword (String passWord) { This. PassWord =PassWord; }}


      Note Description: @Entity entity class callout, @Table label table name, notice the name of the table before the name of the write mode (public), was the pit. @Id represents the primary key @Column column name

    2. Query Database Code Demo:
              FinalStandardserviceregistry Registry =Newstandardserviceregistrybuilder (). Configure (). Build (); Sessionfactory sessionfactory=NULL; Try{sessionfactory=Newmetadatasources (registry). Buildmetadata (). Buildsessionfactory (); } Catch(Exception e) {//the registry would is 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 ();


      Summarize the steps of the query:

        1. Registered
        2. To create a session factory
        3. Session Factory production session
        4. Create a query statement
        5. Session Execution Query statement
        6. Get results

  

Access to PostgreSQL's build process through hibernate

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.