Võ Văn Hải's blog

Chỉ có một điều tuyệt đối đó là mọi thứ đều tương đối…

DÙNG CMP TẠO ORDER

DÙNG CMP TẠO ORDER

Create by: Võ văn Hải

Email: vovanhaiQN.google.com

Home page: https://vovanhai.wordpress.com

PDF version here

  1. Tạo CSDL như script sau
USE [StudentsMS_EJB]

GO

/****** Object:  Table [dbo].[ORDERS] ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

SET ANSI_PADDING ON

GO

CREATE TABLE [dbo].[ORDERS](

[ORDER_ID] [varchar](64) COLLATE Vietnamese_CI_AS NULL,

[STUDENT_ID] [varchar](64) COLLATE Vietnamese_CI_AS NULL,

[ORDER_DATE] [datetime] NOT NULL,

[AMOUNT] [numeric](18, 0) NULL,

[STATUS] [varchar](64) COLLATE Vietnamese_CI_AS NULL

) ON [PRIMARY]

GO

SET ANSI_PADDING OFF

  1. Tạo 1 DSN có tên students chỉ đến database có bảng vừa tạo ở trên.
  1. Tạo EJBObject với class Order có nội dung như sau
package order;

import java.rmi.RemoteException;

import javax.ejb.EJBObject;

public interface Order extends EJBObject {

public String getOrderId()

throws RemoteException;

public String getStudentId()

throws RemoteException;

public void setStudentId(String studentId)

throws RemoteException;

public double getAmount()

throws RemoteException;

public void setAmount(double amount)

throws RemoteException;

public java.sql.Timestamp getOrderDate()

throws RemoteException;

public void setOrderDate(java.sql.Timestamp date)

throws RemoteException;

public String getStatus()

throws RemoteException;

public void setStatus(String status)

throws RemoteException;

}

  1. Tạo EJBHome với class OrderHome.java có nội dung như sau
package order;

import java.rmi.RemoteException;

import java.util.Collection;

import javax.ejb.CreateException;

import javax.ejb.EJBHome;

import javax.ejb.FinderException;

public interface OrderHome extends EJBHome {

/* Create methods */

public Order create(String studentId,

String status, double amount) throws CreateException, RemoteException;

/* Finder methods */

public Order findByPrimaryKey(String key)

throws FinderException, RemoteException;

public Collection findByStatus(String status)

throws FinderException, RemoteException;

/* Home methods */

public double getTotalAmountOfAllOrders()

throws FinderException, RemoteException;

}

  1. Tạo lớp OrderEJB.java có nội dung sau
package order;

import java.util.Collection;

import java.util.Collections;

import java.util.Enumeration;

import javax.ejb.CreateException;

import javax.ejb.EntityBean;

import javax.ejb.EntityContext;

import javax.ejb.FinderException;

import javax.ejb.RemoveException;

public abstract class OrderEJB implements EntityBean

{

protected EntityContext ctx;

public abstract String getOrderId();

public abstract void setOrderId(String orderId);

public abstract String getStudentId();

public abstract void setStudentId(String studentid);

public abstract java.sql.Timestamp getOrderDate();

public abstract void setOrderDate(java.sql.Timestamp timestamp);

public abstract String getStatus();

public abstract void setStatus(String status);

public abstract double getAmount();

public abstract void setAmount(double amount);

/* Callback methods */

public void setEntityContext(EntityContext ctx) {

print(“setEntityContext called”);

this.ctx = ctx;

}

public void unsetEntityContext() {

print(“unsetEntityContext called.\n”);

this.ctx = null;

}

public void ejbActivate() {

print(“ejbActivate() called.\n”);

}

public void ejbPassivate() {

print(“ejbPassivate() called.\n”);

}

public void ejbStore() {

print(“ejbStore() called.\n”);

}

public void ejbLoad() {

print(“ejbLoad() called.\n”);

}

public void ejbRemove() throws RemoveException {

print(“ejbRemove() called.\n”);

}

public String ejbCreate( String studentId,

String status, double amount) throws CreateException {

print(“ejbCreate() called.\n”);

String orderId = getUniqueId();

setOrderId(orderId);

setStudentId(studentId);

setStatus(status);

setAmount(amount);

setOrderDate(new java.sql.Timestamp(System.currentTimeMillis()));

return null;

}

public void ejbPostCreate(String studentId,

String courseId, double amount) throws CreateException {

print(“ejbPostCreate() called.\n”);

}

/* Home methods */

public double ejbHomeGetTotalAmountOfAllOrders()

throws FinderException {

double totalAmount = 0.0;

Collection col = ejbSelectAllOrderAmounts();

Enumeration amounts=Collections.enumeration(col);

while( amounts.hasMoreElements() ) {

Double amount= (Double)amounts.nextElement();

totalAmount += amount.doubleValue();

}

return totalAmount;

}

/* select methods. */

public abstract Collection ejbSelectAllOrderAmounts()

throws FinderException ;

void print(String s) {

System.out.println(s);

}

String getUniqueId(){

return new Long(System.currentTimeMillis()).toString();

}

}

  1. Tạo tập tin ejb-jar.xml trong thư mục META-INF có nội dung sau
<?xml version=”1.0″?>

<!DOCTYPE ejb-jar PUBLIC

‘-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN’

http://java.sun.com/dtd/ejb-jar_2_0.dtd’&gt;

<ejb-jar>

<enterprise-beans>

<entity>

<ejb-name>OrderEJB</ejb-name>

<home>order.OrderHome</home>

<remote>order.Order</remote>

<ejb-class>order.OrderEJB</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>Orders</abstract-schema-name>

<cmp-field>

<field-name>orderId</field-name>

</cmp-field>

<cmp-field>

<field-name>studentId</field-name>

</cmp-field>

<cmp-field>

<field-name>orderDate</field-name>

</cmp-field>

<cmp-field>

<field-name>status</field-name>

</cmp-field>

<cmp-field>

<field-name>amount</field-name>

</cmp-field>

<primkey-field>orderId</primkey-field>

<query>

<query-method>

<method-name>findByStatus</method-name>

<method-params>

<method-param>java.lang.String</method-param>

</method-params>

</query-method>

<ejb-ql>

<![CDATA[SELECT OBJECT(o) FROM Orders AS o

WHERE o.status = ?1]]>

</ejb-ql>

</query>

<query>

<query-method>

<method-name>ejbSelectAllOrderAmounts</method-name>

<method-params>

</method-params>

</query-method>

<ejb-ql>

<![CDATA[SELECT o.amount FROM Orders AS o

WHERE o.orderId IS NOT NULL]]>

</ejb-ql>

</query>

</entity>

</enterprise-beans>

</ejb-jar>

  1. Tạo file jboss.xml trong thư mục META-INF có nội dung sau
<?xml version=”1.0″ encoding=”UTF-8″?>

<jboss>

<enterprise-beans>

<entity>

<ejb-name>OrderEJB</ejb-name>

<jndi-name>order/Order</jndi-name>

</entity>

</enterprise-beans>

</jboss>

  1. Tạo file jbosscmp-jdbc.xml trong thư mục META-INF có nội dung sau
<?xml version=”1.0″ encoding=”UTF-8″?>

<!DOCTYPE jbosscmp-jdbc PUBLIC

“-//JBoss//DTD JBOSSCMP-JDBC 3.0//EN”

http://www.jboss.org/j2ee/dtd/jbosscmp-jdbc_3_0.dtd”&gt;

<jbosscmp-jdbc>

<defaults>

<datasource>java:/Students_DSN</datasource>

<datasource-mapping>MS SQLSERVER</datasource-mapping>

<create-table>false</create-table>

<remove-table>false</remove-table>

<pk-constraint>true</pk-constraint>

<preferred-relation-mapping>foreign-key</preferred-relation-mapping>

</defaults>

<enterprise-beans>

<entity>

<ejb-name>OrderEJB</ejb-name>

<table-name>orders</table-name>

<cmp-field>

<field-name>orderId</field-name>

<column-name>order_id</column-name>

</cmp-field>

<cmp-field>

<field-name>studentId</field-name>

<column-name>student_id</column-name>

</cmp-field>

<cmp-field>

<field-name>orderDate</field-name>

<column-name>order_date</column-name>

</cmp-field>

<cmp-field>

<field-name>status</field-name>

<column-name>status</column-name>

</cmp-field>

<cmp-field>

<field-name>amount</field-name>

<column-name>amount</column-name>

</cmp-field>

</entity>

</enterprise-beans>

</jbosscmp-jdbc>

  1. Tạo/hiệu chỉnh file mssql-ds.xml trong thư mục %JBOSS_HOME%\server\default\deploy có nội dung như sau
<?xml version=”1.0″ encoding=”UTF-8″?>

<datasources>

<!–Cac datasources khac co the co o day–>

<local-tx-datasource>

<jndi-name>Students_DSN</jndi-name>

<connection-url>jdbc:odbc:students</connection-url>

<driver-class>sun.jdbc.odbc.JdbcOdbcDriver</driver-class>

<user-name>sa</user-name>

<password></password>

<metadata>

<type-mapping>MS SQLSERVER2000</type-mapping>

</metadata>

</local-tx-datasource>

</datasources>

  1. Tạo file compile.bat để biên dịch các tập tin java có nội dung sau
javac -d . *.java

pause

  1. Tạo file CreateJarFile.bat với nội dung sau
jar cvf Order.jar order/*.class META-INF/*.xml

pause

Chạy file này để đóng gói các lớp và các file deployment descriptors. Sau khi chạy ta có file Order.jar.

  1. Triển khai file Order.jar bằng cách copy vào thư mục %JBOSS_HOME%\server\default\deploy. Nếu Jboss đang chạy ta sẽ nhận được thông báo trên cửa sổ như sau

21:39:36,237 INFO  [EjbModule] Deploying OrderEJB

21:39:36,830 INFO  [ProxyFactory] Bound EJB Home ‘OrderEJB’ to jndi ‘order/Order’

21:39:36,830 INFO  [EJBDeployer] Deployed: file:/C:/javaSoft/jboss-4.2.2.GA/serv

er/default/deploy/Order.jar

  1. Tạo thư mục client, tạo file Client.java có nội dung sau
import java.util.Collection;

import java.util.Collections;

import java.util.Enumeration;

import javax.naming.Context;

import javax.naming.InitialContext;

public class Client {

public static void main(String[] args) {

print(“Setting environment. . .\n”);

System.setProperty(“java.naming.factory.initial”,

“org.jnp.interfaces.NamingContextFactory”);

System.setProperty(“java.naming.provider.url”,

“localhost:1099”);

print(“Starting Client . . .\n”);

Context initialContext = null;

OrderHome orderHome = null;

Order order = null;

try {

print(“Looking up the order home via JNDI.\n”);

initialContext = new InitialContext();

Object object = initialContext.lookup(“order/Order”);

orderHome = (OrderHome)

javax.rmi.PortableRemoteObject.narrow(object,OrderHome.class);

order = (Order)orderHome.create(“1”, “Submitted”, 100);

String orderId = order.getOrderId();

print(“Created a new order:” + orderId + ” .\n”);

print(“Locating the order ” + orderId

+ ” using findByPrimaryKey method.\n”);

order=orderHome.findByPrimaryKey(orderId);

print(“Locating all orders with status Submitted ”

+ ” using findByStatus method.\n”);

Collection col=orderHome.findByStatus(“Submitted”);

Enumeration orders=Collections.enumeration(col);

while( orders.hasMoreElements() ) {

order=(Order)orders.nextElement();

print(“Order id:”+ order.getOrderId());

}

print(“Finding the total amount of all orders using \n”

+ ” getTotalAmountOfAllOrders home method.\n”);

double totalAmount = orderHome.getTotalAmountOfAllOrders();

print(“Total amount:”+ totalAmount );

} catch ( Exception e) {

e.printStackTrace();

}

}

static void print(String s) {

System.out.println(s);

}

}

  1. Copy thư mục order vào thư mục client, xóa tập tin OrderEJB.class
  2. Tạo file compile.bat để biên dịch các tập tin java với nội dung sau
javac -d . *.java

pause

  1. Tạo file run.bat với nội dung sau
java Client

pause

  1. Chạy file run.bat để thực thi ứng dụng. ta có kết quả như sau
D:\Bai giang Aptech\Aptech – Semester 4\EJB 2\examples\EJB2\CMP_EntityBean\order

\client>java Client

Setting environment. . .

Starting Client . . .

Looking up the order home via JNDI.

Created a new order:1220453763856 .

Locating the order 1220453763856 using findByPrimaryKey method.

Locating all orders with status Submitted  using findByStatus method.

Order id:1219723984638

Order id:1220449297230

Order id:1220449308728

Order id:1220449311879

Order id:1220449315919

Order id:1220453763856

Finding the total amount of all orders using

getTotalAmountOfAllOrders home method.

Total amount:1100.0

D:\Bai giang Aptech\Aptech – Semester 4\EJB 2\examples\EJB2\CMP_EntityBean\order

\client>pause

Press any key to continue . . .

Chúc các bạn thành công

One Response to “DÙNG CMP TẠO ORDER”

  1. phúc said

    Bạn có thể làm một ví dụ về cmp có sử dụng auto increment primary key được không?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: