您的位置:首页 > 编程语言 > Java开发

Hibernate框架(4) —— Hibernate主配置(配置详解)

2018-03-08 20:48 399 查看

引言:Hibernate主配置文件 为hibernate.cfg.xml

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE hibernate-configuration PUBLIC
    “-//Hibernate/HibernateConfiguration DTD 3.0//EN”
    “http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd”>
    <session-factory>
        <property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
        <property name=”hibernate.connection.url”>jdbc:mysql:///hibernate</property>
        <property name=”hibernate.connection.username”>root</property>
        <property name=”hibernate.connection.password”>0516</property>
        <property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>
        <property name=”hibernate.show_sql”>true</property> 显示SQL
        <property name=”hibernate.format_sql”>true</property> 格式化SQL
        <property name=”hibernate.hbm2ddl.auto”>update</property>
 
        <mapping resource=”cn/it/domain/Customer.hbm.xml”>
</session-factory>
</hibernate-configuration> 

一、必选属性配置(5个)

1. 数据库驱动
<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
2. 数据库URL
<property name=”hibernate.connection.url”>jdbc.mysql:///hibernate_32 </property>
3. 数据库连接用户名
<property name=”hibernate.connection.username”>root </property>
4. 数据库连接密码
<property name=”hibernate.connection.password”>123 </property>
5. 数据库方言
<propertyname=”hibernate.dialect”>org.hibernate.MySQLDialect</property>

方言的作用:不同的数据库中,SQL语法略有区别,指定方言可以让hibernate框架在生成SQL语句时,针对数据库的方言生成
SQL99标准:
DDL 定义语言库表的增删改查
DCL 控制语言事务&权限
DML操纵语言增删改查
注意:选择MySQL方言的时候请选择:
org.hibernate.dialect.MySQLDialect

二、可选属性配置(3个)

1. 将hibernate自动生成的sql语句打印到控制台
<property name=”hibernate.show_sql”>true</property>
2. 将hibernate自动生成的sql语句格式化(语法缩近)
<property name=”hibernate.format_sql”>true</property>
注意:以上两个配置一般同时配置。
3. auto schema export 自动导出表结构(自动建表)
<property name=”hibernate.hbm2ddl.auto”>update</property>(推荐使用update)

作用:开发中不需要设计表结构,只要设计出实体对象,表通过实体对象反向生成。
正向设计:先设计实体,后设计表。(面向对象的角度)
反向设计:先设计表,后设计实体。

 A hibernate.hbm2ddl.auto create 自动建表 
每次框架运行都会创建新表,以前的表会被覆盖,表数据会丢失。(开发测试环境中使用)

 Bhibernate.hbm2ddl.auto    create-drop自动建表
每次框架运行结束都会将所有表删除。(开发测试环境中使用)

 Chibernate.hbm2ddl.autoupdate自动建表
如果表存在,不会再次生成,如果有变动,自动更新表。(不会删除任何数据)

 Dhibernate.hbm2ddl.autovalidate不自动生成表
校验,每次启动都会校验数据库中表是否完整,校验失败抛出异常。
 

三、元数据引入配置

<mapping resource=”cn/it/domain/Customer.hbm.xml”>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息