22

From the official hibernate documentation:

@org.hibernate.annotations.Type overrides the default hibernate type used: this is generally not necessary since the type is correctly inferred by Hibernate

There is an example from the documentation:

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

I don't understand that. We declare @Type(type="org.hibernate.test.annotations.entity.MonetaryAmountUserType") but the method's return value has the type MonetaryAmount.

I expected that the type declared within the type annotation and the type of the returned value should be the same type.

Couldn't someone explain the actual purposes of the type, declared within the @Type annotation. Why is it differ from the returned type?

user3663882
  • 6,957
  • 10
  • 51
  • 92

1 Answers1

35

There is difference between return type and @Type.

@Type annotation is for hibernate i.e. to tell what type of data do you want to store in database.

Let's take a simple example:

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

Here return type is boolean but the value which gets stored in the database will be in Y or N format instead of true/false.

In the same fashion you can map your object to a database column. Check here for more detailed explanation.

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
Waheed
  • 1,835
  • 15
  • 21
  • 1
    In new hibernate version 6, these methods depricated https://stackoverflow.com/questions/69858533/replacement-for-hibernates-deprecated-type-annotation – Komal Dec 16 '22 at 11:24