当前位置:Gxlcms > 数据库问题 > 通过hibernate访问postgreSQL的搭建过程

通过hibernate访问postgreSQL的搭建过程

时间:2021-07-01 10:21:17 帮助过:24人阅读

  • postgreSQL jdbc jar包引入   在pom.xml中写依赖:
    <dependency>   <groupId>postgresql</groupId>   <artifactId>postgresql</artifactId>   <version>9.1-901-1.jdbc4</version> </dependency>
  • 配置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>

     

  • 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的搭建过程

    标签:dea   lis   文件   startup   exce   resources   org   depend   查询语句   

    人气教程排行