1.配置hibernate.cfg.xml文件(以mysql为例)。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 配置连接信息 -->
<!-- hibernate.connection.driver_class jdbc驱动类
hibernate.connection.url jdbc URL
hibernate.connection.username 数据库用户
hibernate.connection.password 数据库用户密码
hibernate.connection.pool_size 连接池容量上限数目
hibernate.dialect org.hibernate.dialect.MySQLDialect 数据库方言 -->
<session-factory>
<!-- 必选配置 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/数据库名称</property>
<property name="hibernate.connection.username">数据库账号</property>
<property name="hibernate.connection.password">数据库密码</property>
<!-- 数据库方言 使用的数据库类型 -->
<property name="hibernate.dialect org.hibernate.dialect.MySQLDialect"></property>
<!-- 可选配置 -->
<!-- 映射文件 -->
</session-factory>
</hibernate-configuration>
2.写测试类测试是否能连接数据库(引入junit4)。
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
public class TestConnection {
@Test
public void testConn() {
//读取hibernate.cfg.xml中的配置信息
Configuration config = new Configuration();
config.configure();
//获取数据库的连接池
SessionFactory factory = config.buildSessionFactory();
System.out.println(factory);
}
}
右键方法测试。