hibernate配置并测试是否可以连接数据库

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);
	}
}
右键方法测试。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值