Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding hibernate @Type annotation

Tags:

java

hibernate

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?

like image 687
user3663882 Avatar asked Mar 18 '15 09:03

user3663882


People also ask

What is @data annotation in hibernate?

@Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default.

What are the annotations in hibernate?

Hibernate annotations are the newest way to define mappings without the use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata. Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping.

What is the use of @column annotation?

@Column annotation is used for Adding the column the name in the table of a particular MySQL database.

What do you understand by annotations in JPA?

JPA annotations are used in mapping java objects to the database tables, columns etc. Hibernate is the most popular implement of JPA specification and provides some additional annotations. Today we will look into JPA annotations as well as Hibernate annotations with brief code snippets.


1 Answers

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.

like image 162
Waheed Avatar answered Oct 10 '22 17:10

Waheed