Question

I'm still not clear on the purpose of annotations in Java. Initially I thought they just served as documentation. But looking at this documentation from Google App Engine Datastore, I'm not so sure. @PersistenceCapable(identityType = IdentityType.APPLICATION) looks more like a method signature.

What's the purpose of this type of annotation? What does it do?

import java.util.Date;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Employee {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    @Persistent
    private String firstName;

    @Persistent
    private String lastName;

    @Persistent
    private Date hireDate;

    public Employee(String firstName, String lastName, Date hireDate) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.hireDate = hireDate;
    }

    // Accessors for the fields.  JDO doesn't use these, but your application does.

    public Long getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    } 

    // ... other accessors...
}
Was it helpful?

Solution

They're source-level metadata. They're a way of adding information to the code that's not code, and that is easily machine-processed.

In your example, they're used to configure object-relational mapping for that entity type. It's saying that for example the id field should be the primary key for that object, and that firstName, lastName, and hireDate should be stored in the database. (To tell those fields apart from some transient object state.)

The GAE support for JDO needs to know what objects you'll try to store in the database. It does this by looking through the classes in your code, looking for the ones that are annotated with @PersistenceCapable.

Commonly, they're used to replace where you'd use external configuration files before; the Java standard library has tools to read the annotations in your code, which makes them much easier to process than rolling your own configuration file plumbing, and gets you IDE support for free.

OTHER TIPS

Annotations can be processed with the Annotation Processing Tool APIs to auto-generate boilerplate code.

I think that these come from the Java Data Objects API. It's an API that overlaps to a degree with what EJB3 is supposed to accomplish. Same concepts, different syntax and tools.

If you are not familiar with annotations in general, check the Java tutorial.

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