Vishal Tyagi
Vishal Tyagi

Reputation: 580

How to pass an empty string to a Date type column through hibernate

I am trying to pass an empty string that is "" to a Date type column Logout_date through hibernate:

query.setParameter(3, "");

But an exception is thrown :

java.lang.String cannot be cast to java.util.Date.

How can I achieve this.?

EDIT:

String updq2 = "update TblUser a set loggedStatus = ? ,lockedStatus= ?,currentAttempts = ?,logoutDate = ? where upper(a.id)=?";//,lockedStatus= ?, currentAttempts = ?, logoutDate = ? where upper(a.id) = ?";
            Session newSession2=factory.openSession();
            Transaction tx1=newSession2.beginTransaction();
            Query query =newSession2.createQuery(updq2);
            query.setParameter(0, (byte)9);
            query.setParameter(1,"1" );
            query.setParameter(2, 0);
            query.setParameter(3, "");
            query.setParameter(4,  userName.toUpperCase());
query.executeUpdate();
tx1.commit();
newSession2.close();

Upvotes: 3

Views: 3692

Answers (2)

Felix Gerber
Felix Gerber

Reputation: 1651

  1. If your inserting data to your database and the database allows null values for that column just don't set that parameter in your query. In this case it's automatically set to null.

  2. If your having an update statement and want to set an existing value to null you could try something like that:

    query.setParameter(3, PreparedStatement.setNull());
    

Hope that helps!

EDIT:

    String updq2;
    bool isNull = false;
    //If your data is null and you want to set it null use this 
    if(yourDate == null)
    {
        updq2 = "update TblUser a set loggedStatus = ? ,lockedStatus= ?,currentAttempts = ?,logoutDate = NULL where upper(a.id)=?";//,lockedStatus= ?, currentAttempts = ?, logoutDate = ? where upper(a.id) = ?";
        isNull = true;
    } //If it isn't null and you want to set and value use this
    else
    {
        updq2 = "update TblUser a set loggedStatus = ? ,lockedStatus= ?,currentAttempts = ?,logoutDate = ? where upper(a.id)=?";//,lockedStatus= ?, currentAttempts = ?, logoutDate = ? where upper(a.id) = ?";

    } 

    Session newSession2=factory.openSession();
    Transaction tx1=newSession2.beginTransaction();
    Query query =newSession2.createQuery(updq2);
    query.setParameter(0, (byte)9);
    query.setParameter(1,"1" );
    query.setParameter(2, 0);

    if(isNull)
    {
         query.setParameter(3,  userName.toUpperCase());
    }
    else
    {
         query.setParameter(3, yourDataHere);
         query.setParameter(4,  userName.toUpperCase());
    }

Upvotes: 4

sohan nohemy
sohan nohemy

Reputation: 615

The best practice would be You check if date is null. If null you should avoid adding parameter for null value of type date. Hibernate does not automatically convert string to date.

Upvotes: 1

Related Questions