Learning Hibernate step by step -- 01 Hello World
既然数据库可以连通了,今天就要学习如何通过Hibernate完成对数据库的操作了,还是以简单的HelloWorld程序来做个演示。 一、 准备工作 我们需要创建三个文件,分别是Domain Object、Mapping、DB table 1. 先创建Domain Object--类Greetings.java,这个类包括三个字段: id: ID标识符 name: 问候对象 greeting: 问候语 [code="java"] public class Greetings { private int id; private String name; private String greeting; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGreeting() { return greeting; } public void setGreeting(String greeting) { this.greeting = greeting; } } [/code] 2. 创建映射文件Greetings.hbm.xml [code="java"] Say hello to somebody! [/code] 3. 在test数据库中创建对应的表T_Greetings [code="sql"] CREATE TABLE `t_greetings` ( `id` int(11) NOT NULL auto_increment, `name` varchar(15) default NULL, `greeting` varchar(128) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 [/code] 二、 测试 1. 为方便测试,在控制台输出Hibernate生成的sql语句,在配置文件总增加如下属性: [code="java"] true [/code] 2. 编写简单的测试类HelloWorld.java [code="java"] public class HelloWorld { public static void main(String[] args) { Configuration cfg = new Configuration(); cfg.configure(); SessionFactory sessionFactory = cfg.buildSessionFactory(); try { // First unit of work Session session = sessionFactory.openSession(); Greetings greeting = new Greetings(); greeting.setName("TriEyes"); greeting.setGreeting("Say Hello to "); // 打开事务 Transaction tx = session.beginTransaction(); session.save(greeting); // 提交 tx.commit(); session.close(); } catch (Exception e) { e.printStackTrace(); } } } [/code] 3. 运行测试类--保存数据 a. 首先出现如下异常: org.hibernate.MappingException: Unknown entity: com.foobar.domain.Greetings,是因为我们定义的Greeting.hbm.xml没有加载,Hibernate会在当前CLASSPATH需找默认配置文件hibernate.cfg.xml,但不会自动加载映射文件,我们需要告诉Hibernate内去加载哪些映射文件,在配置文件中增加如下配置: [code="java"] [/code] b. 继续运行,出现如下异常: Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter,原因是缺少相关jar包,导入cglib-2.1.3.jar包。 c. 继续运行,出现如下异常: Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type,原因是缺少相关jar包,导入asm.jar及asm-attrs.jar。 d. 继续运行, 控制台输出:Hibernate: insert into T_Greetings (`name`, `greeting`) values (?, ?) 观察后台数据库,数据已经成功保存到数据库中: mysql> use test; Database changed mysql> select * from t_greetings; +----+---------+---------------+ | id | name | greeting | +----+---------+---------------+ | 1 | TriEyes | Say Hello to | +----+---------+---------------+ 1 row in set 4. 更近一步--检索数据 在HelloWorld类中增加如下代码: [code="java"] ... // Second unit of work Session session2 = sessionFactory.openSession(); Transaction tx2 = session2.beginTransaction(); List greetings = session2.createQuery("from Greetings g").list(); System.out.println(greetings.size() + " greeting(s) found."); for(Iterator it = greetings.iterator(); it.hasNext(); ) { Greetings loadedGreetings = (Greetings)it.next(); System.out.println(loadedGreetings.getGreeting() + " " + loadedGreetings.getName()); } tx2.commit(); session2.close(); ... [/code] 5. 运行测试类,出现如下异常: Exception in thread "main" java.lang.NoClassDefFoundError: antlr/ANTLRException,原因是缺少相关jar包,导入antlr-2.7.6.jar包。 6. 继续运行,控制台输出: Hibernate: insert into T_Greetings (`name`, `greeting`) values (?, ?) Hibernate: select greetings0_.id as id1_, greetings0_.`name` as name2_1_, greetings0_.`greeting` as greeting3_1_ from T_Greetings greetings0_ 2 greeting(s) found. Say Hello to TriEyes Say Hello to TriEyes 数据保存成功,并且可以从刚插入的表中检索出数据。 三、相关jar包,为了顺利运行程序,我们新引入了三个jar包,缺少这三个jar包,会引发相关异常: [table] |ID|包名|说明|异常 |1|cglib-2.1.3.jar|CGLIB库,Hibernate用它来实现PO字节码的动态生成|Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter |2|asm.jar|和cglib类似|Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type |3|asm-attrs.jar|和cglib类似|? |4|antlr-2.7.6.jar|ibernate使用ANTLR来产生查询分析器|Exception in thread "main" java.lang.NoClassDefFoundError: antlr/ANTLRException [/table] 四、总结: 1. 涉及的三个对象:Domain Object、Mapping、DB table 2. 映射文件不会自动加载,需要在配置文件中指定 3. Hibernate不会自动提交事务,需要显示地执行Transaction 4. 到目前为止,已经引入的Hibernate的必须的包如下: LearningHibernate +src +lib antlr-2.7.6.jar asm.jar asm-attrs.jar cglib-2.1.3.jar commons-collections-2.1.1.jar commons-logging-1.0.4.jar dom4j-1.6.1.jar hibernate3.jar jta.jar