Hibernate 4.3 开发过程中常见问题及解决方案

1.Exception in thread "main" org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save():

产生原因
1) 在定义entity时没有为主键指定GeneratedValue属性,导致hibernate不会自动生成主键,因此提示需要“手动为主键赋值”

(ids for this class must be manually assigned)

解决方法:
1) 在private Integer id;这个属性前加上注解@GeneratedValue(strategy=GenerationType.IDENTITY)

2) 或在主键的get方法前加上@GeneratedValue语句

3) 在该实体类的*.hbm.xml对应的数据库字段中将主键id的class属性做对应的修改




2.WARN: HHH000374: Could not unbind factory from JNDI
org.hibernate.engine.jndi.JndiException: Error parsing JNDI name []

产生原因:

1) 未配置相应的JNDI数据源

解决方法:

1) 去除hibernate.cfg.xml文件中<session-factory name="">的name属性,如果配置了JNDI则需要添加对应的属性,如下所示:



3.javax.naming.NoInitialContextException:  Need to specify class name in environment or system property,  or as an applet parameter, or in an application resource file:  java.naming.factory.initial

产生原因
1) 在hibernate容器初始化时找不到JNDI服务提供商的默认属性和JNDI服务器没有被显式的配置时发生。

解决方法:
1) 用hibernate.properties代替hibernate.cfg.xml不会发生这个异常,因此,问题一定出在hibernate.cfg.xml,因为在hibernate.cfg.xml文件的<session-factory>一栏多了个name属性,该name属性的作用是“/jndi/name绑定到JNDI的SessionFactory实例”。但是又有配置JNDI,所以出错。好比是给了门牌号,但是并不存在该地址。

PS:
1) hibernate.properties与hibernate.cfg.xml混用,仅选其一,用自己属性的方式配置hibernate属性;

2) 用hibernate.properties创建SessionFactory时,要用

new AnnotationConfiguration().addAnnotatedClass(hello.Message.class).buildSessionFactory()

方式将POJO配置到hibernate中,否则将报“找不到xx class”的异常;

3) 如果用hibernate.cfg.xml,则需要用

new AnnotationConfiguration().configure().buildSessionFactory()

方式创建SessionFactory,毕竟configure()方法是为了加载hibernate.cfg.xml配置文件。


4.Exception in thread "main" org.hibernate.TransactionException: Transaction not successfully started

可能原因:
这个错误的产生是因为在保存entity后提交事务用的session.getTransaction().commit()语句,session.getTransaction()只是根据session获得一个Transaction实例,但是并没有启动,因此提示“Transaction启动失败”:

(Transaction not successfully started)

解决方法:
1) 用session.beginTransaction()代替session.getTransaction()。

    session.beginTransaction()方法在获得一个Transaction后调用其begin()方法,如果是请求创建一个新的“受控”Transaction,则启动这个Transaction,否则就直接使用已经存在的“受控”Transaction来完成工作。


如有错误之处,不吝赐教!也可以在评论中留言。

发布了105 篇原创文章 · 获赞 35 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/mimica/article/details/48001643
4.3