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:
@Entity
//@Table
public class Simple {

    @Id
    public long id;
    @Column
    public String name;
    @Column
    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:
CREATE TABLE simple
(
  id bigserial NOT NULL,
  name character varying(255),
  "number" integer,
  CONSTRAINT simple_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
On trying to load a record the select SQL generated is:
Hibernate: 
    select
        simple0_.id as id3_0_,
        simple0_.name as name3_0_,
        simple0_.number as number3_0_ 
    from
        Simple simple0_ 
    where
        simple0_.id=?
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