Question

I am following hibernate tutorial from the "Beginning hibernate" book. And I see that the annotations like @Id, @Column are specified above the getXXX() methods.

such as:

@Id
@GeneratedValue
public long getId()
{
    return id;
}

@Column(unique=true)
public String getName()
{
    return name;
}

But not in the attribute definition it self like:

private long id;
private String name;

Is there a link/reference that specifies where the annotation should be placed? and the reasoning behind it. More specifically; how does Hibernate interpret the placement of different annotations and is there a guide to it?

I am talking about the javax.persistence.* annotations

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

I have looked at http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single

I am using:

Hibernate 4.2.6.Final 
Windows 8, 32 bit.
Was it helpful?

Solution

Annotations can be placed on fields or on methods. The option you choose is really a matter of personal preference although I have seen it said to prefer fields over methods.

Personally I prefer field annotations as I find them much easier to work with:

  • all the persistence mappings are located at the top of your source file.
  • if you have any any other methods in your Entity not concerned with JPA mappings then these have to be annotated with @Transient which 'just seems wrong'.
  • when using property access you will have to include a getter even if you don't require one (although this can be be private (or at least protected).
  • if you want to encapsulte add/remove operations for assocations then it is often desirable to return a wrapped, Unmodifiable collection: you cannot do this if the persistance mappings are on the property.

When scanning your class Hibernate will firstly look for a field or method with the @Id annotation and will then look for other mappings accordingly, viz. if @Id is on a field only other fields will be scanned: any mappings defined on a method will, by default, be ignored and vice versa although this behaviour can be modified using:

@Access(AccessType.PROPERTY)
@Access(AccessType.FIELD)

What is the purpose of AccessType.FIELD, AccessType.PROPERTY and @Access

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top