Container-Managed Persistence Entity Beans EJB2 – Employees Example
Container-Managed Persistence Entity Beans Example
A. Tạo CSDL trong SQL Server với tên Employee, tạo bảng có tên tbl_emp có cấu trúc như bảng sau:
Field Name |
Type |
EmpId |
nvarchar (Primary Key) |
FirstName |
nvarchar |
LastName |
nvarchar |
DateOfBirth |
nvarchar |
Address |
nvarchar |
Salary |
Int |
DepartmentNo |
int |
B. Thiết kế CMP:
1. Tạo file EmployeeHome.java với nội dung sau:
package emp;
import java.rmi.RemoteException; import java.util.Collection; import javax.ejb.CreateException; import javax.ejb.EJBHome; import javax.ejb.FinderException;
public interface EmployeeHome extends EJBHome { public Employee create(String empid, String fName, String lName,String doBirth, String address, int salary,int dpNo) throws CreateException, RemoteException;
public Employee findByPrimaryKey(String empid) throws FinderException, RemoteException;
public Collection findByLastName(String s) throws FinderException,RemoteException; } |
2. Tạo file Employee.java với nội dung sau
package emp;
import java.rmi.RemoteException; import javax.ejb.EJBObject;
public interface Employee extends EJBObject {
public String getEmpid() throws RemoteException; public void setFName(String fName) throws RemoteException; public String getFName() throws RemoteException; public void setLName(String lName) throws RemoteException; public String getLName() throws RemoteException; public void setDoBirth(String doBirth) throws RemoteException; public String getDoBirth() throws RemoteException; public void setAddress(String address) throws RemoteException; public String getAddress() throws RemoteException; public void setSalary(int salary) throws RemoteException; public int getSalary() throws RemoteException; public void setDpNo(int dpNo) throws RemoteException; public int getDpNo() throws RemoteException; } |
3. Tạo file EmployeeBean.java với nội dung sau
package emp;
import javax.ejb.CreateException; import javax.ejb.EntityContext; import javax.ejb.RemoveException;
public abstract class EmployeeBean implements javax.ejb.EntityBean { EntityContext entityContext; public String ejbCreate(String empid, String fName, lName, doBirth, String address, int salary, int dpNo) throws CreateException { setEmpid(empid); setFName(fName); setLName(lName); setDoBirth(doBirth); setAddress(address); setSalary(salary); setDpNo(dpNo); return empid; }
public void ejbPostCreate(String empid, String fName, String lName, doBirth, String address, int salary, int dpNo) throws CreateException { } public void ejbRemove() throws RemoveException { } public void ejbLoad() { } public void ejbStore() { } public void ejbActivate() { } public void ejbPassivate() { } public void unsetEntityContext() { this.entityContext = null; } public void setEntityContext(EntityContext entityContext) { this.entityContext = entityContext; }
public abstract void setDpNo(int dpNo); public abstract void setSalary(int salary); public abstract void setAddress(String address); public abstract void setDoBirth(String doBirth); public abstract void setLName(String lName); public abstract void setFName(String fName); public abstract void setEmpid(String empid); public abstract String getEmpid(); public abstract String getFName(); public abstract String getLName(); public abstract String getDoBirth(); public abstract String getAddress(); public abstract int getSalary(); public abstract int getDpNo(); } |
C. Cấu hình triển khai
4. Tạo file file ejb-jar.xml trong thư mục META-INF với nội dung sau
<?xml version=“1.0“ encoding=“UTF-8“?> <!DOCTYPE ejb-jar PUBLIC “-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN“ “http://java.sun.com/dtd/ejb-jar_2_0.dtd“>
<ejb-jar> <enterprise-beans> <entity> <ejb-name>EmployeeBean</ejb-name> <home>emp.EmployeeHome</home> <remote>emp.Employee</remote> <ejb-class>emp.EmployeeBean</ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>java.lang.String</prim-key-class> <reentrant>false</reentrant> <cmp-version>2.x</cmp-version>
<abstract-schema-name>tbl_emp</abstract-schema-name>
<cmp-field> <field-name>empid</field-name> </cmp-field> <cmp-field> <field-name>fName</field-name> </cmp-field> <cmp-field> <field-name>lName</field-name> </cmp-field> <cmp-field> <field-name>doBirth</field-name> </cmp-field> <cmp-field> <field-name>address</field-name> </cmp-field> <cmp-field> <field-name>salary</field-name> </cmp-field> <cmp-field> <field-name>dpNo</field-name> </cmp-field> <primkey-field>empid</primkey-field> <query> <query-method> <method-name>findByLastName</method-name> <method-params> <method-param>java.lang.String</method-param> </method-params> </query-method> <ejb-ql> <![CDATA[SELECT OBJECT(o) FROM tbl_emp AS o WHERE o.lName = ?1]]> </ejb-ql> </query> </entity> </enterprise-beans> <assembly-descriptor> <container-transaction> <method> <ejb-name>EmployeeBean</ejb-name> <method-name>*</method-name> </method> <trans-attribute>Required</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar> |
5. Tạo file file jboss.xml trong thư mục META-INF với nội dung sau
<?xml version=“1.0“ encoding=“UTF-8“?> <!DOCTYPE jboss PUBLIC “-//JBoss//DTD JBOSS 4.0//EN“ “http://www.jboss.org/j2ee/dtd/jboss_4_0.dtd“>
<jboss> <enterprise-beans> <entity> <ejb-name>EmployeeBean</ejb-name> <jndi-name>EmployeeEJB</jndi-name> </entity> </enterprise-beans> </jboss> |
6. Tạo file file jbosscmp-jdbc.xml trong thư mục META-INF với nội dung sau
<?xml version=“1.0“ encoding=“UTF-8“?> <!DOCTYPE jbosscmp-jdbc PUBLIC “-//JBoss//DTD JBOSSCMP-JDBC 4.0//EN“ “http://www.jboss.org/j2ee/dtd/jbosscmp-jdbc_4_0.dtd“>
<jbosscmp-jdbc> <defaults> <datasource>java:/MSSQLDS</datasource> <datasource-mapping>MS SQLSERVER</datasource-mapping> <create-table>true</create-table> <remove-table>true</remove-table> </defaults> <enterprise-beans> <entity> <ejb-name>EmployeeBean</ejb-name> <datasource>java:/MSSQLDS</datasource> <datasource-mapping>MS SQLSERVER</datasource-mapping> <create-table>true</create-table> <table-name>tbl_emp</table-name> <cmp-field> <field-name>empid</field-name> <column-name>EmpId</column-name> </cmp-field> <cmp-field> <field-name>fName</field-name> <column-name>FirstName</column-name> </cmp-field> <cmp-field> <field-name>lName</field-name> <column-name>LastName</column-name> </cmp-field> <cmp-field> <field-name>doBirth</field-name> <column-name>DateOfBirth</column-name> </cmp-field> <cmp-field> <field-name>address</field-name> <column-name>Address</column-name> </cmp-field> <cmp-field> <field-name>salary</field-name> <column-name>Salary</column-name> </cmp-field> <cmp-field> <field-name>dpNo</field-name> <column-name>DepartmentNo</column-name> </cmp-field> </entity> </enterprise-beans> </jbosscmp-jdbc> |
7. Tạo/cấu hình file mssql-ds.xml trong thư mục %JBOSS-HOME%\server\default\deploy
<?xml version=“1.0“ encoding=“UTF-8“?>
<datasources> <local-tx-datasource> <jndi-name>MSSQLDS</jndi-name> <connection-url> jdbc:sqlserver://localhost:1433;databaseName=Employee </connection-url> <driver-class> com.microsoft.sqlserver.jdbc.SQLServerDriver </driver-class> <user-name>sa</user-name> <password></password>
<metadata> <type-mapping>MS SQLSERVER2000</type-mapping> </metadata> </local-tx-datasource> </datasources> |
D. Triển khai
-
- Tạo file compile.bat có nội dung
javac -d . *.java pause |
-
- Tạo file CreateJarFile.bat có nội dung
jar cvf EmployeesBean.jar emp/*.class META-INF/*.xml pause |
-
- Biên dịch: Chạy file compile.bat
- Tạo file jar: Chạy file CreateJarFile.bat
- Sao chép file EmployeesBean.jar vào thư mục %JBOSS-HOME%\server\default\deploy. Kết quả triển khai trên console của JBOSS có dạng như sau:
12:53:23,604 INFO [EjbModule] Deploying EmployeeBean 12:53:23,698 INFO [ProxyFactory] Bound EJB Home ‘EmployeeBean’ to jndi ‘EmployeeEJB’ 12:53:23,698 INFO [EJBDeployer] Deployed: file:/C:/javaSoft/jboss-4.2.2.GA/server/default/deploy/EmployeesBean.jar |
E. Tạo client
1. Tạo thư mục client,Copy thu mục emp vào đây, bỏ đi file EmployeeBean.class
2. Tạo file EMP_Client.java trong thư mục client với nội dung sau
package client;
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
import javax.naming.Context; import javax.naming.InitialContext; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import java.util.Collection; import java.util.Iterator; import javax.rmi.PortableRemoteObject;
import emp.*;
public class EMP_Client extends JFrame implements ActionListener{ private static final long serialVersionUID = 7170837407824840942L;
private JPanel pTop=new JPanel(new BorderLayout()); private JTextField tfID,tfFN,tfLN,tfDOB,tfAD,tfSAL,tfDeptNo; private JButton btAdd,btUpdate,btFindByKey,btFindByLN,btExit; private JLabel lblStatus;
private DefaultTableModel tableModel; private JTable table;
private EmployeeHome home;
public EMP_Client() { super(“Employees EJB Client”); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(500,450);
JLabel lblTitle=new JLabel(“Employees EJB Client”,JLabel.CENTER); lblTitle.setFont(new Font(“Arial”,Font.BOLD,18)); lblTitle.setForeground(Color.blue);pTop.add(lblTitle,BorderLayout.NORTH); lblStatus=new JLabel(“init…”); this.add(lblStatus,BorderLayout.SOUTH); this.add(pTop,BorderLayout.NORTH);
createGUI(); createTable(); initContext(); }
void initContext() { try { System.setProperty(“java.naming.factory.initial”,“org.jnp.interfaces.NamingContextFactory”); System.setProperty(“java.naming.provider.url”,“localhost:1099”);
Context initial = new InitialContext(); Object objref = initial.lookup(“EmployeeEJB”); home = (EmployeeHome) PortableRemoteObject.narrow(objref,EmployeeHome.class); lblStatus.setText(“Binding context completed…”); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); System.exit(0); } }
void createGUI() { Box b=Box.createVerticalBox(); Box b1=Box.createHorizontalBox(); Box b2=Box.createHorizontalBox(); Box b3=Box.createHorizontalBox(); Box b4=Box.createHorizontalBox(); Box b5=Box.createHorizontalBox(); Box b6=Box.createHorizontalBox(); Box b7=Box.createHorizontalBox(); Box b8=Box.createHorizontalBox(); b.add(b1);b.add(Box.createVerticalStrut(8)); b.add(b2);b.add(Box.createVerticalStrut(8)); b.add(b3);b.add(Box.createVerticalStrut(8)); b.add(b4);b.add(Box.createVerticalStrut(8)); b.add(b5);b.add(Box.createVerticalStrut(8)); b.add(b6);b.add(Box.createVerticalStrut(8)); b.add(b7);b.add(Box.createVerticalStrut(8)); b.add(b8);b.add(Box.createVerticalStrut(8));
JLabel l1,l2,l3,l4,l5,l6,l7; b1.add(l1=new JLabel(“Employee ID:”,JLabel.RIGHT)); b2.add(l2=new JLabel(“First Name:”,JLabel.RIGHT)); b3.add(l3=new JLabel(“Last Name:”,JLabel.RIGHT)); b4.add(l4=new JLabel(“Date of Birth:”,JLabel.RIGHT)); b5.add(l5=new JLabel(“Address:”,JLabel.RIGHT)); b6.add(l6=new JLabel(“Salary:”,JLabel.RIGHT)); b7.add(l7=new JLabel(“Department Number:”,JLabel.RIGHT)); l1.setPreferredSize(l7.getPreferredSize()); l2.setPreferredSize(l7.getPreferredSize()); l3.setPreferredSize(l7.getPreferredSize()); l4.setPreferredSize(l7.getPreferredSize()); l5.setPreferredSize(l7.getPreferredSize()); l6.setPreferredSize(l7.getPreferredSize());
b1.add(tfID=new JTextField(20)); b2.add(tfFN=new JTextField(20)); b3.add(tfLN=new JTextField(20)); b4.add(tfDOB=new JTextField(20)); b5.add(tfAD=new JTextField(20)); b6.add(tfSAL=new JTextField(20)); b7.add(tfDeptNo=new JTextField(20));
b8.add(btAdd=new JButton(“Add”)); b8.add(Box.createHorizontalStrut(10)); b8.add(btFindByKey=new JButton(“Find By ID”)); b8.add(Box.createHorizontalStrut(10)); b8.add(btFindByLN=new JButton(“Find By Last Name”)); b8.add(Box.createHorizontalStrut(10)); b8.add(btUpdate=new JButton(“Update”)); b8.add(Box.createHorizontalStrut(10)); b8.add(btExit=new JButton(“Exit”));
btAdd.addActionListener(this); btFindByKey.addActionListener(this); btFindByLN.addActionListener(this); btUpdate.addActionListener(this); btExit.addActionListener(this);
pTop.add(b,BorderLayout.CENTER); }
void createTable(){ String []header= {“Employee ID”,“First Name”, “Last Name”,“Date of Birth”, “Address”,“Salary”,“Department No”}; tableModel=new DefaultTableModel(header,0); table=new JTable(tableModel); this.add(new JScrollPane(table),BorderLayout.CENTER);
}
@Override public void actionPerformed(ActionEvent e) { Object o=e.getSource(); if(o.equals(btExit)) System.exit(1); else if(o.equals(btAdd)) { if(checkData()) try { lblStatus.setText(“Bat dau them”); home.create(tfID.getText(),tfFN.getText(), tfLN.getText(),tfDOB.getText(), tfAD.getText(),Integer.parseInt(tfSAL.getText()), Integer.parseInt(tfDeptNo.getText())); lblStatus.setText(“Them thanh cong”); } catch (Exception e1) { lblStatus.setText(e1.getMessage()); } } else if(o.equals(btFindByKey)) { String key=tfID.getText().trim(); if(key.equals(“”)) lblStatus.setText(“Khong có gi de tim…”); else{ try { Employee emp = home.findByPrimaryKey(key); lblStatus.setText(“Tim nhan vien “+key); if(emp!=null){ tfID.setText(emp.getEmpid()); tfAD.setText(emp.getAddress()); tfDeptNo.setText(emp.getDpNo()+“”); tfDOB.setText(emp.getDoBirth()); tfFN.setText(emp.getFName()); tfLN.setText(emp.getLName()); tfSAL.setText(emp.getSalary()+“”); } else lblStatus.setText(“Khong tim thay nhan vien nay”); } catch (Exception ex) { lblStatus.setText(“Loi tim kiem:”+ex.getMessage()); } } } else if(o.equals(btFindByLN)) { if(tfLN.getText().trim().equals(“”)) lblStatus.setText(“Khong co gi de ma tim…”); else{ try { lblStatus.setText(“Tim nhan vien theo ten: “+tfLN.getText()); Collection cols=home.findByLastName(tfLN.getText()); tableModel.setRowCount(0);//xoa bang Iterator i=cols.iterator(); while (i.hasNext()) { Employee emp = (Employee)i.next(); String empid = (String)emp.getPrimaryKey(); String fn = emp.getFName(); String ln = emp.getLName(); String dob = emp.getDoBirth(); String add = emp.getAddress(); int sal = emp.getSalary(); int de = emp.getDpNo(); String []row={empid,fn,ln,dob,add,sal+“”,de+“” }; tableModel.addRow(row); } } catch (Exception ex) { lblStatus.setText(“Loi tim kiem:”+ex.getMessage()); } } } else if(o.equals(btUpdate)) { String key=tfID.getText().trim(); if(key.equals(“”)) lblStatus.setText(“Khong có gi de update…”); else{ try{ Employee emp = home.findByPrimaryKey(key); lblStatus.setText(“Update thong tin nhan viên “+key); if(emp!=null){ emp.setLName(tfLN.getText()); emp.setFName(tfFN.getText()); emp.setAddress(tfAD.getText()); emp.setDoBirth(tfDOB.getText()); emp.setDpNo(Integer.parseInt(tfDeptNo.getText())); emp.setSalary(Integer.parseInt(tfSAL.getText())); } else lblStatus.setText(“Khong update duoc vi khong tim thay”); }catch(Exception ex){ lblStatus.setText(ex.getMessage()); } } } }
private boolean checkData() { return true; }
public static void main(String[] args) { new EMP_Client().setVisible(true); } } |
3. Compile EMP_Client.java, chạy nó, ta có kết quả:
By Võ Văn Hải
Hữu Trung said
Thưa thầy! Bài này em ko tạo tb_emp trong Databse nhưng chường trình vẫn chạy rất và lựu trữ thành công! Có phải là CMP tự tạo bảng và lữu trữ đúng ko thầy? Em nhở thầyy giải thích dùm em. Em cảm ơn thầy!
Long said
Bị lỗi rồi thầy ơi. EmployeeBean lỗi chỗ hàm create. Còn mssql-ds.xml nó báo lỗi dd nest, UTF-8 gì đó. Thầy làm ơn cho xin code đã dùng để chạy demo chuẩn đi thầy.
vovanhai said
Đúng rồi! trong file jbosscmp-jdbc.xml em thấy thẻ true có nghĩa là cmp sẽ tự động tạo bảng dựa vào entity bạn khai báo. Tuy nhiên bạn cũng cần chú ý thêm thẻ tiếp theo , bạn sẽ thấy khi shutdown jboss, bảng trong csdl cũng bị xoa theo đấy!
vovanhai said
Khi copy bài từ internet xuống, bạn chú ý các dấu “, dấu này bạn phải thay đổi để có thể chạy được. Chúc vui!
Long said
Thầy ơi, nó lại báo cannot instantiate class : org.jnp.interfaces.NamingContextFactory ở EMP_Client ?
Long said
Exception in thread “main” java.lang.NoClassDefFoundError: org/jboss/logging/Logger
at org.jnp.interfaces.NamingContext.(NamingContext.java:160)
at org.jnp.interfaces.NamingContextFactory.getInitialContext(NamingContextFactory.java:56)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.InitialContext.(InitialContext.java:175)
at client.Client.initContext(Client.java:109)
at client.Client.(Client.java:96)
at client.Client.main(Client.java:454)
vovanhai said
Thiếu mấy cái thư viện trong classpath rồi bạn ơi. Logger nằm trong gói commons-logging.jar (trong thư mục %JBOSS_HOME%\lib. org.jnp.interfaces.NamingContextFactory nằm ở gói jnpserver.jar trong thư mục %JBOSS_HOME%\server\default\lib\.
Anh2No said
Bài viết rất hay cho newbie như em. Cảm ơn thầy rất nhiều.
phúc said
Thầy có thể làm 1 vd sử dụng id tăng tự động được không ạ.
thanhquan said
thầy ơi thầy có thể cho bài Example ve trang JSP truy xuất CMP-EJB .cám ơn thầy nhiều.
minh said
thay oi neu em su dung netbean va su dung server trong netbean luon thi em phai config cac file xml nhu the nao? thay giup dum em. cam on thay
vovanhai said
Server trong netbeans là Glassfish hả? Cấu hình XML là chung, em có thể bỏ file jboss.xml đi, khi đó em lookup bằng tên bean.
Smilodon said
Thay oi, neu muon tim kiem tuong doi, minh phai sua query-method nhu the nao ạ ? Cam on thay !
Smilodon said
Thay oi, neu muon tim kiem theo ten tuong doi thi phai sua code the nao a ? Cam on thay !
Hoàng Hồ said
Thầy ơi cho em hỏi, có thể dùng CMP Entity Bean để tạo Remote Session Bean bằng tool được không, nếu được thầy có thể hướng dẫn dùm em được không.Chờ tin thầy !
Lê Hiếu said
Cho e hỏi cách dùng array list trong Entity Bean server JBoss
Thankx.