Bean-Managed Persistent Entity Beans – EJB2- Student Example

download Bean-Managed Persistent Entity Beans – EJB2- Student Example

of 35

Transcript of Bean-Managed Persistent Entity Beans – EJB2- Student Example

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    1/35

    Bean-Managed Persistent Entity Beans EJB2- Student Example

    I. Khi nim1. Bean-Managed Persistence

    - Vi BMP, ngi vit bean phi vit tng minh cc triu gi dng truy xut c s d liu.Truy xut d liu c th c m ha bn trong bean hoc ng gi trong i tng truy xut dliu nh mt phn ca bean.

    - BMP c chn dng khi:

    Mun iu khin hon ton vic truy xut c s d liu, nh vit cc truy vn ti u. Mun vit thao tc truy xut cho cc h qun tr c s d liu c, ERP Ni lu tr khng phi l mt h qun tr c s d liu.

    Tuy nhin, mi lin h qu cht ch gia BMP v c s d liu n thao tc trn l mt yim ca BMP.

    - BMP cng nh cc Entity Bean khc, c 3 trng thi:

    Does Not Exits: khng tn ti trong b nh. Pooled: c mt trong instance pool nhng cha sn sng hot ng. Ready: sn sng p ng cc yu cu t client cho EJB Object y nhim n.

    2. Vng i ca Entity Bean

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    2/35

    - Vng i ca bean bt u khi container giClass.newInstance(), sau lin kt bean vii tng cha thng tin mi trng bng cch gi phng thcsetEntityContext(), beanhnh thnh v c t vo instance pool (trng thi Pooled). Bean trong pool khng linkt vi bt k c s d liu v mt EJB Object no, container c th dng bean ny thc hin bt k mt phng thc home hoc finder no.

    - Khi container chn bean phc v mt triu gi ca clientn EJB Object, bean chuynsang trng thi Ready, lin ktvi c s d liu v vi EJBObject c th. C hai cchchuyn n trng thi Ready:

    Client gi phng thccreate() ca HomeObject v nh vy

    container s gi ln ltcc phng thcejbCreate() vejbPostCreate().

    Container gi phngthcejbActivate()kch hot li cc beanang th ng, cp phtti nguyn nh sockectcho bean..

    - Trong trng thi Ready, bean

    lin kt vi mt EJB Object.Container gi cc businessmethod trn bean, c EJB Object y nhim n. Container cng ng b trng thi ca beanvi c s d liu bng cch dng cc phng thcejbLoad()v ejbStore().

    - Container c th chuyn bean tr li trng thi Pooled, iu ny xy ra khi:

    Client gi phng thcremove()v nh vy container s gi phng thcejbRemove(). Container gi phng thcejbPassivate() chuyn bean sang trng thi th ng.

    - Cui vng i ca bean, container s loi bean ra khi pool v gi phng thcunsetEntityContext()tch bean ra khi i tng cha thng tin mi trng lin quan n n.

    3. Cc phng thc callback v cc Finder

    - Phng thcejbCreate() c gi khi ghi trng thi ca bean vo c s d liu, bean lin ktvi i din EJB Object ca n. Nh vy mt hng mi c to v c ghi vo c s d lic t EJB t 2.0 tr i cho php np chng phng thc ny di dngejbCreate(),cn c phng thccreate()tng ng trong home interface. Lnh SQL tng ng lINSERT.

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    3/35

    - Phng thcejbPostCreate()c gi sau khi giejbCreate(). Phng thc ny dng cho mt stc v nh: gii quyt cc vn pht sinh khi chn hng vo c s d liu, thit lp mi quan gia cc bean c lin quan vi nhau sau khi chng hnh thnh, chuyn tham chiu ca bean nmt bean khc, thay i cc thng s transaction,

    - Phng thcejbRemove()dng tch mi lin kt gia bean vi d liu tng ng trong c s d liu. Lnh SQL tng ng lDELETE.

    - Phng thcejbLoad() dng np d liu t c s d liu vo bean tng ng (cn gi lrefresh d liu), ng b trng thi ca bean vi hng d liu m n nh x. Phng thc nc gi trc khi cc business method c thc hin. Lnh SQL tng ng lSELECT.

    - Phng thcejbStore() dng ghi trng thi (d liu ca lp bean) vo c s d liu, ng btrng thi ca bean vi hng d liu m n nh x. Phng thc ny c gi sau khi businesmethod thc hin xong. Lnh SQL tng ng lUPDATE.

    - Phng thcsetEntityContext() dng lin kt bean vi i tng javax.ejb.EntityContext.Thng qua i tng ny nhn nhng thng tin lin quan n mi trng.

    - Phng thcunsetEntityContext() tch bean khi mi trng, gii phng ti nguyn dosetEntityContext()cp, thc th bean sn sng hy.

    - Mi phng thc c tnfind()trong home interface, phi c mt phng thcejbFind()tng ng vi cng i s trong lp bean. Khi mt phng thcfind() ctriu gi trn Home Object, container s y nhim phng thcejbFind() tng ng trn beanthc hin yu cu. Kt qu tr v ca cc phng thcfind() l mt i tng kiu EJB Objecthoc mtCollectioncc i tng kiu EJB Object, trong lc kt qu tr v ca cc phng thcejbFind() l kha chnh hoc mtCollectioncc kha chnh.

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    4/35

    1. Container ng k tt c cc bean c trin khai vi JNDI.

    2. Client tm thy (lookup()) home interface ca bean thng qua JNDI.

    3. Client dng home interface to ra EJB Object. Khi client triu gi phng thccreate() ca home interface, container triu gi phng thcejbCreate() tng ngca bean.

    4. Client triu gi cc business method trn EJB Object, container y nhim cc ligi ny n bean.

    5. Client gi phng thcremove() ca EJB Object, container giejbRemove()ca bean tng ng.

    Container ng b trng thi ca bean vi c s d liu bng cch dng cc phngthcejbLoad()v ejbStore().

    5. Lp Primary Key (kha chnh)

    - Primary Key l mt i tng dng ch nh duy nht mt entity bean. Primary Key c th lkiu serializable bt k no, bao gm cc kiu c sn (Integer, Double, String, ) hoc cc lpc nh ngha bi ngi pht trin bean.

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    5/35

    - C hai kiu Primary Key:

    Single-Field: Primary Key nh x vi mt field nh ngha trong lp bean. Compound: lp Primary Key (ci t giao din java.io.Serializable) do ngi dng nh

    ngha nh x n nhiu field trong lp bean.

    - V d Coumpound Primary Key:

    public class ShipPK implements java.io.Serializable {

    public String name;

    public String registration;

    public ShipPK() { }

    public ShipPK( String name, String registration ) {

    this.name = name;

    this.registration = registration;

    }

    public String getName() { return name; }

    public String getRegistration( ) { return registration; }

    public boolean equals( Object obj ) {

    if ( obj == null || !( obj instanceof ShipPK ) ) return false;

    ShipPK other = ( ShipPK )obj;

    if ( this.name.equals(other.name) && this.registration.equals( other.registration ) )

    return true;

    else

    return false;

    }

    public int hashCode() { return name.hashCode( )^registration.hashCode( ); }

    public String toString( ) { return name+ +registration; }

    }

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    6/35

    Ch khi to lp Primary Key:

    Phi ci t giao din java.io.Serializable. Cc field phipublic. Cn nh ngha cc phng thcequals()v hashCode() ch nh Primary Key trong

    Collection.

    - Phng thcfindByPrimaryKey()ca home interface nhn i s l mt Primary Key v tr vmt i tng kiu remote interface:

    public Ship findByPrimaryKey( ShipPK primarykey )throws FinderException, RemoteException;

    - Lp bean phi c nhng field tng ng vi d liu ring ca lp Primary Key. Phng thejbCreate() ca lp bean cng tr v mt i tng Primary Key:

    public ShipPK ejbCreate( String name, String registration ) {

    setName( name );

    setRegistration(registration);

    // database insert logic

    return new ShipPK( name, registration );

    }

    public void ejbPostCreate( String name, String registration ) { }

    - Deployment Descriptor cng phi nh ngha lp Primary Key cn cho trin khai:cShipPK

    II. Thit k

    A. To BMP

    1. To remote interface

    packagestudent;

    import java.rmi.RemoteException;

    import javax.ejb.EJBObject;

    public interface StudentRemoteextendsEJBObject{

    public String getName()throws RemoteException;

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    7/35

    public String getStudentId()throws RemoteException;

    public voidsetName(String name)throws RemoteException;

    }

    2. To home interface

    packagestudent;

    import java.rmi.RemoteException;

    import java.util.Enumeration;

    import javax.ejb.CreateException;

    import javax.ejb.EJBHome;import javax.ejb.FinderException;

    public interface StudentRemoteHomeextendsEJBHome{

    public StudentRemote create(String StudentId,String name)throws CreateException, RemoteException;

    public StudentRemote findByPrimaryKey(String StudentId)throws FinderException, RemoteException;

    public Enumeration findByName(String name)throws FinderException, RemoteException;

    }3. Lp Primary Key (kha chnh)

    - Primary Key nh ngha thuc tnh dng nh v mt hng d liu (tc mt bean) trong c sd liu. Thng ch cn mt thuc tnh, nhng i khi cn mt b thuc tnh mi xc nh mt hng duy nht trong bng. Nu Primary Key ch l kiu serializable c sn th khng cn phvit lp Primary Key.

    4. To lp EJB

    - Lp EJB cho BMP vit phc tp v ngi cung cp bean phi chu trch nhim truy xut c sd liu. Bao gm:

    D liu ring (cc field) v cc accesors/mutators (cc business method) Cc phng thc h tr Cc phng thc callback v cc Finder

    a) D liu ring ca bean v cc accesor

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    8/35

    - Bean phi c d liu ring, chnh l th hin cc field ca hng d liu m bean nh x trong nD liu ring ny c truy xut (vo/ra) bi ccgetter/setter (gi chung l cc accessor). ycng l cc business method c client triu gi. Tip u ngset/get l quy c, khng phi bt buc.

    private String studentId;

    private String name;

    public String getName() { return name; }

    public String getStudentId () { return studentId; }

    public void setName( String name ) { this.name = name; }

    b) Phng thc h tr

    - d ci t, nn vit trc cc phng thc h tr (helper method, cn gi l utility methodCc phng thc ny ch dng trong lp nn phm vi truy xut thng lprivate. Bao gm:

    To kt ni c s d liu: kt ni ny lu trong i tng Connection, d liu ring ca bean. Kt ni c s d liu c thc hin thng qua JDBC-ODBC

    private Connection makeConnection()throws Exception{

    Connection con=null;

    Class. forName (sun.jdbc.odbc.JdbcOdbcDriver);

    String url=jdbc:odbc:student;con=DriverManager. getConnection (url);

    return con;

    }

    Cc phng thc dng chn hoc xa mt hng d liu ca bng, s c dng chocc phng thcejbCreate() (chn, lnh SQLinsert) vejbRemove()(xa, lnh SQLdelete) ca bean.

    private voidinsertStudent(String studentId, String name)throws Exception{

    Connection con=makeConnection();

    String sql=insert into Student values(?,?);

    PreparedStatement pSt=con.prepareStatement(sql);

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    9/35

    pSt.setString(1, studentId);

    pSt.setString(2, name);

    pSt.executeUpdate();

    pSt.close();

    con.close();

    }

    private voiddeleteStudent(String studentId)throws Exception{

    Connection con=makeConnection();

    String sql=delete from Student where studentID=+studentId+;

    con.createStatement().executeUpdate(sql);

    con.close();

    }

    Cc phng thc dng np hoc lu mt hng d liu ca bng, s c dng cho c phng thcejbLoad() (lnh SQLselect) vejbStore() (lnh SQLupdate) ca bean.

    private voidstoreStudent()throws Exception{

    Connection con=makeConnection();

    String sql=update Student set name=? where studentId=?;

    PreparedStatement pSt=con.prepareStatement(sql);

    pSt.setString(1, studentId);

    pSt.setString(2, name);

    int effectedRows=pSt.executeUpdate();

    pSt.close();

    con.close();

    if (effectedRows

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    10/35

    }

    private voidloadStudent()throws Exception{

    Connection con=makeConnection();

    String sql=select * from Student where studentID=+studentId+;

    ResultSet rs=con.createStatement().executeQuery(sql);

    if (rs.next()){

    this.name=rs.getString(name);

    }

    else{

    throw newException(Row for student id:+studentId+ not found in database);

    }

    }

    c) Cc phng thc callback v cc Finder

    - m t phn trn.

    d) Code hon chnhpackagestudent;

    import java.rmi.RemoteException;

    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.util.Enumeration;

    import java.util.Properties;

    import java.util.Vector;

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    11/35

    import javax.ejb.CreateException;

    import javax.ejb.EJBException;

    import javax.ejb.EntityBean;

    import javax.ejb.EntityContext;

    import javax.ejb.FinderException;

    import javax.ejb.ObjectNotFoundException;

    public classStudentBeanimplementsEntityBean{

    private static final long serialVersionUID = 1L;

    protected EntityContext context;

    //Environment properties

    public Properties env;

    //Bean-Managed states fields

    private String studentId;

    private String name;

    //==================================================

    //default constructor

    public StudentBean(){

    System.out .println (EJB created);

    }

    //Setters/getters

    public voidsetStudentId(String studentId){

    this.studentId=studentId;

    }

    public String getStudentId(){

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    12/35

    return this.studentId;

    }

    public voidsetName(String name){

    this.name=name;

    }

    public String getName(){

    return this.name;

    }

    //==================================================

    //Tao Student trong database

    public String ejbCreate(String studentId,String name)throws CreateException{

    try {

    insertStudent(studentId,name);

    this.studentId=studentId;

    this.name=name;

    }

    catch (Exception ex) {

    throw newEJBException(ejbCreate: +ex.getMessage());

    }

    return studentId;

    }

    public voidejbPostCreate( String studentId, String name )

    { }

    public String ejbFindByPrimaryKey(String studentId)throws FinderException{

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    13/35

    booleanresult=false;

    System.out .println (in ejbFindByPrimaryKey);

    try {

    result=findByPrimaryKey(studentId);

    }

    catch (Exception ex) {

    throw newEJBException(ejbFindByPrimaryKey+ex.getMessage());

    }

    if (!result)

    throw newObjectNotFoundException(row for id +studentId+ not found!);

    return studentId;

    }

    public Enumeration ejbFindByName(String name)throws FinderException{

    Enumeration a=null;

    try {

    a= FindByName(name);

    } catch (Exception e) {

    e.printStackTrace();

    }

    return a;

    }

    public voidejbRemove(){

    System.out .println (in ejbRemove);

    try {

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    14/35

    deleteStudent(studentId);

    }

    catch (Exception ex) {

    throw newEJBException(ejbRemove: +ex.getMessage());

    }

    System.out .println (leaving ejbRemove);

    }

    public voidsetEntityContext(EntityContext context){

    this.context=context;

    }

    public voidunsetEntityContext()throws EJBException, RemoteException {

    this.context=null;

    this.env=null;

    }

    public voidejbActivate()throws EJBException, RemoteException {

    this.studentId=(String)context.getPrimaryKey();

    }

    public voidejbPassivate()throws EJBException, RemoteException {

    this.studentId=null;

    }

    public voidejbLoad(){

    try {

    loadStudent();

    }

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    15/35

    catch (Exception ex) {

    throw newEJBException(ejbLoad: +ex.getMessage());

    }

    }

    public voidejbStore()throws EJBException, RemoteException {

    try {

    storeStudent();

    } catch (Exception e) {

    e.printStackTrace();

    }//update

    }

    //==========================================================

    private Connection makeConnection()throws Exception{

    Connection con=null;

    Class. forName (sun.jdbc.odbc.JdbcOdbcDriver);

    String url=jdbc:odbc:student;

    con=DriverManager. getConnection (url);

    return con;

    }

    //

    /**

    * T?m theo kha chnh

    * @param studentId: l mssv cn t?m

    * @return: true nu t?m thy

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    16/35

    * @throwsException

    */

    private booleanfindByPrimaryKey(String studentId)throws Exception{

    Connection con=makeConnection();

    String sql=select * from Student where studentID=+studentId+;

    ResultSet rs=con.createStatement().executeQuery(sql);

    booleanret=rs.next();con.close();

    return ret;

    }

    /**

    * T?m theoi tn

    * @param name: l tn cn t?m

    * @return danh sch cc sinh vin c tn l $name

    */

    private Enumeration FindByName(String name)throws Exception{

    Vector vec=newVector();

    Connection con=makeConnection();

    String sql=select * from Student where name=+name+;

    ResultSet rs=con.createStatement().executeQuery(sql);

    while(rs.next())

    vec.add(rs.getString(studentId));

    con.close();

    return vec.elements();

    }

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    17/35

    /**

    * Xa 1 SV khi CSDL

    * @param studentId l mssv c?n x a

    * @throwsException

    */

    private voiddeleteStudent(String studentId)throws Exception{

    Connection con=makeConnection();

    String sql=delete from Student where studentID=+studentId+;

    con.createStatement().executeUpdate(sql);

    con.close();

    }

    /**

    * Thm 1 sinh vin vo csdl

    * @param studentId: l mssv cn thm

    * @param name: tn sv cn thm

    * @throwsException

    */

    private voidinsertStudent(String studentId, String name)throws Exception{

    Connection con=makeConnection();

    String sql=insert into Student values(?,?);

    PreparedStatement pSt=con.prepareStatement(sql);

    pSt.setString(1, studentId);

    pSt.setString(2, name);

    pSt.executeUpdate();

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    18/35

    pSt.close();

    con.close();

    }

    /**

    * Update thngng tin sinh vin

    */

    private voidstoreStudent()throws Exception{

    Connection con=makeConnection();

    String sql=update Student set name=? where studentId=?;

    PreparedStatement pSt=con.prepareStatement(sql);

    pSt.setString(1, studentId);

    pSt.setString(2, name);

    int effectedRows=pSt.executeUpdate();

    pSt.close();

    con.close();

    if (effectedRows

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    19/35

    ResultSet rs=con.createStatement().executeQuery(sql);

    if (rs.next()){

    this.name=rs.getString(name);

    }

    else{

    throw newException(Row for student id:+studentId+ not found in database);

    }

    }

    }

    - Trong BMP, khi container chuyn bean t trng thi Pooled sang trng thi Ready s khng tng thit lp kha chnh. V vy, cc phng thcejbCreate() v ejbActivate()cn phi thit lpkha chnh, l l do cn lu tr i tngEntityContext.

    B. To client truy xut Stateless Session Bean

    - Tng t nh vit phn client cho Session Bean.

    packageclient;

    import java.awt.BorderLayout;import java.awt.Color;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import java.util.Enumeration;

    import javax.naming.Context;

    import javax.naming.InitialContext;import javax.rmi.PortableRemoteObject;

    import javax.swing.Box;

    import javax.swing.JButton;

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    20/35

    import javax.swing.JFrame;

    import javax.swing.JLabel;

    import javax.swing.JScrollPane;

    import javax.swing.JTable;

    import javax.swing.JTextField;

    import javax.swing.table.DefaultTableModel;

    import student.StudentRemote;

    import student.StudentRemoteHome;

    public classClientextendsJFrameimplementsActionListener{

    private static final long serialVersionUID = 1L;

    private JTextField tfID,tfName;

    private JButton btAdd,btFindById,btFindByName;

    private DefaultTableModel dtm;

    private JTable table;

    private StudentRemoteHome studentHome;

    private JLabel lblStatus;

    public Client(){

    super(BMP demontraction);

    setDefaultCloseOperation( EXIT_ON_CLOSE );

    setSize(400,250);setResizable(false);

    Box b=Box.createVerticalBox ();

    Box b1=Box.createHorizontalBox ();

    Box b2=Box.createHorizontalBox ();

    Box b3=Box.createHorizontalBox ();b.add(Box.createVerticalStrut (8));

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    21/35

    b.add(b1); b.add(Box.createVerticalStrut (8));

    b.add(b2);b.add(Box.createVerticalStrut (8));

    b.add(b3);b.add(Box.createVerticalStrut (8));

    this.add(b,BorderLayout. NORTH );

    JLabel l1,l2;

    b1.add(l1=newJLabel(Student ID:,JLabel. RIGHT ));

    b1.add(tfID=newJTextField(20));

    b2.add(l2=newJLabel(Name:,JLabel. RIGHT ));

    b2.add(tfName=newJTextField(20));

    l2.setPreferredSize(l1.getPreferredSize());

    b3.add(btAdd=newJButton(Add));b3.add(Box.createHorizontalStrut (5));

    b3.add(btFindById=newJButton(Find By ID));b3.add(Box.createHorizontalStrut (5));

    b3.add(btFindByName=newJButton(Find By Name));

    btAdd.addActionListener(this);

    btFindById.addActionListener(this);

    btFindByName.addActionListener(this);

    lblStatus=newJLabel(infos);lblStatus.setForeground(Color.red );

    this.add(lblStatus,BorderLayout.SOUTH );

    createTable();

    DoLook();

    }

    private voidDoLook() {

    try {

    System. setProperty ( java.naming.factory.initial, org.jnp.interfaces.NamingContextFactory );

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    22/35

    System. setProperty ( java.naming.provider.url, localhost:1099 );

    System. setProperty ( java.naming.factory.url.pkgs, org.jboss.naming );

    Context ctx =newInitialContext();

    Object ref = ctx.lookup( Student );

    studentHome = ( StudentRemoteHome )PortableRemoteObject.narrow ( ref, StudentRemoteHome.class);

    } catch ( Exception e ) {

    e.printStackTrace();

    }

    }

    private voidcreateTable() {

    String []hd={Student ID,Name};

    dtm=newDefaultTableModel(hd,0);

    table=newJTable(dtm);

    this.add(newJScrollPane(table),BorderLayout.CENTER );

    }

    public static voidmain(String[] args) {

    newClient().setVisible(true);

    }

    @Override

    public voidactionPerformed(ActionEvent e) {

    Object o=e.getSource();

    if (o.equals(btAdd)){

    String id=tfID.getText();

    String name=tfName.getText();

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    23/35

    if (id.trim().equals()||name.trim().equals())

    lblStatus.setText( Fields cannot be null!\nPlease enter it);

    else

    {

    try {

    studentHome.create(id, name);

    lblStatus.setText(Create new item successfully!);

    } catch (Exception e1) {

    lblStatus.setText(Can not be create new Item);

    }

    }

    }

    else if (o.equals(btFindById)){

    StudentRemote student=null;

    dtm.setRowCount(0);

    try {

    student=studentHome.findByPrimaryKey(tfID.getText());

    if (student!=null){

    String []tmp=newString[2];

    tmp[0] = student.getStudentId();

    tmp[1] = student.getName();

    dtm.addRow( tmp );

    }

    } catch (Exception e1) {

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    24/35

    lblStatus.setText(e1.getMessage());

    }

    }

    else if (o.equals(btFindByName)){

    String[] tmp =newString[2];

    StudentRemote student =null;

    dtm.setRowCount(0);

    try {

    Enumeration en = studentHome.findByName( tfName.getText() );

    if ( e !=null ) {

    while( en.hasMoreElements() ) {

    student = (StudentRemote)en.nextElement();

    tmp[0] = student.getStudentId();

    tmp[1] = student.getName();

    dtm.addRow( tmp );

    }

    } else{

    lblStatus.setText( Could not find );

    }

    } catch ( Exception ex ){

    lblStatus.setText(ex.getMessage());

    }

    }

    }

    }

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    25/35

    III. Trin khai

    1. Chun b cc deployment descriptor

    - Chun bejb-jar.xml trong th mcMETA-INF.

    emp

    Student

    student.StudentRemoteHome

    student.StudentRemote

    student.StudentBean

    Bean

    java.lang.String

    false

    Student

    *

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    26/35

    Required

    - Chun b jboss.xmltrong th mcMETA-INF.

    Student

    Student

    2. ng gi EJB

    - Dng cng c jar ng gi EJB

    C:\EJB\BMP> jar cvf Student.jar student/*.class META-INF/*.xml

    added manifest

    adding: student/StudentRemote.class(in = 302) (out= 204)(deflated 32%)

    adding: student/StudentBean.class(in = 5908) (out= 2775)(deflated 53%)

    adding: student/StudentRemoteHome.class(in = 485) (out= 271)(deflated 44%)

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    27/35

    adding: META-INF/ejb-jar.xml(in = 535) (out= 224)(deflated 58%)

    adding: META-INF/jboss.xml(in = 262) (out= 137)(deflated 47%)

    - Kt qu gistudent.jar c ni dung nh sau:

    student

    StudentRemote.class

    StudentBean.class

    StudentRemoteHome.class

    META-INF

    ejb-jar.xml

    jboss.xml

    MANIFEST.MF

    2. To c s d liu

    - To c s d liu bt k, to bngstudent vi design nh sau:

    Nhp trc mt s record th

    Sau Control Panel->Administrative Tools->Data Sources(ODBC) to 1 DSN c tn student.

    3. Trin khai gistudent.jar:

    - Sao chp gistudent.jar vo th mc%JBOSS_HOME%\server\default\deploy

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    28/35

    4. S dng client truy xut EJB

    - cn c cc gi ni trong bi Session Bean

    To lp Client.java trong th mc c tn client.

    Ni dung nh sau

    packageclient;

    import java.awt.BorderLayout;import java.awt.Color;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import java.util.Enumeration;

    import javax.naming.Context;

    import javax.naming.InitialContext;

    import javax.rmi.PortableRemoteObject;

    import javax.swing.Box;

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    29/35

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    30/35

    Box b1=Box.createHorizontalBox();

    Box b2=Box.createHorizontalBox();

    Box b3=Box.createHorizontalBox();b.add(Box.createVerticalStrut(8));

    b.add(b1); b.add(Box.createVerticalStrut(8));

    b.add(b2);b.add(Box.createVerticalStrut(8));

    b.add(b3);b.add(Box.createVerticalStrut(8));

    this.add(b,BorderLayout.NORTH);

    JLabel l1,l2;

    b1.add(l1=newJLabel(Student ID:,JLabel.RIGHT));

    b1.add(tfID=newJTextField(20));

    b2.add(l2=newJLabel(Name:,JLabel.RIGHT));

    b2.add(tfName=newJTextField(20));

    l2.setPreferredSize(l1.getPreferredSize());

    b3.add(btAdd=newJButton(Add));b3.add(Box.createHorizontalStrut(5));

    b3.add(btFindById=newJButton(Find By ID));b3.add(Box.createHorizontalStrut(5));

    b3.add(btFindByName=newJButton(Find By Name));

    btAdd.addActionListener(this);

    btFindById.addActionListener(this);

    btFindByName.addActionListener(this);

    lblStatus=newJLabel(infos);lblStatus.setForeground(Color.red);

    this.add(lblStatus,BorderLayout.SOUTH);

    createTable();

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    31/35

    DoLook();//lookup

    }

    private voidDoLook() {

    try {

    System.setProperty(java.naming.factory.initial,org.jnp.interfaces.NamingContextFactory);

    System.setProperty(java.naming.provider.url, localhost:1099);

    System.setProperty(java.naming.factory.url.pkgs, org.jboss.naming);

    Context ctx =newInitialContext();

    Object ref = ctx.lookup(Student);

    studentHome = ( StudentRemoteHome )PortableRemoteObject.narrow( ref, StudentRemoteHome.class);

    } catch ( Exception e ) {

    e.printStackTrace();

    }

    }

    private voidcreateTable() {

    String []hd={Student ID,Name};

    dtm=newDefaultTableModel(hd,0);

    table=newJTable(dtm);

    this.add(newJScrollPane(table),BorderLayout.CENTER);

    }

    public static voidmain(String[] args) {

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    32/35

    newClient().setVisible(true);

    }

    @Override

    public voidactionPerformed(ActionEvent e) {

    Object o=e.getSource();

    if (o.equals(btAdd)){

    String id=tfID.getText();

    String name=tfName.getText();

    if (id.trim().equals()||name.trim().equals())

    lblStatus.setText(Fields cannot be null!\nPlease enter it);

    else

    {

    try {

    studentHome.create(id, name);

    lblStatus.setText(Create new item successfully!);

    } catch (Exception e1) {

    lblStatus.setText(Can not be create new Item);

    }

    }

    }

    else if (o.equals(btFindById)){

    StudentRemote student=null;

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    33/35

    dtm.setRowCount(0);

    try {

    student=studentHome.findByPrimaryKey(tfID.getText());

    if (student!=null){

    String []tmp=newString[2];

    tmp[0] = student.getStudentId();

    tmp[1] = student.getName();

    dtm.addRow( tmp );

    }

    } catch (Exception e1) {

    lblStatus.setText(e1.getMessage());

    }

    }

    else if (o.equals(btFindByName)){

    String[] tmp =newString[2];

    StudentRemote student =null;

    dtm.setRowCount(0);

    try {

    Enumeration en = studentHome.findByName( tfName.getText() );

    if ( e !=null ) {

    while( en.hasMoreElements() ) {

    student = (StudentRemote)en.nextElement();

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    34/35

    tmp[0] = student.getStudentId();

    tmp[1] = student.getName();

    dtm.addRow( tmp );

    }

    } else{

    lblStatus.setText(Could not find);

    }

    } catch ( Exception ex ){

    lblStatus.setText(ex.getMessage());

    }

    }

    }

    }

    To file build.bat vi ni dung

    javac -d . *.javapause

    Bin dch chng trnh bng cch chy file build.bat. m bo l khng c li no!

    To file run.bat vi ni dung

    java client/Client

    pauseThc thi file ny. Kt qu nh sau:

  • 7/31/2019 Bean-Managed Persistent Entity Beans EJB2- Student Example

    35/35

    CHC CC BN THNH CNG!