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; } } }6. 运行该程序,控制台输出 数据库连接成功!
四、相关jar包汇总:
4commons-logging-1.0.4.jarApache Commons包中的一个,包含了日志功能Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory5commons-collections-2.1.1.jarApache Commons包中的一个,包含了一些Apache开发的集合类Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/LRUMap6jta.jarJTA规范,当Hibernate使用JTA的时候需要Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/Synchronization
五、总结
1. 如果配置文件中对session-factory设置属性name的值(<session-factory name="foo">),可能会出现如下异常:javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial 解决方法是去掉name属性,即改为:<session-factory>
2. 以上汇总的包不是全部的必须包,只是其中的一部分,只能保证正常连接数据库。以后需要其他的包再导入。