一、Hibernate配置文件常用属性
Hibernate配置文件常用属性
属性 | 功能描述 |
---|---|
hibernate.dialect | 针对不同的数据库提供不同的方言类,允许Hibernate针对特定的数据库生成优化的SQL语句 |
hibernate.connection.driver_class | 数据库驱动类 |
hibernate.connection.datasource | 数据源的JNDI名字 |
hibernate.connection.url | JNDI数据库提供者的URL |
hibernate.connection.username | 连接数据库的用户名 |
hibernate.connection.password | 连接数据库的密码 |
hibernate.connection.pool_size | 数据库连接池的最大容量 |
hibernate.show_sql | 是否输出Hibernate操作数据库使用的SQL语句 |
hibernate.format_sql | 是否格式化输出的SQL语句 |
hibernate.hbm2ddl.auto | 是否根据映射文件自动建立数据库表,该属性可以是create、create-drop和update三个值:值为create时会根据POJO创建表,但每次运行都要重新生成表;值为create-drop时,则关闭sessionFactory时,自动删除创建的表;update是最常用的属性,不会删除以前的行记录 |
二、数据库方言类
数据库方言类
Oracle 9i/10g/11g | org.hibernate.dialect.OracleDialect |
MySQL | org.hibernate.dialect.MySQLDialect |
DB2 | org.hibernate.dialect.DB2Dialect |
Microsoft SQL Server | org.hibernate.dialect.SQLServerDialect |
Sybase | org.hibernate.dialect.SybaseDialect |
三、一个基于MySQL数据库的实例
方式1:hibernate.cfg.xml
org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql:///databaseName root 123 true update
方式2:hibernate.properties
hibernate.dialect = org.hibernate.dialect.MySQLDialecthibernate.connection.driver_class = com.mysql.jdbc.Driverhibernate.connection.url = jdbc:mysql:///databaseNamehibernate.connection.username = roothibernate.connection.password = 123hibernate.show_sql = truehibernate.hbm2ddl.auto = update
由于hibernate.properties文件没有对映射文件进行配置,在Hibernate应用程序中必须调用Configuration对象的addResource()方法添加映射文件,示例代码如下:
//实例化ConfigurationConfiguration configuration = new Configuration();//添加映射文件configuration.addResource(com/qust/ssh/entities/User.hbm.xml);
方式3:xml和properties联合使用
将对映射文件的配置等属性放入hibernate.xml文件中,将数据库连接等属性放入hibernate.properties中。