前面我们使用Maven构建了Struts2项目,这里我们来试一下Hibernate项目:
ps: 昨天晚上没有整明白,例子也一直有问题,就没有完成博客,早上起来才明白错在哪
这里的例子,大体框架应该是正确的,但是,对于Maven的很多约定都没有掌握,估计包的命名都不是非常好,等以后,理解深刻了再改吧
1. 构建一个基本的Web项目
这里请参考前面的博客,一样的
2. 添加依赖,修改pom.xml
在保存的时候,Maven会自动从库中各种包下载到本地,如果有异常的话,可以尝试手动下载
3. 添加hibernate.cfg.xml和log4j.properties资源文件
注意,资源文件的话,根据约定,需要放在src/main/resources文件夹下
hibernate.cfg.xml
log4j.properties
4. 新建一个实体类,测试一下
PersonEntity.java
HibernateUtil.java
测试类 ModelTest.java
项目结构如下图所示:
对了,注意一下,在上面的pom.xml中,没有看到数据库驱动包,我用的是SQL Server,直接将jar包放到了项目的lib文件夹下,而从网上查的说,使用scope引入本地的包,试了一下,好像不行,等我再试一试。
5. 测试
如果你现在运行JUnit测试的话,是不会成功的,昨天晚上就是这个原因,提示说找不到hibernate.cfg.xml,
后来发现,在target文件夹下,并没有生成class文件,配置文件也没有,这样当然运行不成功
这里需要执行两个命令
使用CMD窗口,进入当前项目的根目录:
第一条命令:输入mvn compile
注意:这里一定要成功啊,即 BUILD SUCCESS
第二条命令:输入mvn test-compile
同样的,这里一定要 BUILD SUCCESS
这样的话,再一次运行测试程序,就可以成功了!
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------