Saturday, July 27, 2013

Basic Annotations in Java Persistence API(JPA)

Hi,

Today we will discuss some of the basic JPA annotations.

Annotations :-
  • @Table
  • @Column
  • @Temporal
  • @Transient

Lets consider below table -Company

    SNO
  • NAME
    MAIL
    1
  • Google
  • google@gmail.com
    2
  • Yahoo
  • yahoo@yahoo.com
    3
  • Microsoft
  • microsoft@live.com

1.@Table :-is used to map your entity java bean with the table
In general your table name and entity bean will have same name at that time there is no need to use @Table
If the Entity bean is different from the table name we map it by using @Table annotation

Example :-
Lets take the above table-Company ,but my entity bean name is named as Organization  then we can use @Table to map them

@Entity
@Table(name="Company")
Public class Organization{.......}


2.@Column :- is used to map an instance variable with a column in a table
If the variable name and database column name is same ,then there is no need to use column
This is similar to @Table

Example :-
Lets take the data base column -Name in the above table
In Entity bean we have companyName.so how to map them?

@Column(name="Name")
Private String companyName;

3.@Temporal :-
  • In Java we have java.util.Date and java.util.Calendar classes,if we wnat to persist them into data base we should use @Temporal
  • Temporal are set of time based types
Example :-
@Temporal(TemporalType.DATE)
Date currentDate;

In Entity                                                                   Mapped to data base
  • TemporalType.DATE
  • Mapped to java.sql.Date
  • TemporalType.TIME
  • Mapped to java.sql.Time
  • TemporalType.TIMESTAMP
  • Mapped to java.sql.Timestamp

4.@Transient :-
  • Attributes that are part of Entity but should not be persisted should be marked as @Transient
  • Suppose we have a attribute lastName and should not be persisted to data base,we use@Transient
Example :-
@Transient
private String lastName;

There are many annotations in JPA,each one of them has special functionality which i will discuss in my later posts


Happy Learning

Please provide your valuable comments on this article and share it across your network.



No comments:

Post a Comment

Like and Share