SSH初体验系列--Hibernate--1--环境配置及demo

时间:2021-07-24 20:01:25

最近在学hibernate,常见的教程都是搭配mysql,因为公司本地电脑用的是pg,所以就尝试着做个pg的小demo. 自己也是边学边写,只当是加深印象.话不多说,直接开始;

一) 准备工作;

  1) 本地安装postgresql ,这个不多说,自己去网上下载;

    注: 本次使用的为pg 9.4

  2)下载pg的jdbc Driver;

    网址: 可FQ的点此下载 ,不能*的自己百度吧。

    说明一下,支持pg9.4的有4个版本,根据自己的jdk做选择:

       JDBC3 Postgresql Driver, Version 9.3-1103 ( < jdk1.6)

       JDBC4 Postgresql Driver, Version 9.4.1212 ( = jdk1.6)

       JDBC41 Postgresql Driver, Version 9.4.1212 (= jdk1.7)

       JDBC42 Postgresql Driver, Version 9.4.1212 (= jdk1.8)

  3) 下载hibernate的jar包;

    网址:FQ下载 (文件还挺大,248M);既然是学习,那就直接上最新版本: 5.2.4.Final(2016-10-26)

    解压后目录:

        SSH初体验系列--Hibernate--1--环境配置及demo

    required目录下的jar包是必须添加的( 比3.x版本的多了好多呀):

        SSH初体验系列--Hibernate--1--环境配置及demo

    意外发现在spatial目录下已经包含有pg的驱动文件了,哈哈,考虑的果然周到:

        SSH初体验系列--Hibernate--1--环境配置及demo

二) 启程;

  1) pg 创建一个用户反馈表(feedback);

    orm框架连接数据库都有两种方式:code first和db first; db first 指提前建好数据库表格,在code中写好匹配的model类进行mapping,而code first指在代码中配置好表格的相关字段信息,项目运行时,再由框架根据你的model类及配置,自动在数据库执行表格的创建及修改操作;

    如果你用db first的方式,可以用类似如下的sql语句在pg提前创建表格:

create table feedback
(
id serial not null primary key,
//serial 相当于mysql中的int auto_increment,实现的是自增长效果
username varchar(45) not null,
content varchar(200) not null,
sendtime timestamp not null
)

  2)创建数据表Feedback对应的持久化类Feedback, 及持久化类Feedback对应的映射文件Feedback.hbm.xml。需要注意的是,该映射文件与对应的持久化类应该在同一目录下。关键代码如下:

/**
* Created by c-yangx on 11/16/2016.
*/
public class Feedback { private Integer id;
private String username;
private String content;
private Timestamp sendTime; public Integer getId() { return id;} public void setId(Integer id) {this.id = id;} public String getUsername() {return username;} public void setUsername(String username) {this.username = username;} public String getContent() {return content;} public void setContent(String content) {this.content = content;} public Timestamp getSendTime() {return sendTime;} public void setSendTime(Timestamp sendTime) {this.sendTime = sendTime;} }

Feedback.java

<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="models">
<class name="models.Feedback" table="feedback" catalog="hbstudy">
<id name="id" column="id" type="java.lang.Integer">
<generator class="increment"></generator>
</id>
<property name="username" type="java.lang.String">
<column name="username" length="45" not-null="true">
<comment>反馈人</comment>
</column>
</property>
<property name="content" type="java.lang.String">
<column name="content" length="200" not-null="true">
<comment>反馈内容</comment>
</column>
</property>
<property name="sendTime" type="java.sql.Timestamp">
<column name="sendTime" length="19" not-null="false">
<comment>反馈时间</comment>
</column>
</property>
</class>
</hibernate-mapping>

Feedback.hbm.xml

  3) 创建Hibernate的主配置文件src/hibernate.cfg.xml,该文件中存放着 数据库连接驱动程序类、登陆数据库的用户名/密码、映射实体类配置文件的位置...etc.

    Hibernate在初始化时,会自动在classes路径下寻找该主配置文件,并且读取配置信息,用于后期的数据库操作;

    那么问题就来了,hinernate.cfg.xml的格式是什么呢?不要怕,你能想到的,官方也都考虑到了,直接在文件路径下搜索,ctrl+C=>ctrl+V  就是这么简单;

    SSH初体验系列--Hibernate--1--环境配置及demo

    打开文件如下,自己修改配置:

<?xml version='1.0' encoding='UTF-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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>
<property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.url">jdbc:hsqldb:.</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.region_prefix">hibernate.test</property>
<property name="hibernate.jdbc.use_streams_for_binary">true</property>
<property name="hibernate.jdbc.batch_size">0</property>
<property name="hibernate.max_fetch_depth">3</property>
<!-- 是否自动创建数据库表 他主要有一下几个值:validate:当sessionFactory创建时,
自动验证或者schema定义导入数据库。 create:每次启动都drop掉原来的schema,创建新的。 create-drop:
当sessionFactory明确关闭时,drop掉schema。update(常用):如果没有schema就创建,有就更新。 -->
<!--此处配置来实现code first-->
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="hibernate.generate_statistics">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.testing.cache.CachingRegionFactory</property>
<mapping class="org.hibernate.jpa.test.Item"/>
<mapping class="org.hibernate.jpa.test.Cat"/>
<mapping class="org.hibernate.jpa.test.Kitten"/>
<mapping class="org.hibernate.jpa.test.Distributor"/>
<class-cache class="org.hibernate.jpa.test.Item" usage="read-write"/>
<collection-cache collection="org.hibernate.jpa.test.Item.distributors" usage="read-write" region="RegionName"/>
</session-factory>
</hibernate-configuration>

  4)编写HibernateUtil.java,用于构建SessionFactory

package utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; /**
* Created by c-yangx on 11/16/2016.
*/
public class HibernateUtil {
static SessionFactory sessionFactory; //Init Hibernate
static{
try{
Configuration config=new Configuration().configure();
sessionFactory=config.buildSessionFactory();
}catch(Exception e){
String msg=e.getMessage();
e.printStackTrace();
System.out.println(msg);
}
} //Start Session
public static Session openSession(){
return sessionFactory.openSession();
}
}

HibernateUtil.java

    数据库Feedback表的操作类FeedbackDaoImpl及接口IFeedbackDao定义:

package IDao;

import models.Feedback;

/**
* Created by c-yangx on 11/16/2016.
*/
public interface IFeedbackDao {
void save(Feedback item);
}

IFeedbackDao

package dao;

import IDao.IFeedbackDao;
import models.Feedback;
import org.hibernate.Session;
import org.hibernate.Transaction;
import utils.HibernateUtil; /**
* Created by c-yangx on 11/16/2016.
*/
public class FeedbackDaoImpl implements IFeedbackDao {
@Override
public void save(Feedback item) {
Session session=null;
Transaction tx=null;
try{
session= HibernateUtil.openSession();
tx=session.beginTransaction();
session.save(item);
tx.commit();
}catch(Exception e){
tx.rollback();
e.printStackTrace();
throw new RuntimeException(e);
}finally {
session.close();
}
}
}

FeedbackDaoImpl.java

  5)最后写一个测试类Test

import dao.FeedbackDaoImpl;
import models.Feedback;
import java.sql.Timestamp; /**
* Created by c-yangx on 11/16/2016.
*/
public class Test { @org.junit.Test
public void testSave(){
Feedback newItem=new Feedback();
newItem.setUsername("Andrew");
newItem.setContent("test content one");
newItem.setSendTime(new Timestamp(System.currentTimeMillis())); FeedbackDaoImpl feedbackDao=new FeedbackDaoImpl();
feedbackDao.save(newItem);
}
}

Test

三)路途坎坷;

  项目启动运行,遇到一些bug,一起做个记录:

  a)Error msg如下;  是配置的密码有误,干脆给数据库加了一个新的role和密码

org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:267)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at utils.HibernateUtil.<clinit>(HibernateUtil.java:17)
at dao.FeedbackDaoImpl.save(FeedbackDaoImpl.java:18)
at Test.testSave(Test.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:105)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.addConnections(PooledConnections.java:123)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:42)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:20)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:161)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:109)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257)
... 38 more
Caused by: org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:443)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:217)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:52)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:216)
at org.postgresql.Driver.makeConnection(Driver.java:404)
at org.postgresql.Driver.connect(Driver.java:272)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 53 more

   b)添加账号之后,又遇到新的Bug,原来是忘了给账号配置数据库权限了,在pg端配置一下就ok了

org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
at org.hibernate.id.IncrementGenerator.initializePreviousValueHolder(IncrementGenerator.java:113)
at org.hibernate.id.IncrementGenerator.generate(IncrementGenerator.java:52)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:666)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:661)
at dao.FeedbackDaoImpl.save(FeedbackDaoImpl.java:20)
at Test.testSave(Test.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
Caused by: org.postgresql.util.PSQLException: ERROR: permission denied for relation feedback
... 35 more

四) 抵达;

  运行Test.java中的testSave方法,执行成功,再查看下数据库,数据也已成功插入;

SSH初体验系列--Hibernate--1--环境配置及demo

  最后放一个项目结构图:(说明一下,因为后续打算学习全部的ssh,所以用了个web项目)

    SSH初体验系列--Hibernate--1--环境配置及demo

后言:

  楼主也是刚开始学习java中的ssh框架,所以后面也会继续写一些hibernate的crud,Spring及struct2的文章记录自己的学习过程,并在最后整理成一个小系列.如果感兴趣,欢迎大家关注;

 大家有觉得可以优化的地方,也欢迎指正.

      

(...未完待续)

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利;

本文出自:博客园--别问是谁