Monday, 2 June 2014

Commonly used Annotations in EJB

Annotation

   Annotations are used to describe configuration meta-data in ejb classes. By this way EJB 3.0 eliminates the need to describe configuration data in configuration XML files.Purpose of annotation is to attach additional information in the class or a meta-data of a class within its source code.

Annotaions Majorly used in any EJB class

In general our IDE(Jdeveloper/NetBeans/Eclipse)generates some annotaions by default when we create entities.


1.@Entity

 purpose
   To convert normal class into Entity we will use this annotation.we need to import javax.persistence.Entity API.

 Example
@Entity    //Now we convert this class Test to an entity which will interact                       with DB---step 2
public Class Test(){//general class —step 1
}

2.@ID

purpose
Used to mention the Primary Key in the entity.import javax.persistance.ID
example:
@Entity
Public class Test(){
@ID   //now mention like this column in the table will act as PK—step 4
private int emp_Id; //field in this class—step 3
//getter and setter 
}

3.@GeneratedValue

Purpose
To mention the feature of Primary key generation in our table.For example In our table EMP_ID if we select Autogenerate the  ID value.So in this scenerio we need to mention this feature in our entity using this annotaion and by sending strategy to generate the primary key.
Example

@Entity
public class Test(){
@ID
//we mentioned here the generation type of Primary key in our table.we have 
// 4 types of Strategies(AUTO,SEQUENCE,IDENTITY,TABLE)-----step 5
@GeneratedValue(Strategy=GenerationType.Identity)
private int emp_Id;
//getter and setter for this field here
}

4.@Table:

Purpose
If we need to use some other name for our class other than the original Table name,we will go for @Table Annotation.So By using this annotaion we will going to connect the original table with our entity class.

Example:

@Entity
@Table (name=”Test”)
//Original table name in DB,and Previously we've used same name to our class,so we no need to mention this annotation there.--step 7
Public class Sample() //class name differs from table name.--step 6
{
@ID
@GeneratedValue(Strategy=GenerationType.Identity)
private int emp_Id;
//getter and setter for this field here
}

NOTE:
convention over configuration:
Configure only when the default convention is not as per the requirements. Means here we can use these annotations to configure the original table/fields mapping.(we have to make JPA understand this default is not we want).

5.@Column

purpose

Used to mention the original column name in the table whenever our field name differs from the original column in the table we used.

Example

@Entity
@Table (name=”Test”)
Public class Sample()
{
@ID
@GeneratedValue(Strategy=GenerationType.Identity)
//By using column annotation we aregoing to map the column name in the table.previously we used same name to our field so we no need to mention this annotation there--step9
@column(name ="emp_Id")
private int employeeID;//we used different name for this field and this not the default name what we want---step8
//getter and setter for this field here
}

6.@singleton

Specifies that there will be only one instance of this bean will be created in Application server.(used in class level)

7.@Startup
Intance of this bean is created whenever the applicaiton is deployed in the server.(used in class level).So by marking the class with @startup,We are telling the container like eagerly create the  bean instance as soon as the application is deployed instead of waiting for some component to use it.

8.@PostContruct

First method to run when the instance is created.just like Main() method in normal Java class.

Example :

@Singleton//specifies that only one instance should be there in server
@Startup//instance of this bean(Test) is created when we deploy this                       application
public class Test(){
 //When we deploy this application in server this is methond automatically run //if we annotate this using this annotation
@PostConstruct
public void myTestMethod(){
//code
}
}

9.@PersistenceContext

This is used to inject the entitymanager class in our entity and we need to pass the Persistence Unit name in this to work with entity manager transactions like CRUD operations in our J2EE applications.

Example

@Singleton
@Startuppublic class Test()
{

@PersistenceContext(name="//Persistence context name as in persistence.xml file of our application//")

EntityManager em; //here we just create a object of EntityManager type,in desktop applications we need to create entitymanager by using entitymanager factory

@PostConstruct
public void myTestMethod(){
//code
//here we can use the EntityManager transactions by using em to interact with //DB like em.persist();em.remove();

}
}

10.@Lob

To specify the functionality of the database to store Large objects(LOB) like Images,documents,Presentaions,pdf files.we have two types.(Blob-binary Large Objects and Clob -charecter Large Objects).

Example:
@Lob
private byte[] image;
//getter and setter
public byte getImage(){
}
public void setImage(byte Image){

}

11.@Basic

 In the case like,Blod field not to be loaded eargerly(automatically),and to make the field to be loaded when ever someone access the field by using getter method of the field.


Example:
@Lob
@Basic(fetch=FetchType.Lazy)
// Lazy:Hint to the JPA Provider
This image field is loaded when some one access this field using getImage in our example.
//Eager:
This field is loaded automatically when the application is deployed 
private byte[] image;
//getter and setter
public byte getImage(){
}
public void setImage(byte Image){

}

12.@Enumerated

To prevent user to not to enter any other random  string into the field,and to restrict ther user to enter only specified values into that field,we will go for this Annotaion.

Example:
  • Lets consider Gender field.In our DB we would like to store M/F values in this field.But normally  when we create entities we use like

public class Test(){
private  String gender;

 public String getgender(){
}

public void setgender(String gender){
}
}
  • So as we declare gender field as String ,user may allowed to enter any other String value other than M/F as per our requirement.(male/female/....).To restrict the user not to enter any other random string into this field,WE have to create a enum class first.Create NewEnum class
public enum Gender{

M,     //These are the two constants in Gender enum class
F

}

  • Now we need to modify our Actual Test() Class as

@Entity
public class Test(){
@Enumerated(EnumType.String)//Here two types of enum types are there
1.Ordinal-Default type which will store 0/1 in DB
2.String-It will store the actual constants M/F which we have mensioned in our enum class into DB.
@Column (name="gender")
private  Gender gender;

 public Gender getgender(){
}

public void setgender(Gender gender){
}
}
  • Usage
Test.setgender(Gender.F);



13.@Temporal

If we have any Date field in our DB,By using this annotaion we can prevent the format of data to be stored in this field like date,time, date and time.....

Example

@Temporal(TemporalType.DATE/TemporalType.TIME/TemporalType.TIMESTAMP)
@Column(name="Join_date")
private Date HireDate;

14.@Transient

Used to mark a filed that should not be persistence in database when we save the entity data into database forexaple using em.persist().

Example:

@Transient
private String empString;

when we call em.persistence() this field empString wont be stored in DB.

:)




No comments:

Post a Comment

test