我正在尝试使用 hibernate 连接到数据库,我已阅读文档和用户协会,但仍然无法连接到数据库。 我采取的步骤:
- 将所有相关的 hibernate jar 和 sqljdbc41.jar(sql server jdbc 驱动程序)添加到我的项目中。
- 将包含以下
sqljdbc_auth.dll
(x64) 的 xml 添加到环境路径。 使用以下连接和方言创建了名为
hibernate.cfg.xml
的 xml:<!-- Database connection settings --> <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> <property name="hibernate.connection.url">"jdbc:sqlserver://localhost;databaseName=ForumSystem;integratedSecurity=true;"</property> <!-- SQL dialect --> <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
如您所见,我的服务器是本地的,并且我正在使用 Windows 身份验证,而且我也没有更改默认实例和端口。
我尝试使用以下代码连接到数据库:
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
我收到以下错误:
Exception in thread "main" org.hibernate.HibernateException: Unable to make JDBC Connection ["jdbc:sqlserver://SHPERB;databaseName=ForumSystem;integratedSecurity=true;"]
我尝试修改连接 URL 以包含端口和实例名称,并且还尝试在没有 Windows 身份验证的情况下进行连接,但没有取得任何进展。
我是不是错过了什么?有没有办法知道哪个参数是错误的?
编辑:忘记提及在 SQL 服务器配置中启用了 TCP\IP,并且我在数据库中允许 Windows 身份验证和 SQL 身份验证。 如果我尝试使用以下方式连接:
String connectionUrl = "jdbc:sqlserver://SHPERB;database=ForumSystem;integratedSecurity=true;";
Connection con = DriverManager.getConnection(connectionUrl);
它可以工作,但不使用 hibernate
最佳答案
尝试在您的网址中添加jdbc:microsoft:sqlserver
。您需要为 Microsoft SQL JDBC 驱动程序指定驱动程序。查看更多
Connecting to MS sql through hibernate和 how to configure hibernate config file for sql server
同时检查是否设置了自定义端口并将其添加到连接参数中。
关于java - 使用 hibernate 连接到数据库 - 连接 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29800226/