【问题标题】:How to pass an empty string to a Date type column through hibernate如何通过休眠将空字符串传递给日期类型列
【发布时间】:2015-12-07 12:13:56
【问题描述】:

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

【问题讨论】:

  • 如果该字段可以为空,则无需调用 setParameter。
  • 您不能将字符串传递给日期。
  • 我需要在我的表中插入(null),我可以通过 JDBC 来做到这一点。@Jens
  • @StefanBeike 如果我正在更新并且我希望将该值设为 (null),该怎么办

标签: java sql oracle hibernate


【解决方案1】:
  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());
    }

【讨论】:

  • 感谢插入很好,但如果我正在更新并需要将其设置为 (null)
  • @VishalTyagi 见第二部分(2.-)我认为应该可以解决你的问题
  • 嗯嗯好吧...您能否使用查询发布其余代码?
  • @VishalTyagi 执行上面的code-sn-p时,日期是否始终为空?如果是这样,您可以将 NULL direkcty 写入您的 SQL 语句。否则,您可以使用 if-clause 进行检查
  • 我没有办法在 setparameter 中设置它
【解决方案2】:

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

【讨论】:

  • 其实不需要显式设置null,默认为null
  • 该列可以为空。
猜你喜欢
  • 2020-09-18
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多