将MySql datetime映射到Hibernate

4

我在我的MySQL数据库中有一个datetime字段。典型的条目看起来像这样:2015-08-26 11:45:48

但是当它到达我的应用程序时,小时、分钟和秒总是00:00:00

这是映射条目:

<property name="listingTime" column="listing_time"/>         

我Java类中的字段是

private java.sql.Timestamp startTime;

我试图在hibernate.cfg.xml中为listingTime属性设置各种类型,但它并没有更改所有零。我错过了什么?


1
你如何获取“Timestamp”? - Jordi Castilla
你是什么意思?它被映射成我在问题中写的那样。 - Eddy
@Eddy:为什么你选择了java.sql.Timestamp类型的字段而不是java.util.Date - beemaster
@beemaster 看起来更适合与 Hibernate / Spring 集成。 - Eddy
2个回答

7
更好的做法是像这样使用注释:
...
@Column
@Type(type="timestamp")
private Date listing_time;

或者你可以这样做,如果你不想它改变,请看“可更新”

@Column(name = "created", nullable = false, updatable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date created;

我在Product.hbm.xml中尝试使用type="timestamp",但似乎没有效果。 - Eddy

4
使用JPA时,使用temporal。
<entity class="com.package.of.my.entities.MyEntity" name="MyEntity">
    <attributes>
        <basic name="startTime">
            <temporal>TIMESTAMP</temporal>
        </basic>
    </attributes>
</entity>

使用Hibernate (hbm.xml),用户
<hibernate-mapping package="com.package.of.my.entities">
    <class name="MyEntity">
        <timestamp name="startTime" column="START_TIME" />
    </class>
</hibernate-mapping>

或者在注释中。
@Basic
@Temporal(TemporalType.TIMESTAMP)
private java.sql.Timestamp startTime;

另一种方法是使用Long数据类型存储您的时间戳。因此,您可以在实体中使用注释声明如下:
@Basic
private Long startTime;

public void setStartTime(Long startTime) {
    this.startTime = startTime;
}

public Long getStartTime() {
    return startTime;
}

在您的逻辑中,您执行以下操作

Date dateStartTime = new Date();
entity.setStartTime(dateStartTime.getTime());

设置日期属性...并且

Date dateStartTime = new Date(entity.getStartTime());

获取日期属性。

我正在使用hbm.xml。这是我的属性:<property name="startTime" type="timestamp" column="listing_time"/>。如何在其中指定时间属性? - Eddy
好的,我编辑了我的答案,添加了hbm.xml示例。 - Ferdinand Neman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接