Results 1 to 3 of 3
  1. #1
    Join Date
    Oct 2002

    Question Unanswered: java jdbc transaction & oracle sequence


    I wrote following code.

    	public void insert(KKBInquiryVO bean) throws Exception {
    		Connection cn = null;
    		try {
    			cn = OracleDAOFactory.getConnection();
    			OracleInsertSQLs sql = OracleInsertSQLs.getInstance();
    			// get ID for KKBInquiries
    			Long ID = sql.getNextID(cn);
    			sql.insertKKB_INQUIRIES(cn, bean);
    			// get ID for Applicants (Debtor)
    			ID = sql.getNextID(cn);
    			sql.insertAPPLICANTS(cn, bean.getDebtor());
    			if (bean.getGuarantor1() != null) {
    				// get ID for Applicants (Guarantor1)
    				ID = sql.getNextID(cn);
    				sql.insertAPPLICANTS(cn, bean.getGuarantor1());
    				if (bean.getGuarantor2() != null) {
    					// get ID for Applicants (Guarantor1)
    					ID = sql.getNextID(cn);
    					sql.insertAPPLICANTS(cn, bean.getGuarantor2());
    		} catch (SQLException sqle) {
    			throw sqle;
    		} finally {
    the code for getNextID() :
    public Long getNextID(Connection cn) throws SQLException {
    		return (Long) new QueryRunner().query(cn, "SELECT KRS.KRSSEQUENCE.NEXTVAL FROM DUAL", new ScalarHandler());
    cn : java.sql.Connection
    the insertAPPLICANTS methods throw SQLException's.

    up to this line getNextID is called 4 times, thus 4 values are generated for this thread.

    lets say thread 1 starts getting IDs 1,2, a.s.o.

    1) my first question here is :
    would a second thread get for example ID number 3 from the sequence ? or would it wait for thread 1's transaction until it releases the sequence and get ID number 5 ? are sequences beeing locked ?
    (simple question maybe but I'm new to Oracle and sequences)

    2) after setting AutoCommit to false, starting a transaction lets say an exception is thrown at this line :

    sql.insertAPPLICANTS(cn, bean.getGuarantor2());

    (that's right before the cn.commit(); call)

    what would be the next ID the sequence would generate ? would it re-generate the rolledback numbers 1,2,3,4 ?

    thanks in advance

  2. #2
    Join Date
    Nov 2003
    Provided Answers: 23
    Quote Originally Posted by msegmx
    would it re-generate the rolledback numbers 1,2,3,4
    No, never. Once a value has been obtained from sequence, that value is "gone".

    If you want to ensure your IDs have no gaps than sequences are the wrong way to do it.

    Additionally: in most of the cases (95%) putting a meaning into an ID (such as "should not have gaps in there") indicates a wrong DB design.

  3. #3
    Join Date
    Oct 2002
    ID is a surrogate key. it's not important to have gaps or not.

    thanks for answering.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts