Java 使用 Hibernate 调用 Driver#connect 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22441076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:44:34  来源:igfitidea点击:

"Error calling Driver#connect" using Hibernate

javahibernate

提问by

This is my cfg.xml file:

这是我的 cfg.xml 文件:

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=hiber;</property>
    <property name="connection.username">Costi-PC\Costi</property>
    <property name="connection.password"></property>

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

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.SQLServerDialect</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="model.User" />

User class and Main class:

用户类和主类:

@Entity
    public class User {

        @Id
        private int userId;
        private String userName;

        public int getUserId() {..}
        public void setUserId(int userId) {..}
        public String getUserName() {..}
        public void setUserName(String userName) {..}

    }

    public class Main {

        public static void main(String[] args) {
           User user = new User();
           user.setUserId(1);
           user.setUserName("Costi");

           AnnotationConfiguration configuration = new AnnotationConfiguration();
           configuration.configure();

           SessionFactory sessionFactory = configuration.buildSessionFactory();

           Session session = sessionFactory.openSession();
           session.beginTransaction();
           session.save(user);
           session.getTransaction().commit();
           session.close();

           sessionFactory.close();

}

When I run the program i get this error:

当我运行程序时,我收到此错误:

Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:132)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convert(BasicConnectionCreator.java:118)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
    at main.Main.main(Main.java:23)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
    at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:241)
    at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
    at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1309)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
    at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
    ... 14 more

I'm using sql server 2008. I tried different types of cfg configuration but none seems to work. I believe the problem is from connection.url. I tried to change the port (1433) but nothing. Can anyone tell what's the problem ?

我使用的是 sql server 2008。我尝试了不同类型的 cfg 配置,但似乎都不起作用。我相信问题来自 connection.url。我试图更改端口 (1433) 但什么也没有。谁能告诉我有什么问题?

回答by Angular University

Try going to the command line and see if sqlserver is indeed listening to that port. On windows this would be the command:

尝试转到命令行并查看 sqlserver 是否确实在侦听该端口。在 Windows 上,这将是命令:

netstat -nao | findstr 1433

Then see if the PID is Sql Server as expected in the windows (Ctr+Alt+Delete) process list.

然后在windows(Ctr+Alt+Delete)进程列表中查看PID是否为Sql Server,如预期。

If the server is running, try to connect to it using a SQL client GUI, see here for examples. When you can connect to the database from an external client successfully, try again from the Java program.

如果服务器正在运行,请尝试使用 SQL 客户端 GUI 连接到它,请参见此处的示例。当您可以从外部客户端成功连接到数据库时,请从 Java 程序中重试。

Try to see also if your local firewall settings to see if the firewall is the cause for the error, although by default firewalls do not block localhost - have a look at this answer.

还尝试查看您的本地防火墙设置是否是防火墙导致错误的原因,尽管默认情况下防火墙不会阻止 localhost - 看看这个答案

回答by Abhijit Patra

Check you Sid in

检查你 Sid

hibernate.cfg.xml file

hibernate.cfg.xml 文件

For Oracle Express Edition:

对于 Oracle 快捷版:

<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>

For Oracle Enterprise Edition:

对于 Oracle 企业版:

<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> 

回答by Marco de Boer

I know this post is almost 2 years old, but for me the questions gave me, for me, the right answer. And because people with the same question are getting this post from Google. I thought, lets add my story.

我知道这篇文章已经快 2 年了,但对我来说,这些问题给了我正确的答案。因为有同样问题的人是从谷歌那里得到这篇文章的。我想,让我们添加我的故事。

Same thing, same problem. And for me the answer was that SQL Server didn't accept connections from the outside. The tcp/ip network client configuration is standard disabled.

同样的事情,同样的问题。对我来说,答案是 SQL Server 不接受来自外部的连接。tcp/ip 网络客户端配置是标准禁用的。

So it was for me a hint in the right direction.

所以这对我来说是一个正确方向的提示。

回答by Omid

the error is due to AnnotationConfiguration and making session by it. you can try this solution:

错误是由于 AnnotationConfiguration 并通过它进行会话。你可以试试这个解决方案:

@Autowired
SessionFactory sessionFactory;
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(ce);

回答by dhiraj kakran

Use This with all Permission of DB

在 DB 的所有权限下使用它

 <property name="hibernate.connection.url">jdbc:mysql://ip:3306/dbname</property><property name="hibernate.connection.username">*******</property>
     <property name="hibernate.connection.password">*******</property> 

回答by Susheel Dwivedi

I also face same problem due to some dependency issue. i solve my problem to change sql depenedency which is compatible to my current version of sql server in pom.xml file.

由于某些依赖性问题,我也面临同样的问题。我解决了我的问题,以更改与 pom.xml 文件中我当前版本的 sql server 兼容的 sql 依赖。

回答by Otto M.

I had a same error when migrating from jTDS1.2.8 to mssql-jdbc and for me it helped removing the port number and specifying the named instance in the connection URL within hibernate.cfg.xml

从 jTDS1.2.8 迁移到 mssql-jdbc 时我遇到了同样的错误,对我来说它有助于删除端口号并在 hibernate.cfg.xml 中的连接 URL 中指定命名实例

From:

从:

<property name="hibernate.connection.url">jdbc:sqlserver://MYHOSTNAME:1433;databaseName=mydbname;instanceName=MYINSTANCENAME;</property>

To:

到:

  <property name="hibernate.connection.url">jdbc:sqlserver://MYHOSTNAME;instanceName=MYINSTANCENAME;databaseName=mydbname;</property>

Reference: https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-2017

参考:https: //docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-2017

When using Named and Multiple SQL Server Instances, to use a JDBC URL property, do the following:

使用命名和多个 SQL Server 实例时,要使用 JDBC URL 属性,请执行以下操作:

jdbc:sqlserver://localhost;instanceName=instance1;integratedSecurity=true;<more properties as required>;

回答by H0ZC4RD

if you are using a virtual server or server that is not updated the time zone should update it.

如果您使用的是未更新的虚拟服务器或服务器,则时区应更新它。

SQL CONSOLE:

SQL 控制台:

SET GLOBAL time_zone = '+3:00';

回答by Sadina Khatun

I have Faced Same issue just i have changed the Version on mysql server connector than works fine

我遇到了同样的问题,只是我更改了 mysql 服务器连接器上的版本,但工作正常

    <!-- commented as it was not make to connect 
       <dependency> 
          <groupId>mysql</groupId> 
          <artifactId>mysql-connector-java</artifactId> 
          <version>5.1.34</version> 
       </dependency> 
   -->

added latest version of mysql connector

添加了最新版本的 mysql 连接器

   <!-- added latest version of mysql connector -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.18</version>
            </dependency>

回答by Sasha S

Wrong username or a password in a config hibernate file "hibernate.cfg.xml"

配置休眠文件“hibernate.cfg.xml”中的用户名或密码错误