maven+hibernate使用Junit测试找不到hibernate.cfg.xml 的解决

使用了Junit去测试maven管理的项目,会出现找不到配置资源。而我的项目是用到hibernate的,又没有使用到Spring。所以出现下面的异常信息。 Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found。

原因:在maven项目中,hibernate.cfg.xml在src/resource包中,并不是在src目录下,尽管在web容器下面hibernate.cfg.xml会输出到WEB-INF/Class文件夹中去,但是junit是脱离web容器测试的。

百度谷歌找不到解决方法。又在csdn中的J2ee论坛下提问过,帖子地址如下:http://bbs.csdn.net/topics/390760743?page=1#post-397199290。

有几位热心的网友给了我一些建议,但是我自己觉得不是很满意,再次谷歌,翻了几页后,终于找到一个国外帖子,地址为http://www.shaunabram.com/hibernate-maven-unit-tests/

翻一下他的解决方法:

1) Copy the hibernate.cfg.xml file to
my-app/target/classes

复制hibernate.cfg到 /target/classes里面,不过他本人不推荐。

2) The next solution I found suggested moving the hibernate.cfg.xml to
my-app/src/main/resources

hibernate.cfg.xml 移动/src/main/resources目录下。这个其实我本人就是这么干的,但是依然会出现上面的异常。

3) The next and I think best solution was to create a new, duplicate hibernate.cfg.xml inside
my-app/src/test/resources

新建一个文件夹,路径为sre/texs/resoures。这个也是他本人推荐的。尝试之后成功。


总结:其实这个方法并不是最佳方案,因为这样子,就要维护两个hibernate.cfg.xml 。对于一个开发人员,这无疑增加自己负担的事情。如果有哪位知道更好的解决方案,望不吝赐教。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值