java - 如何通过 hibernate 将空字符串传递给日期类型的列

标签 java sql oracle hibernate

我正在尝试通过 hibernate 将 "" 的空字符串传递给日期类型列 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();

最佳答案

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

  2. 如果您有更新语句并想将现有值设置为 null,您可以尝试类似的操作:

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

希望对您有所帮助!

编辑:

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

关于java - 如何通过 hibernate 将空字符串传递给日期类型的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34133327/

相关文章:

sql - 使用 SQL 查询的逗号分隔值

MySQL:从带有锁的另一个表创建一个表

SQL - 元组作为主键

java - Oracle PL/SQL 和 Java 依赖项

oracle - 使用 HDBC 在 Haskell 中连接到 Oracle 数据库

java - 如何通过 Java API 从正在运行的 docker 镜像中获取 Docker 容器 ID?

java - 是否可以将依赖项打包到.jar中

从列中查找大写单词的 SQL

java - Netbeans javac 在 LayerGenerateProcessor 中为 @Override 抛出异常。问题出在哪里?

java - 如何手动设置每个 "page"的哈希值