2 introduction toentitybeans


Published on

Introduction to Entity Bean

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

2 introduction toentitybeans

  1. 1. Session 2 EJB Creating First Entity Bean
  2. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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