Search This Blog

Thursday, 2 May 2013

Simple Annotated Entity

In an earlier post when working with Hibernate I tried to generate an hbm with minimal content. I decided to try something similar with JPA. The minimum annotations needed to work with a simple table.
The entity is:
public class Simple {

    public long id;
    public String name;
    public int number;
As seen there are just three annotations used here. The @Entity indicates that the class is an entity.
The @Id indicates that id is the primary key property. I have not specified any @GeneratedValue, as I do not intend to add any records to the table. The generator is only needed if we plan to add records.
The column annotation does not take any attributes. If there was only the id column, then even these could be skipped.
The create script for the table (not Hibernate generated) is:
  id bigserial NOT NULL,
  name character varying(255),
  "number" integer,
  CONSTRAINT simple_pkey PRIMARY KEY (id)
On trying to load a record the select SQL generated is:
    select as id3_0_, as name3_0_,
        simple0_.number as number3_0_ 
        Simple simple0_ 
If we don't add the @Entity annotation then our class won't be considered as an entity. (even if you list it out in your configuration). @Entity is a must.
Can we avoid the Id annotation?
I tried to run my code by commenting out @Id and it failed. The annotation is a must along with @Entity .
The @Table is optional. Above code worked perfectly; it assumed all default values for the @Table settings i.e. a table named "simple" in the default schema.

No comments:

Post a Comment