`

2009.11.20——Hibernate(2) 主健生成问题(2)

阅读更多
2009.11.20——Hibernate(2) 主健生成问题(2)
为了屏蔽底层数据库的差异,我主键的生成策略用的是Table的,如下
@Id
@Column(name="student_id")
@TableGenerator(name="stuGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="STU_ID",
allocationSize=1)
@GeneratedValue(strategy=GenerationType.TABLE,generator="stuGen")

建表的sql如下:
实体类Student:
create table STUDENT
(
  STUDENT_ID NUMBER(2) not null,
  NAME       VARCHAR2(5)
)
生成主键的表Id_gen
create table ID_GEN
(
  ID        NUMBER not null,
  GEN_KEY   VARCHAR2(255) not null,
  GEN_VALUE NUMBER not null
)
并插入一条记录:
insert into id_gen values(1,'student_id',1);
执行的save操作:
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
StudentService ss = (StudentService)ctx.getBean("studentService");
Student s = new Student();
s.setName("fdsa");
ss.save(s);

但是 当我运行程序后,
2009/11/20 11:01:59.860 WARN  JDBCExceptionReporter.logExceptions() : SQL Error: 1400, SQLState: 23000
2009/11/20 11:01:59.860 ERROR JDBCExceptionReporter.logExceptions() : ORA-01400: 无法将 NULL 插入 ("SYSTEM"."ID_GEN"."ID")

Exception in thread "main" org.springframework.dao.DataIntegrityViolationException: could not get or update next value; nested exception is org.hibernate.exception.ConstraintViolationException: could not get or update next value
Caused by: org.hibernate.exception.ConstraintViolationException: could not get or update next value
Caused by: java.sql.SQLException: ORA-01400: 无法将 NULL 插入 ("SYSTEM"."ID_GEN"."ID")

=======================================================================================

迫于无奈,我用的是oracle的数据库,所以我就用只好用sequence了
注释:
@SequenceGenerator (name="student_seq",
sequenceName="student_seq",initialValue=1,allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="student_seq")
sql语句:
create sequence student_seq nocache;
然后可以执行了
但是,这个通用性 也就被破坏了
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics