通过hibernate访问postgreSQL的搭建过程
- 环境:win7,Intellij IDEA
- postgreSQL的安装:
- 安装包下载:https://www.postgresql.org/download/ 去官网下载postgresql-9.1.3-1-windows.exe(46M)
- 傻瓜式安装,跟着安装引导走,一路next,用户名默认为 postgres,密码*****,端口默认5432
- 启动服务,打开services.msc,如果postgre没有启动则手动启动
- postgreSQL客户的工具的安装:目前有多种客户工具,我用的是navicat for postgreSQL,去官网下载https://www.navicat.com/download/navicat-for-postgresql
- 解压压缩包,点击navicat.ext启动
- 双击连接->填写用户名,密码,端口,连接名,创建连接
- 右键点击连接名称,创建数据库
- 创建模式,(postgre的数据结构多了一层模式的结构,数据库>模式>表>字段),数据库创建时有默认的模式为public,右键数据库名,创建模式myschema
- 创建表,右键表,创建表,填写字段(user_id,username,password);
- 搭建hibernate环境:
- 用Intellij 新建javaWeb项目
- 引入jar包:
- 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>
-
postgreSQL jdbc jar包引入 在pom.xml中写依赖:
<dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.1-901-1.jdbc4</version> </dependency>
- hibernate jar包 在pom.xml写依赖:
- 配置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.注解,这里用的是注解法,图个方便.
- 实体类的定义,如下:
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列名 - 查询数据库代码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();
总结一下查询的步骤:- 注册
- 创建会话工厂
- 会话工厂生产会话
- 创建查询语句
- 会话执行查询语句
- 获取结果
- 实体类的定义,如下: