我正在尝试通过 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();
最佳答案
如果您向数据库中插入数据并且数据库允许该列的
null
值,则不要在查询中设置该参数。在这种情况下,它会自动设置为null
。如果您有更新语句并想将现有值设置为
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/