0

I am making a program that makes a file and gives it a unique name. As per the propose technology, we need to have sequential file name. ex. Myfile-00001 (format : MyFile-Sequence). I am using oracle sequence to maintain the sequence number for the file name.

Below is the sample code I am trying to write to get just the sequence out of oracle sequence. If I can get just the string of sequence out of Oracle sequence, I can use it to namemy file I am creating.

Below is my Code:

public class TestSequence {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Configuration cfg = new Configuration();
        cfg.configure();
        SessionFactory sf = cfg.buildSessionFactory();
        Session ses = sf.openSession();
        System.out.println("Next Val: "+getNextKey(ses));
    ses.close();
    sf.close();
    }

    public static String getNextKey(Session ses)
    {
        Query query = ses.createSQLQuery( "select atl_seq.nextval from dual" );
        String key = (String) query.uniqueResult();
        return key;
    }
    }

But its giving me error:

    Next Val: 
Hibernate: select atl_seq.nextval from dual
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.lang.String
    at test.TestSequence.getNextKey(TestSequence.java:31)
    at test.TestSequence.main(TestSequence.java:23)

Please help how do I convert the unique result into string. No Mapping file is used, as I am running the query directly.

I have googled a lot and found similar example, they cast the unique result into Long, but even that code is not running and it gives me same error :cannot cast [Ljava.lang.Object to Long.

My sequence is :

 CREATE SEQUENCE   "ATL_SEQ"  MINVALUE 1 MAXVALUE 100 INCREMENT BY 1 START WITH 1 CACHE 48 
user3769778
  • 967
  • 2
  • 7
  • 26

2 Answers2

0

Sequence probably returns a long or integer. So you need to cast to that and not to a string!

Long key = (Long) query.uniqueResult();

or

Integer key = (Integer) query.uniqueResult();

Don't know which one it is but easy to try for yourself.

beginner_
  • 7,230
  • 18
  • 70
  • 127
  • have tried that too. Its giving me same error ,in above cases its : if I use Integer casting : [Ljava.lang.Object; cannot be cast to java.lang.Integer If I use Long casting : [Ljava.lang.Object; cannot be cast to java.lang.Long – user3769778 Jul 31 '14 at 09:00
0

Try with addScalar() and specify type as Long (for Hibernate4)

public static Long getNextKey(Session ses) {
     Query query = ses.createSQLQuery("select atl_seq.nextval as num from dual") 
                        .addScalar("num", LongType.INSTANCE);
     return (Long)query.uniqueResult();
 }

If you are using Hibernate3, type should be

addScalar("num", Hibernate.LONG);

You can convert the value Long to String later.

Community
  • 1
  • 1
Wundwin Born
  • 3,467
  • 19
  • 37