今天总结一下利用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>
<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) {
Configuration cfg=new Configuration().configure();
SchemaExport export=new SchemaExport(cfg);
export.create(true, true);
}
}
至此,我们就可以连接上数据库,并且在运行程序的时候,可以在控制台中查看表的创建信息了。