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

本文详细解析了Hibernate主配置文件hibernate.cfg.xml,包括必选的五个属性配置,如数据库驱动、URL、用户名、密码和方言,以及可选的三个属性,如显示和格式化SQL,自动建表策略。并介绍了元数据引入配置的方法。

引言: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”>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值