Annotations are powerful and easy way used to provide metadata about the class.They do not effect the operation of the code. They can be used to provide information about the class to the compiler. They can be used to replace the configuration files. Many applications scan files and detect annotated classes and get configured accordingly. I am using JPA API here to demonstrate you the usage of annotations. Please download ejb3-persistence.jar and include in your referenced libraries.
We do not need jboss to run JPA hibernate examples but we can copy these jar files in our webserver and we are good to go.
I hope you have gone through my previous post explaining how to configure and run the first hibernate example because this hibernate tutorial would cover the next steps. There I have used Conatct.hbm.xml file to map the Contact class to the contact table. Below I have explained how we can use annotations to replace the table hbm.xml files in Hibernate.
For beginners, the contact table contains following fields:
Create table CONTACT(
ID int(15),
FIRSTNAME varchar(50) ,
LASTNAME varchar(50),
EMAIL varchar(150));
ID int(15),
FIRSTNAME varchar(50) ,
LASTNAME varchar(50),
EMAIL varchar(150));
Change the Contact class as follows:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;
@Entity
@Table(name=”contact”)
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;
@Entity
@Table(name=”contact”)
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
@Column(name=”FIRSTNAME”)
public String getFirstName() {
return firstName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String string) {
firstName = string;
}
firstName = string;
}
@Column(name=”LASTNAME”)
public String getLastName() {
return lastName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String string) {
lastName = string;
}
lastName = string;
}
@Column(name=”EMAIL”)
public String getEmail() {
return email;
}
public void setEmail(String string) {
email = string;
}
public String getEmail() {
return email;
}
public void setEmail(String string) {
email = string;
}
@Id
@Column(name=”ID”)
public long getId() {
return id;
}
@Column(name=”ID”)
public long getId() {
return id;
}
public void setId(long l) {
id = l;
}
id = l;
}
}
Remove following lines from hibernate.cfg.xml
<mapping resource=”contact.hbm.xml”/>
In above class, we have added
@Entity
@Table(name=”contact”)
@Table(name=”contact”)
annotations.
@Entity declares the class as an entity bean. @Table annotation specifies compiler that the table name in db is ‘contact’. If @Table is not specified, then the classname will be considered as table name.
@Column specifies the column name of the table. We specify it for the getter method of the field. If not specified, the field name itself is considered as the column name.
Each table should have a primary key. This will be specified by @Id annotation.
Now we can test the above configuration using the client class as follows:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class MyExample {
public static void main(String[] args) {
Session session = null;
public static void main(String[] args) {
Session session = null;
try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
// This step will read hibernate.cfg.xml and prepare hibernate for use
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass(Contact.class);
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
session =sessionFactory.openSession();
cfg.addAnnotatedClass(Contact.class);
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
session =sessionFactory.openSession();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println(“Inserting Record”);
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName(“Smitha”);
contact.setLastName(“Rao”);
contact.setEmail(“smithaxxx@yahoo.com“);
session.save(contact);
System.out.println(“Done”);
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();
System.out.println(“Inserting Record”);
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName(“Smitha”);
contact.setLastName(“Rao”);
contact.setEmail(“smithaxxx@yahoo.com“);
session.save(contact);
System.out.println(“Done”);
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();
}
}
}
Run MyExample file.
Run MyExample file.
Output would be :
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Hibernate: insert into contact (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Hibernate: insert into contact (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)
Posted in: