SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Session 2

EJB
Creating First Entity
Bean
Introduction to Entity Bean
1. Entity Bean is something which represents data in persistence store (I
mean any persistence store, like database, files etc). For e.g. row in
database.

2. We can also say that, entity bean is object representation of persistence
store. For e.g. refer below fig.

Customer Table

ID : 42

ID

First_Name

City

First : John

42

John

California

87

Lin

Barcelona

65

Tom

Yugoslavia

Entity Bean

City : California

ID : 87
First : Lin
City : Barcelona

Entity Bean
Introduction to Entity Bean
1. There are 2 different things, say Entity & Entity Bean
2. Entity is real thing that entity bean represents, means entity is the
actual row in database.
3. If you delete the entity (row in database), the entity bean disintegrates.
4. And if entity bean dies on heap, it does delete entity (row in db).

Operations on Entity
1. Create new entity (SQL Insert)

2. Delete a entity (SQL Delete)
3. Update entity set (SQL Update)
4. Search/query on entities (SQL Select)
Creating Entity Bean
1. Lets create a sample entity bean.
2. I assume that you have basic understanding of ejb & you already created
sample Session bean. If not, then go back & refer Session-1 slide. That
will give you proper understanding of this session.
3. Let assume you have Customer table in database with ID, first_name &
city.
4. Where Id is your primary key. (notice ID-Primary Key here it is very
important in entity bean)
Customer Table

ID

First_Name

City

42

John

California

87

Lin

Barcelona

65

Tom

Yugoslavia
Rules for Building a Entity Bean
As you already created session bean (in 1st session), we
follow same steps to create entity bean
• Code to interfaces for bean (component & home)
• Code the bean class with all business method
• Create XML Deployment Descriptor, must be
name it as ejb-jar.xml
• Deploy bean in application server
Creating Component Interface
Component interface rules are simple & same as session bean

1. Component interface must extends EJBObject.
2. The component interface contains declarations of all
business mth which is to be defined by Bean class.
3. Its all mth must throws RemoteException
4. They can also thorws custom application (Checked)
Exception.
5. Its return type must be primitives/Serializable
Objs/Arrays/Collection of primitives or Serializable
Objs/Remote obj (These are called as RMI-IIOP
Complients).
6. In our case lets say we write business method which prints
customer data on console.
Component Interface Customer.java

package com.entity;

import javax.ejb.*;
import java.rmi.*;
public interface Customer extends EJBObject{

}

public void printCustomerData() throws
RemoteException;
Creating the Entity Bean Home Interface
The Home interface rules are Simple
1. Home interface must extends EJBHome

2. You can have multiple overloaded create() mth in home.
3. Your create method must throws CreateException & RemoteException.
4. You are required to put at least one finder mth for an entity bean home.
5. You can have many finder mth in home, but you must have
findByPrimaryKey(String key) mth in every home.
6. Your findByPrimaryKey(String key) mth must throws FinderException
7. The return type must be Component interface (in home interface only).
8. I am not including all entity points here as it may lead to lots of
confusion
9. Lets code the home interface
Home Interface CustomerHome.java
package com.entity;
import javax.ejb.*;
import java.rmi.*;
public interface CustomerHome extends EJBHome {
public Customer create(String astrName,String astrCity)
throws CreateException, RemoteException;
public Customer findByPrimaryKey(String
customerID) throws FinderException,
RemoteException;

}
Creating Bean Class CustomerBean.java
Rules for creating Entity Bean is simple but little different
from Session bean
1. Your bean class (which contains the actual definition of mth
or says business logic) must implements EntityBean
interface according to spec
2. According to java rule you have to implements all
unimplemented mth from interface
3. The printCustomerData() is your actual business mth, which
will be called by client
4. You need to implement create(String astrName,String
astrCity) which is coming from home interface.
5. We create this bean class part by part. Lets create bean
class with above mentioned details
Creating Bean Class CustomerBean.java
public class CustomerBean implements EntityBean{

private String customerId;
private String first_name;
private String city;

public void printCustomerData() {
System.out.println(this.customerId+""+this.first_name+"-"+this.city);
}
Implementing ejbCreate()
1. We have create() mth in home, this mth must be implemented by
bean class as ejbCreate().
2. The return type of ejbCreate() mth (not create() mth) must be
primary key class (we will see more about primary key class in next
few slides).
3. The ejbCreate() mth is responsible for creating the row in
database, that’s why it return type is primary key class.

4. The ejbCreate() mth must throws CreateException.
5. The return & argument type must be RMI-IIOP complient.
6. You also need to implement ejbPostCreate() which is same as
ejbCreate(). This mth invoke after ejbCreate so that you can get
chance to do any other stuff after database row creation.
7. For now I am providing empty definition of this mth.
Implementing ejbCreate()
public String ejbCreate(String astrName,String astrCity) throws CreateException{
this.first_name = astrName;
this.city = astrCity;
this.customerId = this.getPK();
String insertQry = "insert into customer (customer_id,first_name,city) values (?,?,?)";
try{

Connection conn = getDBConnection();
PreparedStatement ps = conn.prepareStatement(insertQry);
ps.setString(1,this.customerId);
ps.setString(2,this.first_name);
ps.setString(3,this.city);
int i = ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
throw new CreateException(e.getMessage());
}
return customerId;
}
Implementing ejbCreate()
public void ejbPostCreate(String first,String city)throws CreateException{
}

private String dbName = "jdbc.test.entity";
public Connection getDBConnection(){
Connection conn = null;
try{
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup(this.dbName);
conn = ds.getConnection();
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
public String getPK(){
return ""+(int)(Math.random()*32);
}
Implementing EntityBean mth
1.

You also need to implements below EntityBean interface mths
ejbActivate()
ejbLoad()
ejbPassivate()
ejbRemove()
ejbStore()
setEntityContext(EntityContext ctx)
unsetEntityContext()

2.

Three mth are very important for entity bean point of view, they are
ejbLoad(), ejbStore() & setEntityContext().

3. setEntityContext() is called when you create the bean, it is best chance to to
save your context object.
4. This EntityContext object is responsible for giving you primaryKey.
5. You use this object in ejbStore() & ejbLoad() (we will see this in next few
slides).
6. The other methods are also important but I not able cover all of them.
Implementing EntityBean mth
private EntityContext ctx;
public void setEntityContext(EntityContext ctx) throws EJBException,
RemoteException {
this.ctx = ctx;
}
public void unsetEntityContext() throws EJBException,
RemoteException {}
public void ejbActivate() throws EJBException, RemoteException {}

public void ejbPassivate() throws EJBException, RemoteException {}
public void ejbRemove() throws RemoveException, EJBException,
RemoteException {}
Implementing EntityBean mth
1.

ejbLoad() is called before calling any business mth, so that bean get chance
to synchronize its state with database.

2. So what do you think what should be in ejbLoad()???
3. Yes, ejbLoad() mth should contain the select data statement from database.
4. But how you get the particular row from database, if you don’t have primary
key?
5.

Remember we already set EntityContext object in setEntityContext() mth.

6.

Confuse!!! Check the next slide.
Implementing EntityBean mth
public void ejbLoad() throws EJBException, RemoteException {
String cust_id = (String)this.ctx.getPrimaryKey();
ResultSet rs = null;
String selectQry = "Select customer_id,first_name,city from Customer
where customer_id=?";
try{
Connection conn = getDBConnection();
PreparedStatement ps = conn.prepareStatement(selectQry);
ps.setString(1,cust_id);
rs = ps.executeQuery();
if(rs.next()){
this.customerId = rs.getString(1);
this.first_name = rs.getString(2);
this.city = rs.getString(3);
}
}catch(Exception e){
e.printStackTrace();
}
}
Implementing EntityBean mth
1.

As ejbLoad() is called before calling any business mth, the same way
ejbStore() is called after calling business mth.

2. The reason is same to stay sync with database.
3. So what do you think what should be in ejbStore()???
4. Yes ejbStore() mth should contain the update data statement for database.

5. You might confuse why ejbStore() call after business mth.
6. The answer is simple, when client call any business mth, there is high
probability that business mth will change the state of bean.
7.

Confuse!!! next slide will give you a clear picture.
Client call buss mth
ejbLoad()

updateCustData()

ID : 42
First : John
City : California

updateCustData()
ID : 42
Select Data
from DB

First : John Dhere
City : California

ejbStore()
DB

ID : 42
Update Data

First : John Dhere

City : California
Implementing EntityBean mth
public void ejbStore() throws EJBException, RemoteException {

String udpateQry = "update Customer set first_name=?,city=?
where customer_id=?";
try{

}

Connection conn = getDBConnection();
PreparedStatement ps = conn.prepareStatement(udpateQry);
ps.setString(1,this.first_name);
ps.setString(2,this.city);
ps.setString(3,this.customerId);
ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}
Implementing ejbFindByPrimaryKey() mth
1.

ejbFindByPrimaryKey() mth use to find the existing entity bean.

2. There are simple rules for ejbFindByPrimaryKey() mth
3.

You can have multiple overloaded mth in home & same implementation in bean
class.

4.

This mth usually take & return the primary key as argument & return type,
which is specified in ejb-jar.xml (we will see this in next few slides)

5.

This mth contains the select statement for bean which must return only one
row, i.e. this mth is single entity finder.

6. For multi entity finder there are other finder methods.

7. Now lets implement ejbFindByPrimaryKey() mth
Implementing ejbFindByPrimaryKey() mth
public String ejbFindByPrimaryKey(String custId){
String selectQry = "Select customer_id,first_name,city from
Customer where customer_id=?";
try{
Connection conn = getDBConnection();
PreparedStatement ps = conn.prepareStatement(selectQry);
ps.setString(1,custId);
ResultSet rs = ps.executeQuery();
if(rs.next()){
this.customerId = rs.getString(1);
this.first_name = rs.getString(2);
this.city = rs.getString(3);
}
}catch(Exception e){
e.printStackTrace();
}
return custId;
}
Binding all in ejb-jar.xml
1. Now lets bind all stuff together in ejb-jar.xml
2. As this is entity bean we use entity tag, for session bean we
use session tag.
3. We added three new tag i.e. <reentrant>,<prim-key-class> &
<persistence-type>

4. As we know we are returning primary key of database from
ejbCreate & ejbFindByPrimaryKey mths we must define
<prim-key-class> in DD (deployment descriptor) so that
container can understand this is primary key.
5. You can also create your custom primary key class & declare
in DD (in <prim-key-class> tag).
Sample ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee" version="2.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd">
<enterprise-beans>
<entity>
<ejb-name>DemoCustomer</ejb-name>
<home>com.entity.CustomerHome</home>
<remote>com.entity.Customer</remote>
<ejb-class>com.entity.CustomerBean</ejb-class>
<persistence-type>Bean</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>false</reentrant>
</entity>
</enterprise-beans>
</ejb-jar>
Sample App Structure
•

Now you have to create the jar of all compiled class with
below structure, which is same as session bean example.
DemoCustomer-Entity.jar
com
entity
Customer.class
CustomerHome.class
META-INF

CustomerBean.class
ejb-jar.xml
glassfish-ejb-jar.xml
Deploying & Calling the Bean mth
•
•
•
•

You also need to create vendor specific DD, as I m using
glassfish server for app deployment so I have glassfish-ejbjar.xml
We will see the deployments of ejb & web application (part)
in later.
Now I am writing the plane jsp to call the Bean mth.
You need to deploy this jsp(war) file in glassfish & run the
jsp.
Client CustomerClient.jsp
<html>
<body>
<%
try{

InitialContext ic = new InitialContext();
Object obj = ic.lookup("DemoCustomerEntity");
Customer customer = home.create("John","California");
System.out.println("Customer Id : "+customer.getPrimaryKey());
customer.printCustomerData();

Customer customer = home.findByPrimaryKey("31");
System.out.println("Customer Id : "+customer.getPrimaryKey());
customer.printCustomerData();
}catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
Thank you
• If you have any doubts in tutorial, please feel free to
contact me on ashishkirpan@gmail.com
• Sorry for spelling & grammar mistakes :)

Have a fun with EJB

Weitere ähnliche Inhalte

Was ist angesagt?

Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
Java script introducation & basics
Java script introducation & basicsJava script introducation & basics
Java script introducation & basicsH K
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mockskenbot
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...ssuserd6b1fd
 
重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1Chris Huang
 
重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2Chris Huang
 
Object Calisthenics em Go
Object Calisthenics em GoObject Calisthenics em Go
Object Calisthenics em GoElton Minetto
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
 
Ip project work test your knowledge
Ip project work test your knowledgeIp project work test your knowledge
Ip project work test your knowledgeKïShørê Choudhary
 
HATARI: Raising Risk Awareness
HATARI: Raising Risk AwarenessHATARI: Raising Risk Awareness
HATARI: Raising Risk AwarenessThomas Zimmermann
 
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...ssuserd6b1fd
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
 

Was ist angesagt? (20)

Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Java script introducation & basics
Java script introducation & basicsJava script introducation & basics
Java script introducation & basics
 
Tdd.eng.ver
Tdd.eng.verTdd.eng.ver
Tdd.eng.ver
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
 
Clean code
Clean codeClean code
Clean code
 
Java
JavaJava
Java
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5  b...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 3 of 5 b...
 
重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1
 
重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2
 
Object Calisthenics em Go
Object Calisthenics em GoObject Calisthenics em Go
Object Calisthenics em Go
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
 
Clean code
Clean codeClean code
Clean code
 
Martin Roy Portfolio
Martin Roy PortfolioMartin Roy Portfolio
Martin Roy Portfolio
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Ip project work test your knowledge
Ip project work test your knowledgeIp project work test your knowledge
Ip project work test your knowledge
 
HATARI: Raising Risk Awareness
HATARI: Raising Risk AwarenessHATARI: Raising Risk Awareness
HATARI: Raising Risk Awareness
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
 
Eclipse Banking Day
Eclipse Banking DayEclipse Banking Day
Eclipse Banking Day
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 

Ähnlich wie 2 introduction toentitybeans

Ejb 2.0
Ejb 2.0Ejb 2.0
Ejb 2.0sukace
 
Session 6 Tp6
Session 6 Tp6Session 6 Tp6
Session 6 Tp6phanleson
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jniPeter Hagemeyer
 
please code in c#- please note that im a complete beginner- northwind.docx
please code in c#- please note that im a complete beginner-  northwind.docxplease code in c#- please note that im a complete beginner-  northwind.docx
please code in c#- please note that im a complete beginner- northwind.docxAustinaGRPaigey
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5phanleson
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Vagif Abilov
 
Enterprise java beans(ejb)
Enterprise java beans(ejb)Enterprise java beans(ejb)
Enterprise java beans(ejb)vikram singh
 
Enterprise Java Beans( E)
Enterprise  Java  Beans( E)Enterprise  Java  Beans( E)
Enterprise Java Beans( E)vikram singh
 
Session 3 Tp3
Session 3 Tp3Session 3 Tp3
Session 3 Tp3phanleson
 
Enterprise java beans(ejb)
Enterprise java beans(ejb)Enterprise java beans(ejb)
Enterprise java beans(ejb)vikram singh
 
Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) update 2Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) update 2vikram singh
 
H U F F M A N Algorithm
H U F F M A N AlgorithmH U F F M A N Algorithm
H U F F M A N AlgorithmJade Danial
 
Session 7 Tp7
Session 7 Tp7Session 7 Tp7
Session 7 Tp7phanleson
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
 

Ähnlich wie 2 introduction toentitybeans (20)

Ejb examples
Ejb examplesEjb examples
Ejb examples
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
Ejb 2.0
Ejb 2.0Ejb 2.0
Ejb 2.0
 
Session 6 Tp6
Session 6 Tp6Session 6 Tp6
Session 6 Tp6
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jni
 
please code in c#- please note that im a complete beginner- northwind.docx
please code in c#- please note that im a complete beginner-  northwind.docxplease code in c#- please note that im a complete beginner-  northwind.docx
please code in c#- please note that im a complete beginner- northwind.docx
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
Ecom lec4 fall16_jpa
Ecom lec4 fall16_jpaEcom lec4 fall16_jpa
Ecom lec4 fall16_jpa
 
Enterprise java beans(ejb)
Enterprise java beans(ejb)Enterprise java beans(ejb)
Enterprise java beans(ejb)
 
Enterprise Java Beans( E)
Enterprise  Java  Beans( E)Enterprise  Java  Beans( E)
Enterprise Java Beans( E)
 
Ejb3 Presentation
Ejb3 PresentationEjb3 Presentation
Ejb3 Presentation
 
Windows Phone Launchers and Choosers
Windows Phone Launchers and ChoosersWindows Phone Launchers and Choosers
Windows Phone Launchers and Choosers
 
Practical
PracticalPractical
Practical
 
Session 3 Tp3
Session 3 Tp3Session 3 Tp3
Session 3 Tp3
 
Enterprise java beans(ejb)
Enterprise java beans(ejb)Enterprise java beans(ejb)
Enterprise java beans(ejb)
 
Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) update 2Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) update 2
 
H U F F M A N Algorithm
H U F F M A N AlgorithmH U F F M A N Algorithm
H U F F M A N Algorithm
 
Session 7 Tp7
Session 7 Tp7Session 7 Tp7
Session 7 Tp7
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 

Kürzlich hochgeladen

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 

Kürzlich hochgeladen (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 

2 introduction toentitybeans

  • 2. Introduction to Entity Bean 1. Entity Bean is something which represents data in persistence store (I mean any persistence store, like database, files etc). For e.g. row in database. 2. We can also say that, entity bean is object representation of persistence store. For e.g. refer below fig. Customer Table ID : 42 ID First_Name City First : John 42 John California 87 Lin Barcelona 65 Tom Yugoslavia Entity Bean City : California ID : 87 First : Lin City : Barcelona Entity Bean
  • 3. Introduction to Entity Bean 1. There are 2 different things, say Entity & Entity Bean 2. Entity is real thing that entity bean represents, means entity is the actual row in database. 3. If you delete the entity (row in database), the entity bean disintegrates. 4. And if entity bean dies on heap, it does delete entity (row in db). Operations on Entity 1. Create new entity (SQL Insert) 2. Delete a entity (SQL Delete) 3. Update entity set (SQL Update) 4. Search/query on entities (SQL Select)
  • 4. Creating Entity Bean 1. Lets create a sample entity bean. 2. I assume that you have basic understanding of ejb & you already created sample Session bean. If not, then go back & refer Session-1 slide. That will give you proper understanding of this session. 3. Let assume you have Customer table in database with ID, first_name & city. 4. Where Id is your primary key. (notice ID-Primary Key here it is very important in entity bean) Customer Table ID First_Name City 42 John California 87 Lin Barcelona 65 Tom Yugoslavia
  • 5. Rules for Building a Entity Bean As you already created session bean (in 1st session), we follow same steps to create entity bean • Code to interfaces for bean (component & home) • Code the bean class with all business method • Create XML Deployment Descriptor, must be name it as ejb-jar.xml • Deploy bean in application server
  • 6. Creating Component Interface Component interface rules are simple & same as session bean 1. Component interface must extends EJBObject. 2. The component interface contains declarations of all business mth which is to be defined by Bean class. 3. Its all mth must throws RemoteException 4. They can also thorws custom application (Checked) Exception. 5. Its return type must be primitives/Serializable Objs/Arrays/Collection of primitives or Serializable Objs/Remote obj (These are called as RMI-IIOP Complients). 6. In our case lets say we write business method which prints customer data on console.
  • 7. Component Interface Customer.java package com.entity; import javax.ejb.*; import java.rmi.*; public interface Customer extends EJBObject{ } public void printCustomerData() throws RemoteException;
  • 8. Creating the Entity Bean Home Interface The Home interface rules are Simple 1. Home interface must extends EJBHome 2. You can have multiple overloaded create() mth in home. 3. Your create method must throws CreateException & RemoteException. 4. You are required to put at least one finder mth for an entity bean home. 5. You can have many finder mth in home, but you must have findByPrimaryKey(String key) mth in every home. 6. Your findByPrimaryKey(String key) mth must throws FinderException 7. The return type must be Component interface (in home interface only). 8. I am not including all entity points here as it may lead to lots of confusion 9. Lets code the home interface
  • 9. Home Interface CustomerHome.java package com.entity; import javax.ejb.*; import java.rmi.*; public interface CustomerHome extends EJBHome { public Customer create(String astrName,String astrCity) throws CreateException, RemoteException; public Customer findByPrimaryKey(String customerID) throws FinderException, RemoteException; }
  • 10. Creating Bean Class CustomerBean.java Rules for creating Entity Bean is simple but little different from Session bean 1. Your bean class (which contains the actual definition of mth or says business logic) must implements EntityBean interface according to spec 2. According to java rule you have to implements all unimplemented mth from interface 3. The printCustomerData() is your actual business mth, which will be called by client 4. You need to implement create(String astrName,String astrCity) which is coming from home interface. 5. We create this bean class part by part. Lets create bean class with above mentioned details
  • 11. Creating Bean Class CustomerBean.java public class CustomerBean implements EntityBean{ private String customerId; private String first_name; private String city; public void printCustomerData() { System.out.println(this.customerId+""+this.first_name+"-"+this.city); }
  • 12. Implementing ejbCreate() 1. We have create() mth in home, this mth must be implemented by bean class as ejbCreate(). 2. The return type of ejbCreate() mth (not create() mth) must be primary key class (we will see more about primary key class in next few slides). 3. The ejbCreate() mth is responsible for creating the row in database, that’s why it return type is primary key class. 4. The ejbCreate() mth must throws CreateException. 5. The return & argument type must be RMI-IIOP complient. 6. You also need to implement ejbPostCreate() which is same as ejbCreate(). This mth invoke after ejbCreate so that you can get chance to do any other stuff after database row creation. 7. For now I am providing empty definition of this mth.
  • 13. Implementing ejbCreate() public String ejbCreate(String astrName,String astrCity) throws CreateException{ this.first_name = astrName; this.city = astrCity; this.customerId = this.getPK(); String insertQry = "insert into customer (customer_id,first_name,city) values (?,?,?)"; try{ Connection conn = getDBConnection(); PreparedStatement ps = conn.prepareStatement(insertQry); ps.setString(1,this.customerId); ps.setString(2,this.first_name); ps.setString(3,this.city); int i = ps.executeUpdate(); }catch(Exception e){ e.printStackTrace(); throw new CreateException(e.getMessage()); } return customerId; }
  • 14. Implementing ejbCreate() public void ejbPostCreate(String first,String city)throws CreateException{ } private String dbName = "jdbc.test.entity"; public Connection getDBConnection(){ Connection conn = null; try{ InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup(this.dbName); conn = ds.getConnection(); }catch(Exception e){ e.printStackTrace(); } return conn; } public String getPK(){ return ""+(int)(Math.random()*32); }
  • 15. Implementing EntityBean mth 1. You also need to implements below EntityBean interface mths ejbActivate() ejbLoad() ejbPassivate() ejbRemove() ejbStore() setEntityContext(EntityContext ctx) unsetEntityContext() 2. Three mth are very important for entity bean point of view, they are ejbLoad(), ejbStore() & setEntityContext(). 3. setEntityContext() is called when you create the bean, it is best chance to to save your context object. 4. This EntityContext object is responsible for giving you primaryKey. 5. You use this object in ejbStore() & ejbLoad() (we will see this in next few slides). 6. The other methods are also important but I not able cover all of them.
  • 16. Implementing EntityBean mth private EntityContext ctx; public void setEntityContext(EntityContext ctx) throws EJBException, RemoteException { this.ctx = ctx; } public void unsetEntityContext() throws EJBException, RemoteException {} public void ejbActivate() throws EJBException, RemoteException {} public void ejbPassivate() throws EJBException, RemoteException {} public void ejbRemove() throws RemoveException, EJBException, RemoteException {}
  • 17. Implementing EntityBean mth 1. ejbLoad() is called before calling any business mth, so that bean get chance to synchronize its state with database. 2. So what do you think what should be in ejbLoad()??? 3. Yes, ejbLoad() mth should contain the select data statement from database. 4. But how you get the particular row from database, if you don’t have primary key? 5. Remember we already set EntityContext object in setEntityContext() mth. 6. Confuse!!! Check the next slide.
  • 18. Implementing EntityBean mth public void ejbLoad() throws EJBException, RemoteException { String cust_id = (String)this.ctx.getPrimaryKey(); ResultSet rs = null; String selectQry = "Select customer_id,first_name,city from Customer where customer_id=?"; try{ Connection conn = getDBConnection(); PreparedStatement ps = conn.prepareStatement(selectQry); ps.setString(1,cust_id); rs = ps.executeQuery(); if(rs.next()){ this.customerId = rs.getString(1); this.first_name = rs.getString(2); this.city = rs.getString(3); } }catch(Exception e){ e.printStackTrace(); } }
  • 19. Implementing EntityBean mth 1. As ejbLoad() is called before calling any business mth, the same way ejbStore() is called after calling business mth. 2. The reason is same to stay sync with database. 3. So what do you think what should be in ejbStore()??? 4. Yes ejbStore() mth should contain the update data statement for database. 5. You might confuse why ejbStore() call after business mth. 6. The answer is simple, when client call any business mth, there is high probability that business mth will change the state of bean. 7. Confuse!!! next slide will give you a clear picture.
  • 20. Client call buss mth ejbLoad() updateCustData() ID : 42 First : John City : California updateCustData() ID : 42 Select Data from DB First : John Dhere City : California ejbStore() DB ID : 42 Update Data First : John Dhere City : California
  • 21. Implementing EntityBean mth public void ejbStore() throws EJBException, RemoteException { String udpateQry = "update Customer set first_name=?,city=? where customer_id=?"; try{ } Connection conn = getDBConnection(); PreparedStatement ps = conn.prepareStatement(udpateQry); ps.setString(1,this.first_name); ps.setString(2,this.city); ps.setString(3,this.customerId); ps.executeUpdate(); }catch(Exception e){ e.printStackTrace(); }
  • 22. Implementing ejbFindByPrimaryKey() mth 1. ejbFindByPrimaryKey() mth use to find the existing entity bean. 2. There are simple rules for ejbFindByPrimaryKey() mth 3. You can have multiple overloaded mth in home & same implementation in bean class. 4. This mth usually take & return the primary key as argument & return type, which is specified in ejb-jar.xml (we will see this in next few slides) 5. This mth contains the select statement for bean which must return only one row, i.e. this mth is single entity finder. 6. For multi entity finder there are other finder methods. 7. Now lets implement ejbFindByPrimaryKey() mth
  • 23. Implementing ejbFindByPrimaryKey() mth public String ejbFindByPrimaryKey(String custId){ String selectQry = "Select customer_id,first_name,city from Customer where customer_id=?"; try{ Connection conn = getDBConnection(); PreparedStatement ps = conn.prepareStatement(selectQry); ps.setString(1,custId); ResultSet rs = ps.executeQuery(); if(rs.next()){ this.customerId = rs.getString(1); this.first_name = rs.getString(2); this.city = rs.getString(3); } }catch(Exception e){ e.printStackTrace(); } return custId; }
  • 24. Binding all in ejb-jar.xml 1. Now lets bind all stuff together in ejb-jar.xml 2. As this is entity bean we use entity tag, for session bean we use session tag. 3. We added three new tag i.e. <reentrant>,<prim-key-class> & <persistence-type> 4. As we know we are returning primary key of database from ejbCreate & ejbFindByPrimaryKey mths we must define <prim-key-class> in DD (deployment descriptor) so that container can understand this is primary key. 5. You can also create your custom primary key class & declare in DD (in <prim-key-class> tag).
  • 25. Sample ejb-jar.xml <?xml version="1.0" encoding="UTF-8"?> <ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee" version="2.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"> <enterprise-beans> <entity> <ejb-name>DemoCustomer</ejb-name> <home>com.entity.CustomerHome</home> <remote>com.entity.Customer</remote> <ejb-class>com.entity.CustomerBean</ejb-class> <persistence-type>Bean</persistence-type> <prim-key-class>java.lang.String</prim-key-class> <reentrant>false</reentrant> </entity> </enterprise-beans> </ejb-jar>
  • 26. Sample App Structure • Now you have to create the jar of all compiled class with below structure, which is same as session bean example. DemoCustomer-Entity.jar com entity Customer.class CustomerHome.class META-INF CustomerBean.class ejb-jar.xml glassfish-ejb-jar.xml
  • 27. Deploying & Calling the Bean mth • • • • You also need to create vendor specific DD, as I m using glassfish server for app deployment so I have glassfish-ejbjar.xml We will see the deployments of ejb & web application (part) in later. Now I am writing the plane jsp to call the Bean mth. You need to deploy this jsp(war) file in glassfish & run the jsp.
  • 28. Client CustomerClient.jsp <html> <body> <% try{ InitialContext ic = new InitialContext(); Object obj = ic.lookup("DemoCustomerEntity"); Customer customer = home.create("John","California"); System.out.println("Customer Id : "+customer.getPrimaryKey()); customer.printCustomerData(); Customer customer = home.findByPrimaryKey("31"); System.out.println("Customer Id : "+customer.getPrimaryKey()); customer.printCustomerData(); }catch(Exception e){ e.printStackTrace(); } %> </body> </html>
  • 29. Thank you • If you have any doubts in tutorial, please feel free to contact me on ashishkirpan@gmail.com • Sorry for spelling & grammar mistakes :) Have a fun with EJB