Saturday, March 26, 2011

Customizing the Entity object in JPA

Changing the default table name

By default the table name corresponds to the unqualified name of the class. We can change this behavior with the help of @Entity annotation itself, like this.

@Entity(name = "MOBILE_ENTITY")
public class MobileEntity{

Now, the table name becomes MOBILE_ENTITY and this should be the name that must be referred in query strings (Queries are discussed later). The value to the name property must be legal in the sense, it cannot accept any keywords that are found in the query language.

Customizing the Column behaviors

The default name of the columns, their size, whether they can accept null values or not etc., can be customized using the @Column annotation. Following is the sample code that illustrates this,

@Column(name = “MOBILE_MODEL”, nullable = true, length = 35)
private String model;

@Column(name = “MOBILE_MANUFACTURER” nullable = true, length = 100)
private String manufacturer;

@Column(name = “MOBILE_IMEI_NO”, nullable = false)
private String imeiNo;


The name property, when specified will override the default column name (which is the same as that of the field name in the Entity class). The nullable property tells that whether the column can accept null values. Length property is only applicable if the type of the column is String (or VARCHAR). There are also properties like scale and precision which is applicable only when the type of the column is NUMBER.

[Note, multiple annotations can be legally applied to elements (like class, field, method etc.). In the above example the imeiNo has two annotations attached with it, namely @Id and @Column.]

Auto-generation of Primary Keys

A primary key for an entity which is usually annotated with @Id annotation can be given a value manually or we can depend on the persistence provider for the same. For this we have to use the @GeneratedValue annotation.

Consider the following example,

@GeneratedValue(strategy = GenerationType.AUTO)
private String imeiNo;

Since the imeiNo is going to be the primary key for the mobile object, we have decorated the field with @GeneratedValue annotation, which delegates the burden of creating values from developers to the persistence engine. Also, there are 4 different methods (or strategies) for primary key generation, which are AUTO, IDENTITY, SEQUENCE and TABLE. The simplest one is the automatic primary key generation strategy which is represented as GenerationType.AUTO.

[GenerationType is an Enumeration (new feature in Java 5.0) and the four different strategies for primary key generation, namely AUTO, IDENTITY, TABLE and SEQUENCE are defined in that enumeration.]

No comments:

Post a Comment