Hibernate基础(一)——连接数据库,并导出表

今天总结一下利用hibernate如何来进行数据库的连接。其实总的来说,利用任何技术,连接数据库无非就那么几个步骤。1、写好配置文件
 2、配置文件的读取 3、连接 
如今,在hibernate上也离不开这三步。通过hibernate再回顾一下这些最基础的技术。在此之前,要将hibernate所需要的各种Lib进行引用,
这里用的是mysql,所以也要引入mysql的数据库驱动。

一、配置文件编写

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory >
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>    
        <!--User表的映射文件-->   
        <mapping resource="com/bjpowernode/hibernate/User.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

二、配置文件的读取

    1、如果直接new Configuration 默认读取的是hibernate.properties 文件
    2、new Configuration().configure() 读取的才是hibernate.cfg.xml 文件,
    3、如果修改文件名,以构造函数的方式将文件名作为参数写入即可
package com.bjpowernode.hibernate;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class ExportDB {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //如果直接new Configuration 默认读取的是hibernate.properties 文件
        //new Configuration().configure() 读取的才是hibernate.cfg.xml 文件,
        //如果修改文件名,以构造函数的方式将文件名作为参数写入即可
        Configuration cfg=new Configuration().configure();

        SchemaExport export=new SchemaExport(cfg);
        //export.create在这里生成ddl文件,并在控制台输出。
        export.create(true, true);

    }

}
    至此,我们就可以连接上数据库,并且在运行程序的时候,可以在控制台中查看表的创建信息了。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值