我正在使用 hibernate 逆向工程并尝试将我的时间戳映射到 JodaTime 类型。
我已经正确设置了 hibernate.reveng.xml 文件
<sql-type jdbc-type="TIMESTAMP" hibernate-type="org.joda.time.contrib.hibernate.PersistentDateTime" not-null="true"></sql-type>
问题是,当我运行 rev-eng 进程时,我的 Java 类也获得了作为 PersistentDateTime 对象创建的成员,但我不希望这样,因为它们不可用。我需要 java 对象是 org.joda.time.DateTime
所以我尝试创建自定义工程策略
public class C3CustomRevEngStrategy extends DelegatingReverseEngineeringStrategy {
public C3CustomRevEngStrategy(ReverseEngineeringStrategy res) {
super(res);
}
public String columnToHibernateTypeName(TableIdentifier table, String columnName, int sqlType, int length, int precision, int scale, boolean nullable, boolean generatedIdentifier) {
if(sqlType==Types.TIMESTAMP) {
return "org.joda.time.DateTime";
} else {
return super.columnToHibernateTypeName(table, columnName, sqlType, length, precision, scale, nullable, generatedIdentifier);
}
}
}
我的想法是 hibernate 映射文件将获取 hibernate.reveng.xml 文件设置,而 java 对象将从自定义策略文件中获取设置...但事实并非如此。映射文件和对象都是“org.joda.time.DateTime”类型,这不是我想要的。
我怎样才能实现我的目标?另外,我没有使用注释。
- hibernate 3.6
- Joda Time 2.3
- JodaTime-Hibernate 1.3
谢谢
编辑:明确问题是什么
经过逆向工程后,这就是我在映射文件和 POJO 类中得到的内容
<property name="timestamp" type="org.joda.time.contrib.hibernate.PersistentDateTime">
private PersistentDateTime timestamp;
作为 POJO 属性,PersistentDateTime 对我来说毫无用处,因为我无法用它做任何事情,例如时间操作或任何事情。这就是我逆向工程后想要的
<property name="timestamp" type="org.joda.time.contrib.hibernate.PersistentDateTime">
private org.joda.time.DateTime timestamp;
按照下面的建议使用 Jidira 库会得到相同的结果,即我无法使用的 POJO。
最佳答案
JodaTime-Hibernate 库已弃用,这可能是您问题的根源。不过,不要失望,因为还有一个(更好的)替代方案。
您将需要使用 JadiraTypes 库从 Hibernate 创建正确的 JodaTime 对象。添加库which can be found here到您的项目类路径,然后将类型更改为 org.jadira.usertype.dateandtime.joda.PersistantDateTime。所有 JodaTime 对象在该包中都有相应的映射,因此如果您决定更改为另一个对象,则只需更新您的类型即可。
这应该确保您的对象被正确创建。
我应该在我的答案中添加一个警告,那就是我从未在 Hibernate 3 中使用过 JadiraTypes 库。如果它只支持 Hibernate 4(我不明白为什么会这样,但是......)让我知道我会删除我的答案。
关于java - Hibernate + JodaTime 映射不同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24000461/