了解hibernate @Type注释

时间:2015-03-18 09:25:48

标签: java hibernate

来自official hibernate documentation

  

@ org.hibernate.annotations.Type会覆盖默认的hibernate类型   使用:这通常不是必需的,因为类型是正确的   由Hibernate推断

文档中有一个例子:

@Type(type="org.hibernate.test.annotations.entity.MonetaryAmountUserType")
@Columns(columns = {
    @Column(name="r_amount"),
    @Column(name="r_currency")
})
public MonetaryAmount getAmount() {
    return amount;
}

我不明白。我们声明@Type(type="org.hibernate.test.annotations.entity.MonetaryAmountUserType")但方法的返回值的类型为MonetaryAmount

我预计在类型注释中声明的类型和返回值的类型应该是相同的类型。

无法解释在@Type注释中声明的类型的实际目的。为什么它与返回的类型不同?

1 个答案:

答案 0 :(得分:19)

返回类型与@Type之间存在差异。

@Type注释用于休眠,即告诉您要在数据库中存储哪种类型的数据。

我们举一个简单的例子:

@Type(type="yes_no")
private boolean isActive; 

此处返回类型为boolean,但存储在数据库中的值将采用YN格式,而不是true / false

以同样的方式,您可以将对象映射到数据库列。请查看here以获取更详细的说明。