Let's write a program where we will map a student table an Entity bean and will persist the data using session beans. Session beans in turn will use JPA (Java persistence api).
Let's write the entity bean first. This is a Student java class which is mapped to the Student table
//Entity annotation tells that this class is an entity bean.
//Table annotation is not mandatory. If it is not present than
//table name is same as class name
@Entity
@Table(name="STUDENT")
public class Student {
Long id;
String firstName;
String lastName;
//Id - maps the attribute to the primary key
//GeneratedValue - How the next key is generated
//Column - The column to which the attribute is mapped. Not mandatory
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="STUDENT_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name="LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
For those who want to create Student table but do not remember the SQL like me
//SQL Statement
Create Table Student (
STUDENT_ID INTEGER PRIMARY KEY,
FIRST_NAME VARCHAR(25),
LAST_NAME VARCHAR(25)
);
Now let's write the session bean. A session bean requires an interface. There are two kind of interfaces
- Local Interface: When session bean needs to be invoked from the same jvm, a local interface is required.
- Remote Interface: When session bean is invoked from the other jvm, a remote interface is required.
Local Interface:
//Annotating it with Local, makes it a local interface
@Local
public interface StudentServiceLocal {
public void saveStudent(String firstName,String lastName);
}
Remote:
//Annotating it with Remote, makes it a remote interface
@Remote
public interface StudentServiceRemote {
public void saveStudent(String firstName,String lastName);
}
Now the stateless bean
//Stateless session bean
@Stateless
public class StudentService implements StudentServiceLocal,
StudentServiceRemote{
//With PersistenceContext annotation, the resource is injected
//by the container.
//EntityManager is the JPA api used to interact with database.
@PersistenceContext(name="EJBBasics")
private EntityManager entityManager;
public void saveStudent(String firstName, String lastName) {
Student student = new Student();
//Id will be generated
//student.setId(100);
student.setFirstName(firstName);
student.setLastName(lastName);
//persisting the object
entityManager.persist(student);
}
Also we need to write persistence.xml, where we put the database connectivity details. The persistence.xml file is put inside META-INF directory. In this case, we are assuming Hibernate as the provider and we are running on Jboss. In JBoss, Hibernate is provider for entity beans and JPA specification
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="EJBBasics">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
Now let's write a client which will invoke the stateless bean.
public class StudentServiceClient {
static InitialContext context = null;
public static void main(String[] args){
init();
invokeSessionBean();
}
public static void invokeSessionBean(){
try{
//Lookup of stateless sessionBean. As we are invoking it from another
//jvm, we will look for remote interface.
StudentServiceRemote studentService =
(StudentServiceRemote)context.lookup("StudentService/remote");
studentService.saveStudent("Amitabh", "Bachhan");
}catch(NamingException ne){
ne.printStackTrace();
System.out.println("Could not find StudentService");
}
}
//the initialization assumes jboss server
static void init(){
Hashtable props = new Hashtable();
props.put(InitialContext.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");
props.put(InitialContext.PROVIDER_URL,
"jnp://localhost:1099");
props.put(InitialContext.URL_PKG_PREFIXES,
"org.jboss.naming:org.jboss.interfaces");
try{
context = new InitialContext(props);
}catch(NamingException ne){
ne.printStackTrace();
System.out.println("Could not find Context");
}
}
No comments:
Post a Comment