您的位置:首页 > 数据库 > MySQL

hibernate连接sqlserver、mysql数据库

2017-04-19 19:45 148 查看
hibernate--一个持久层框架,是ssh三大框架中的重头戏,它取代了传统的jdbc,大大的方便了开发人员操作、切换数据库,在web开发或其他开发中发挥着重要作用。在传统的jdbc开发中,如果开发人员要切换数据库,基本上要重写dao层,特别是那些用到sql语句的代码块。下面就来看看hibernate是怎么连接sqlserver、mysql数据库的:

1、hibernate连接sqlsever:

<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=testDB</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">zwr2016</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>


2、hibernate连接mysql:

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testDB</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>


说明:(1)hibernate.connection.driver_class:数据库驱动,大家在连接数据库的时候,一定记得把对应的数据库驱动包导入到项目中,无论是用hibernate开发,还是用传统的jdbc开发,都必须要导入驱动包,且不同的数据库对应的驱动包是不同的,否则是连接不上数据库的;

(2)hibernate.connection.url:这句话的作用有2个,一要连接哪个机器上的数据库,分为本地和远程(只要你知道远程机器的ip、账号和密码,也可以连接远程机器上的数据库);二要连接该机器上的哪个数据库;

(3)hibernate.connection.username:数据库的账号;

(4)hibernate.connection.password:数据库的密码;

(5)hibernate.dialect:方言。这个就给大家好好解释一下:每种数据库(常用的就是sqlserver、mysql、oracle)的大部分语法都是符和sql规范的,但是为了提升性能、增加功能,每种数据库又做了拓展,这些拓展是每种数据库私有的,也就是说这些拓展是不符合sql规范的。因此,hibernate为了适配各种数据库,为每种数据库指定了一个方言dialect。其实,在hibernate里面,方言只是一个类,它将你写的那些HQL、QBC等等,翻译成对应数据库能识别的SQL。没有对应的dialect,Hibernate是无法操作数据库的。

总结,无论hibernate连接哪种数据库,都是5点配置,其中方言是重点,同时要记得把对应的数据库驱动包导入到项目中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息