既然数据库可以连通了,今天就要学习如何通过Hibernate完成对数据库的操作了,还是以简单的HelloWorld程序来做个演示。
一、 准备工作
我们需要创建三个文件,分别是Domain Object、Mapping、DB table
1. 先创建Domain Object--类Greetings.java,这个类包括三个字段:
id: ID标识符
name: 问候对象
greeting: 问候语
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;
}
}
2. 创建映射文件Greetings.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping
package="com.foobar.domain">
<class name="Greetings" table="T_Greetings">
<comment>Say hello to somebody!</comment>
<id name="id">
<generator class="native"/>
</id>
<property name="name"
not-null="true"
length="15"
column="`name`"/>
<property name="greeting"
not-null="false"
column="`greeting`"/>
</class>
</hibernate-mapping>
3. 在test数据库中创建对应的表T_Greetings
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
二、 测试
1. 为方便测试,在控制台输出Hibernate生成的sql语句,在配置文件总增加如下属性:
<!-- 在控制台输出Hibernate SQL 语句 -->
<property name="show_sql">true</property>
2. 编写简单的测试类HelloWorld.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();
}
}
}
3. 运行测试类--保存数据
a. 首先出现如下异常:
org.hibernate.MappingException: Unknown entity: com.foobar.domain.Greetings,是因为我们定义的Greeting.hbm.xml没有加载,Hibernate会在当前CLASSPATH需找默认配置文件hibernate.cfg.xml,但不会自动加载映射文件,我们需要告诉Hibernate内去加载哪些映射文件,在配置文件中增加如下配置:
<mapping resource="com/foobar/conf/hbm/Greetings.hbm.xml"/>
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类中增加如下代码:
...
// 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();
...
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包,会引发相关异常:
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 |
四、总结:
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
分享到:
相关推荐
赠送jar包:deeplearning4j-core-1.0.0-M1.1.jar; 赠送原API文档:deeplearning4j-core-1.0.0-M1.1-javadoc.jar; 赠送源代码:deeplearning4j-core-1.0.0-M1.1-sources.jar; 赠送Maven依赖信息文件:deeplearning...
赠送jar包:deeplearning4j-nn-1.0.0-M1.1.jar; 赠送原API文档:deeplearning4j-nn-1.0.0-M1.1-javadoc.jar; 赠送源代码:deeplearning4j-nn-1.0.0-M1.1-sources.jar; 赠送Maven依赖信息文件:deeplearning4j-nn-...
《Learning Java - Introduction to Real-World Programming》第五版是一本深入浅出的Java编程教材,专为初学者和有一定经验的开发者设计。该书详细介绍了Java语言的基础知识以及如何将其应用于实际开发场景。第五版...
《Learning PHP, MySQL & JavaScript》第六版是由Robin Nixon编写的动态网站开发指南。该书涵盖PHP 8、MySQL 8和JavaScript的最新技术,旨在指导读者从零开始创建动态网站。 PHP基础 * PHP是什么?PHP是 Hypertext...
Deep Learning for Signal Processing with MATLAB。Deep learning networks have been used for image classification for many years, but they are powerful tools for signal data as well. A deep learning ...
Adrian Rosebrock-Deep-Learning-For-Computer-Vision-全三册(Starter,Practitioner,ImageNet bundle)PDF高清-带目录和标签-以及start章节代码.1,2,3三本书从基础到入门提高,很好的资源
深度学习处理图片,适合学习仔细研究等等等等
React Quickstart Step-By-Step Guide To Learning React Javascript Library 英文azw3 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
Algorithm-Machine-Learning-for-Beginner-by-Python3.zip,斯克莱恩、坦索流。,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
Machine Learning: Step-by-Step Guide To Implement Machine Learning Algorithms with Python By 作者: Rudolph Russell ISBN-10 书号: 1719528403 ISBN-13 书号: 9781719528405 出版日期: 2018-05-22 pages ...
使用MATLAB实现信号处理的深度学习,中文白皮书 本白皮书将回顾一些深度学习基础知识,然后会讲解三个信号处理示例: • 语音命令识别 • 剩余使用寿命 (RUL) 预估 • 信号去噪 这些示例将向您展示如何通过 MATLAB®...
赠送jar包:deeplearning4j-datasets-1.0.0-M1.1.jar; 赠送原API文档:deeplearning4j-datasets-1.0.0-M1.1-javadoc.jar; 赠送源代码:deeplearning4j-datasets-1.0.0-M1.1-sources.jar; 赠送Maven依赖信息文件:...
赠送jar包:deeplearning4j-nn-1.0.0-M1.1.jar; 赠送原API文档:deeplearning4j-nn-1.0.0-M1.1-javadoc.jar; 赠送源代码:deeplearning4j-nn-1.0.0-M1.1-sources.jar; 赠送Maven依赖信息文件:deeplearning4j-nn-...
赠送jar包:deeplearning4j-ui-components-1.0.0-M1.1.jar; 赠送原API文档:deeplearning4j-ui-components-1.0.0-M1.1-javadoc.jar; 赠送源代码:deeplearning4j-ui-components-1.0.0-M1.1-sources.jar; 赠送...
赠送jar包:deeplearning4j-utility-iterators-1.0.0-M1.1.jar; 赠送原API文档:deeplearning4j-utility-iterators-1.0.0-M1.1-javadoc.jar; 赠送源代码:deeplearning4j-utility-iterators-1.0.0-M1.1-sources....
赠送jar包:deeplearning4j-ui-components-1.0.0-M1.1.jar; 赠送原API文档:deeplearning4j-ui-components-1.0.0-M1.1-javadoc.jar; 赠送源代码:deeplearning4j-ui-components-1.0.0-M1.1-sources.jar; 赠送...
原有的代码仓库也可以下载得到 https://github.com/PacktPublishing/Learning-Data-Mining-with-Python-Second-Edition 此处直接放在了CSDN上,方便大家下载,若有用,请大家多多支持一下我。
React Quickstart Step-By-Step Guide To Learning React Javascript Library 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn...