Learning Hibernate step by step -- 00 搭建环境
最近开始学习Hibernate,做一个学习笔记(好脑子不如烂笔头嘛!),以备将来回顾查阅之用。
一、准备工作:
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory name="foo"> <!-- 方言 --> <property name="hibernate.dialect org.hibernate.dialect">MySQLInnoDBDialect</property> <!-- 驱动包 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 数据库连接url jdbc:mysql:///test<==>jdbc:mysql:/localhost/3306/test --> <property name="hibernate.connection.url">jdbc:mysql:///test</property> <!-- 用户名 --> <property name="hibernate.connection.username">root</property> <!-- 密码 --> <property name="hibernate.connection.password">*******</property> </session-factory> </hibernate-configuration>
5. 编写一个简单的测试程序,测试是否可以正常连接数据库:
public class TestConnection { public static void main(String[] args) { if(test()) { System.out.println("数据库连接成功!"); } else { System.out.println("数据库连接失败!"); } } public static boolean test() { Configuration cfg = new Configuration(); cfg.configure(); SessionFactory sessionFactory = cfg.buildSessionFactory(); try { Session session = sessionFactory.openSession(); if(session == null) { return false; } else { session.close(); return true; } } catch (Exception e) { return false; } } }