hibernate - 第一个 hibernate 程序出错

标签 hibernate postgresql jdbc

大家好,我刚刚开始使用教程视频学习 hibernate 我完全按照导师所说的一步步完成了第一个基础程序 但是当我尝试在 Eclipse 上运行该项目时出现错误 我尝试使用不同的 hibernate.cfg.xml 文件,但对于每个文件我都会收到错误 请帮助我运行这个程序,以便我可以学习 hibernate ,因为这只是第一步,我被困在这里,我将无法继续学习

bean 类

package org.ankur.sharma.dto;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {

    @Id
    private int userId;
    private String userName;

    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }

}

主类

package org.ankur.sharma.main;

import org.ankur.sharma.dto.UserDetails;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {

    /**
     * @param args
     */
    @SuppressWarnings("deprecation")
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        UserDetails user = new UserDetails();
        user.setUserId(1);
        user.setUserName("First User");

        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();

    }

}

HIBERNATE>CFG>XML 文件

<?xml version='1.0' encoding='utf-8'?>

<hibernate-configuration
        xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
        xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration hibernate-configuration-4.0.xsd"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">org.postgresql.Driver</property>
    <property name="connection.url">jdbc:postregsql://localhost:5432/hibernatedb</property>
    <property name="connection.username">postgres</property>
    <property name="connection.password">ankur</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.HSQLDialect</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">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>
    <mapping resource="org.ankur.sharma.dto.UserDetails"/>
  </session-factory>
</hibernate-configuration>

错误

Dec 25, 2012 8:47:20 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 25, 2012 8:47:20 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Dec 25, 2012 8:47:20 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Dec 25, 2012 8:47:20 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Exception in thread "main" org.hibernate.MappingException: invalid configuration
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2018)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1935)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1914)
    at org.ankur.sharma.main.HibernateTest.main(HibernateTest.java:22)
Caused by: org.xml.sax.SAXParseException; lineNumber: 3; columnNumber: 25; Document is invalid: no grammar found.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)

尝试使用第二个配置文件

<?xml version='1.0' encoding='utf-8'?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ Copyright (c) 2010, Red Hat Inc. or third-party contributors as
  ~ indicated by the @author tags or express copyright attribution
  ~ statements applied by the authors.  All third-party contributions are
  ~ distributed under license by Red Hat Inc.
  ~
  ~ This copyrighted material is made available to anyone wishing to use, modify,
  ~ copy, or redistribute it subject to the terms and conditions of the GNU
  ~ Lesser General Public License, as published by the Free Software Foundation.
  ~
  ~ This program is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  ~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  ~ for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public License
  ~ along with this distribution; if not, write to:
  ~ Free Software Foundation, Inc.
  ~ 51 Franklin Street, Fifth Floor
  ~ Boston, MA  02110-1301  USA
  -->
<!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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postregsql://localhost:5432/hibernatedb</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">ankur</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>

        <!-- 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">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

        <!-- Names the annotated entity class -->
        <mapping class="org.ankur.sharma.dto.UserDetails"/>

    </session-factory>

</hibernate-configuration>

错误

Dec 25, 2012 8:57:01 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Dec 25, 2012 8:57:01 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.9.Final}
Dec 25, 2012 8:57:01 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 25, 2012 8:57:01 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Dec 25, 2012 8:57:01 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Dec 25, 2012 8:57:01 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Dec 25, 2012 8:57:01 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Dec 25, 2012 8:57:01 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Dec 25, 2012 8:57:01 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1
Dec 25, 2012 8:57:01 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Dec 25, 2012 8:57:01 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [org.postgresql.Driver] at URL [jdbc:postregsql://localhost:5432/hibernatedb]
Dec 25, 2012 8:57:01 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=postgres, password=****}
Dec 25, 2012 8:57:01 PM org.hibernate.engine.jdbc.internal.JdbcServicesImpl configure
WARN: HHH000342: Could not obtain connection to query metadata : No suitable driver found for jdbc:postregsql://localhost:5432/hibernatedb
Dec 25, 2012 8:57:01 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Dec 25, 2012 8:57:01 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000422: Disabling contextual LOB creation as connection was null
Dec 25, 2012 8:57:01 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Dec 25, 2012 8:57:01 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Dec 25, 2012 8:57:02 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Dec 25, 2012 8:57:02 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
ERROR: HHH000231: Schema export unsuccessful
java.sql.SQLException: No suitable driver found for jdbc:postregsql://localhost:5432/hibernatedb
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:193)
    at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:51)
    at org.hibernate.tool.hbm2ddl.DatabaseExporter.<init>(DatabaseExporter.java:52)
    at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:367)
    at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:304)
    at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:293)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:498)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1750)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1788)
    at org.ankur.sharma.main.HibernateTest.main(HibernateTest.java:21)

Dec 25, 2012 8:57:02 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Dec 25, 2012 8:57:02 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08001
Dec 25, 2012 8:57:02 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: No suitable driver found for jdbc:postregsql://localhost:5432/hibernatedb
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Could not open connection
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1395)
    at org.ankur.sharma.main.HibernateTest.main(HibernateTest.java:23)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:postregsql://localhost:5432/hibernatedb
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:193)
    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:292)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
    ... 5 more

最佳答案

您的 JDBC URL 有拼写错误:“postgresql”。

关于hibernate - 第一个 hibernate 程序出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14031933/

相关文章:

java - MySql jdbc 驱动程序加载为版本 3 而不是版本 4

java - P6Spy 不使用 HSQLDB 记录 hibernate 更新

java - 如何找出用于 hibernate 中特定查询的事务隔离级别?

java - 执行 JPA 查询时获取 NoSuchMethodError : javax. persistence.Table.indexes()

sql - 选择批处理的行

java - 如何比较三个组合框并在文本框或标签中显示结果?

java - Hibernate 中的 ClassCastException

java - 如何在服务层处理Spring JPA的版本

python - 无法在 fedora 27 上从 python3 导入 psycopg2

oracle - 编译成功后,首次调用存储过程失败。甲骨文10克