如何通过休眠

时间:2015-12-07 12:13:56

标签: java sql oracle hibernate

我试图通过hibernate将""的空字符串传递给Date类型列Logout_date

query.setParameter(3, "");

但抛出异常:

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

我怎样才能做到这一点。?

修改

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();

2 个答案:

答案 0 :(得分:4)

  1. 如果您向数据库和数据库插入数据允许该列的null值,则不要在查询中设置该参数。在这种情况下,它会自动设置为null

  2. 如果你有一个更新声明并希望将现有值设置为null,你可以尝试这样的事情:

    query.setParameter(3, PreparedStatement.setNull());
    
  3. 希望有所帮助!

    修改

        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());
        }
    

答案 1 :(得分:1)

最佳做法是检查日期是否为空。如果为null,则应避免为date类型的null值添加参数。 Hibernate不会自动将字符串转换为日期。