-1

I have a Spring / Hibernate project and I am trying to store a date into the database but it's not working. It must be something stupid but I have no idea what I am doing wrong.

Here is my code:

user.setFailedPasswordAnswerAttemptCount(0);
user.setLastLoginDate(new Date());
user.setIsOnline(true);

The other two variables (failedPasswordAnswerAttemptCount and isOnline) are getting written to the database without issue. I have also tried it with just passing a java.util.Date instead of a java.sql.Timestamp...same result. Here is how the property is defined on the user object:

private Date lastLoginDate;

@Temporal(TemporalType.TIMESTAMP)
@Column(name="last_login_date")
public Date getLastLoginDate() {
    return this.lastLoginDate;
}

public void setLastLoginDate(Date lastLoginDate) {
    this.lastLoginDate = lastLoginDate;
}

Here is the column definition:

`last_login_date` datetime DEFAULT NULL

Any help? I don't even know what else to look for as this should be working.

Some more detail about the error: No errors or strange messages in the hibernate log. The hibernate log is showing a parameterized query but it isn't telling me what it is actually writing. It looks like it's not updating the column at all. In other words, if there is already a date there it doesn't change, or if it is null it doesn't change.

Update: I have looked at the logs and it looks like hibernate does write the proper data, but then immediately writes the incorrect data again. I see the following entry in the log:

11:15:12.280 [http-bio-8080-exec-26] TRACE o.h.e.def.AbstractSaveEventListener - detached instance of: com.hi.model.User
11:15:12.280 [http-bio-8080-exec-26] TRACE o.h.e.def.DefaultMergeEventListener - merging detached instance

And right after that I see it putting the old value back in for the lastLoginDate.

4

3 回答 3

0

你为什么使用

Date date = new Date();
user.setLastLoginDate(new Timestamp(date.getTime()));

而不仅仅是这个?

user.setLastLoginDate(new Date());

首先 - 您可能不想同时使用 Date 和 Timestamp。(例如,用于集合等)

Java 平台库中有一些类确实扩展了可实例化的类并添加了值组件。例如,java.sql.Timestamp 扩展了 java.util.Date 并添加了一个纳秒字段。Timestamp 的 equals 实现确实违反了对称性,如果 Timestamp 和 Date 对象在同一个集合中使用或以其他方式混合使用,则可能导致不稳定的行为。Timestamp 类有一个免责声明,警告程序员不要混合日期和时间戳。虽然只要将它们分开就不会遇到麻烦,但没有什么可以阻止您混合它们,并且由此产生的错误可能难以调试。Timestamp 类的这种行为是错误的,不应被模仿。(布洛赫,有效的 Java,第 2 版。)

第二 - 我检查了你的例子,它在 mysql-connector(5.1.21) / hibernate (4.0.1) 上运行良好

我用 arquillian 集成测试准备了简单的测试项目(你需要在运行之前准备好 jboss): https ://github.com/rchukh/StackOverflowTests/tree/master/13803848

如果您可以提供更多信息,它可能会有所帮助 - hibernate 版本、mysql 版本、mysql 引擎(MyISAM、InnoDB 等)否则这可能只是一个错误配置。

于 2012-12-10T20:54:45.237 回答
0

我发现了问题。我正在重构一些代码,看起来我正在这样做:

//get user object
User user = getUser();
//call a function which modifies user
functionModifiesUser();
//modify user
user.blah = blah;
entityManager.merge(user);

所以当我试图保存它时,父函数有一个用户对象的旧副本。实际上,删除合并语句就足以修复它。但是我已经重构了代码以将所有这些都放在一个地方。

于 2012-12-11T18:06:12.043 回答
-1

将列设置last_login_datetimestamp应该工作,至少对我有用。

于 2012-12-10T16:40:06.370 回答