Illep
Illep

Reputation: 16851

JAVA, SQL exception while retrieving a value

I am using Netbeans 6.9.1, and glassfish 3.1, the DB is MySql.

There is a table in the database called HotelNames, i need to write a SQL and pass the Hotel name to get its hotel ID. I get an exception which i am unable to solve.

    @Override
public int GetHotelID(String hotellName) {
   Query query  = em.createNativeQuery("select ID from HotelNames where hotName ='"+ hotellName+"'");
    String hotelID =  (String) query.getSingleResult();

    return Integer.parseInt(hotelID );
}

The exception i get points to the SQL i wrote in the above code

Caused by: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.String

MySQL create table looks like;

CREATE TABLE HotelNames (`ID` BIGINT NOT NULL AUTO_INCREMENT, `hotName` VARCHAR(255), PRIMARY KEY (`ID`));

I think its because of the BIGINT in the SQL and int in the code that's causing this, but i am unable to solve this.

Upvotes: 0

Views: 2377

Answers (4)

RanRag
RanRag

Reputation: 49567

BigInteger bg = new BigInteger();
bg = query.getSingleResult();
String hotelId = bg.toString();

I hope this explains more.....you can also do it in one line if you wish to...

Upvotes: 0

phlogratos
phlogratos

Reputation: 13924

Your query returns an BigInteger. So you can get an int like that:

        return ((BigInteger)  query.getSingleResult()).intValue();

Upvotes: 0

Alex Gitelman
Alex Gitelman

Reputation: 24722

You may want to do something like this

Number hotelID =  (Number) query.getSingleResult();
return hotelID.intValue();

Upvotes: 4

sudmong
sudmong

Reputation: 2036

java.math.BigInteger cannot be cast to java.lang.String - You are trying to convert the ID to string, which is BigInteger.. See String hotelID = (String) query.getSingleResult();

Upvotes: 0

Related Questions