Get next value from Oracle Sequence with Spring

สำหรับท่านที่ใช้ Sequence ในการจัดการ next primary key เวลาจะ insert ข้อมูลลง Oracle

โดยหากเราใช้ Hibernate ก็สามารถ configure ได้เลยโดย Hibernate จะจัดการการขอ next value ให้เอง
แต่ถ้าเราใช้ JdbcTemplate ของ Spring ในทำงานกับฐานข้อมูล เราก็สามารถขอ next value จาก Oracle Sequence ได้ง่ายๆดังนี้ครับ

int id = new OracleSequenceMaxValueIncrementer(dataSource,”MY_SEQ_NAME”).nextIntValue();

Code ด้านบนผมเขียนเพื่อทดสอบการทำงานแบบรวดเร็วเท่านั้น ซึ่งแน่นอนเวลาใช้งานจริงเราควรประกาศตัวแปรเป็น DataFieldMaxValueIncrementer interface แล้วกำหนดว่าจะใช้เป็น OracleSequenceMaxValueIncrementer ใน Spring IoC container ครับ

Related posts:

  1. ถาม "ต้อม" ได้ถ้ามีปัญหา Oracle
  2. Spring MVC step-by-step
  3. Best practice สำหรับการจัดการ Form ใน Spring Framework
  4. Oracle and her Sun
  5. Spring IDE 2.0 RC2

Tags: ,

Leave a Reply