Hibernate常见错误
Mapping (RESOURCE) not found
解决方法
- 解决方法
- IDEA中,entity的xml应放在resources文件夹下,并将
hibernate.cfg.xml中对应的mapping-resource修改
- IDEA中,entity的xml应放在resources文件夹下,并将
No CurrentSessionContext configured
问题重现
- 使用
getCurrentSession时出现
- 使用
解决方法
使用
openSession,但会造成session打开过多在
hibernate.cfg.xml中添加配置文件hibernate.cfg.xml 1
<property name="hibernate.current_session_context_class">thread</property>
Calling method ‘get’ is not valid without an active transaction
问题重现
- 使用
getCurrentSession时出现
- 使用
解决方法
hibernate要求对数据库的所有操作都必须开启事务管理
e.g. 1
2
3
4
5
6
7transaction = session.beginTransaction();
try{
操作;
transcation.commit();
}catch( Exception e){
transcation.rollback();
}
failed to lazily initialize a collection of role
问题重现
- 当使用一对多映射时,默认延迟加载
解决方法
修改加载方式
在映射文件的集合映射处,添加
lazy属性可选值 说明 false 不延迟加载,一次性加载所有值 true (默认)延迟加载,在调用具体实体的时加载 extra 自动,只加载需要的信息
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 AlMirai!