解决Hibernate注解不能自动创建oracle表

来源:互联网 发布:windows向mac传输文件 编辑:程序博客网 时间:2024/06/05 19:22
实体类
import javax.persistence.Entity;//注意不能导入org.hibernate.annotations.Entity包import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.SequenceGenerator;@Entitypublic class Book {private Integer id;private String name;@SequenceGenerator(name = "seq_book", sequenceName ="seq_book")@Id@GeneratedValue(strategy=GenerationType.SEQUENCE,generator = "seq_book")public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}

执行测试类保存对象时报错:

Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update

Caused by: java.sql.BatchUpdateException: ORA-00942: 表或视图不存在


解决方法:要想自动创建表,需要在hibernate.cfg.xml文件中加上hibernate.hbm2ddl.auto属性

<property name="hibernate.hbm2ddl.auto">update</property>


hibernate.hbm2ddl.auto包含4个值:
create : 会根据你的model类来生成表,但是每次运行都会删除上一次的表,重新生成表,哪怕2次没有任何改变
create-drop : 根据model类生成表,但是sessionFactory一关闭,表就自动删除
update : 最常用的属性,也根据model类生成表,即使表结构改变了,表中的行仍然存在,不会删除以前的行
validate : 只会和数据库中的表进行比较,不会创建新表,但是会插入新值
开发调试时可以选择create和update,但是网站发布正式版本的时候,对数据库现有的数据或表结构进行自动的更新是很危险的。此时此刻应该由DBA同志通过手工的方式进行后台的数据库操作。


原创粉丝点击