Võ Văn Hải's blog

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

TẠO TRANSACTION VỚI BEAN-MANAGED TRANSACTION

TẠO TRANSACTION VỚI BEAN-MANAGED TRANSACTION

Author: Võ Văn Hải

CNC-Aptech, Tp HCM

Website: https://vovanhai.wordpress.com

Email: vovanhaiqn@google.com

    1. Một ví dụ sử dụng BMT

    Sau đây là 1 ví dụ EJB với BMT

    1. Tạo Remote Interface

    package bmt;

    import java.rmi.RemoteException;

    import java.sql.SQLException;

    import javax.ejb.EJBObject;

    public interface Student extends EJBObject

    {

    public void setupDB() throws RemoteException;

    public StudentInfo getStudent (String id)

    throws RemoteException, SQLException;

    public void addStudent (StudentInfo Student)

    throws RemoteException, SQLException;

    public void updateStudent (StudentInfo Student)

    throws RemoteException, SQLException;

    public void deleteStudent (String id)

    throws RemoteException, SQLException;

    }

    1. Tạo Home Interface

    package bmt;

    import java.rmi.RemoteException;

    import javax.ejb.CreateException;

    import javax.ejb.EJBHome;

    public interface StudentHome extends EJBHome

    {

    public Student create () throws RemoteException, CreateException;

    }

    1. Tạo Bean’s Class

    package bmt;

    import java.rmi.RemoteException;

    import java.sql.Connection;

    import java.sql.ResultSet;

    import java.sql.SQLException;

    import java.sql.Statement;

    import javax.ejb.CreateException;

    import javax.ejb.SessionBean;

    import javax.ejb.SessionContext;

    import javax.naming.InitialContext;

    import javax.sql.DataSource;

    import javax.transaction.SystemException;

    import javax.transaction.UserTransaction;

    public class StudentBean implements SessionBean{

    SessionContext ctx;

    DataSource ds = null;

    String id = null;

    String fname = null;

    String lname = null;

    String address = null;

    public void setupDB()

    throws RemoteException

    {

    System.out.println(“Settingup Database…”);

    try {

    InitialContext ctx = new InitialContext();

    //tim trong ejb-jar.xml tag <resource-env-ref-name>, sau do lookup tiep trong jboss.xml de lay duoc <jndi-name>

    ds = (DataSource)ctx.lookup(“java:comp/env/jdbc/studentsDB”);

    }catch (Exception ex) {

    ex.printStackTrace();

    }

    }

    public StudentInfo getStudent(String id)

    throws RemoteException, SQLException

    {

    try {

    String sql = “SELECT * “ +

    “FROM STUDENTS “ +

    “WHERE STUDENT_ID ='”+id+“‘”;

    Connection conn = ds.getConnection();

    System.out.println(“Conntected to DB…”);

    Statement stmt = conn.createStatement();

    ResultSet rs = stmt.executeQuery(sql);

    System.out.println(“Getting Result…”);

    while(rs.next()){

    id = rs.getString(1);

    fname = rs.getString(2);

    lname = rs.getString(3);

    address = rs.getString(4);

    }

    conn.close();

    System.out.println(“Returning Student Info…”);

    return (new StudentInfo (id, fname, lname, address));

    }catch (java.sql.SQLException e) {

    throw new RemoteException(“SQL failed: “ + e.getMessage());

    }catch (Exception ex) {

    ex.printStackTrace();

    }

    return null;

    }

    public void addStudent(StudentInfo st)

    throws RemoteException, SQLException

    {

    UserTransaction ut = ctx.getUserTransaction ();

    try {

    System.out.println(“addStudent: Starting new transaction…”);

    ut.begin ();

    String sql = “INSERT INTO STUDENTS VALUES(“ + st.id +

    “,'” + st.fname +

    “‘, ‘” + st.lname +

    “‘, ‘” + st.address + “‘)”;

    Connection conn = ds.getConnection();

    Statement stmt = conn.createStatement();

    stmt.executeUpdate(sql);

    ut.commit ();

    stmt.close();

    conn.close();

    System.out.println(“addStudent: transaction committed…”);

    }catch (java.sql.SQLException e) {

    try{

    System.out.println(“addStudent: transaction rolled back…”);

    ut.rollback();

    } catch (SystemException ex) {

    throw new RemoteException(“Rollback failed: “ + ex.getMessage());

    }

    }catch (Exception e) {

    try{

    ut.rollback();

    } catch (SystemException ex) {

    throw new RemoteException(“Rollback failed: “ + ex.getMessage());

    }

    }

    }

    public void updateStudent(StudentInfo st)

    throws RemoteException, SQLException

    {

    UserTransaction ut = ctx.getUserTransaction ();

    try {

    System.out.println(“updateStudent: Starting new transaction…”);

    ut.begin ();

    String sql = “UPDATE STUDENTS SET FNAME ='” + st.fname +

    “‘, LNAME ='” + st.lname +

    “‘, ADDRESS ='” + st.address +

    “‘ WHERE STUDENT_ID='”+st.id+“‘”;

    Connection conn = ds.getConnection();

    Statement stmt = conn.createStatement();

    stmt.executeUpdate(sql);

    ut.commit ();

    stmt.close();

    conn.close();

    System.out.println(“updateStudent: transaction committed…”);

    }catch (java.sql.SQLException e) {

    try{

    System.out.println(“updateStudent: transaction rolled back…”);

    ut.rollback();

    } catch (SystemException ex) {

    throw new RemoteException(“Rollback failed: “ + ex.getMessage());

    }

    }catch (Exception e) {

    try{

    ut.rollback();

    } catch (SystemException ex) {

    throw new RemoteException(“Rollback failed: “ + ex.getMessage());

    }

    }

    }

    public void deleteStudent(String id)

    throws RemoteException, SQLException

    {

    UserTransaction ut = ctx.getUserTransaction ();

    try {

    System.out.println(“deleteStudent: Starting new transaction…”);

    ut.begin ();

    String sql = “DELETE FROM STUDENTS WHERE STUDENT_ID='”+id+“‘”;

    Connection conn = ds.getConnection();

    Statement stmt = conn.createStatement();

    stmt.executeUpdate(sql);

    ut.commit ();

    stmt.close();

    conn.close();

    System.out.println(“deleteStudent: transaction committed…”);

    }catch (java.sql.SQLException e) {

    try{

    System.out.println(“deleteStudent: transaction rolled back…”);

    ut.rollback();

    } catch (SystemException ex) {

    throw new RemoteException(“Rollback failed: “ + ex.getMessage());

    }

    }catch (Exception e) {

    try{

    ut.rollback();

    } catch (SystemException ex) {

    throw new RemoteException(“Rollback failed: “ + ex.getMessage());

    }

    }

    }

    public void ejbCreate () throws RemoteException, CreateException {}

    public void ejbRemove() {}

    public void setSessionContext (SessionContext ctx) {this.ctx = ctx;}

    public void ejbActivate () {}

    public void ejbPassivate () {}

    }

    1. Tạo Helper Classes

    package bmt;

    public class StudentInfo implements java.io.Serializable {

    public String fname = null;

    public String lname = null;

    public String id = null;

    public String address = null;

    public StudentInfo (String ID, String fname, String lname, String address){

    this.fname = fname;

    this.lname = lname;

    this.id = ID;

    this.address = address;

    }

    }

    1. Đóng gói thành file jar
      1. Tạo file 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&#8217;>

    <ejb-jar>

    <enterprise-beans>

    <session>

    <ejb-name>Student</ejb-name>

    <home>bmt.StudentHome</home>

    <remote>bmt.Student</remote>

    <ejb-class>bmt.StudentBean</ejb-class>

    <session-type>Stateful</session-type>

    <transaction-type>Bean</transaction-type>

    <resource-env-ref>

    <resource-env-ref-name>jdbc/studentsDB</resource-env-ref-name>

    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>

    </resource-env-ref>

    </session>

    </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>

    <session>

    <ejb-name>Student</ejb-name>

    <jndi-name>bmt/MyStudentBMT</jndi-name>

    <resource-env-ref>

    <resource-env-ref-name>jdbc/studentsDB</resource-env-ref-name>

    <!–Cau hinh trong \server\default\deploy\mssql-ds.xml ten jndi nay–>

    <jndi-name>java:/Students_DSN</jndi-name>

    </resource-env-ref>

    </session>

    </enterprise-beans>

    </jboss>

      1. Tạo file build.bat

    javac -d . *.java

    pause

    Chạy file này để biên dịch. Đảm bảo mọi thứ phải OK.

      1. Tạo file makejar.bat

    jar cvf EJB_BMT.jar bmt/*.class META-INF/*.xml

    pause

    Tạo file này để tạo file jar, nếu OK ta được file EJB_BMT.jar

    1. Triển khai
      1. Tạo bảng có cấu trúc như sql statemnet sau:

    CREATE TABLE STUDENTS

    (

    STUDENT_ID VARCHAR(12) NOT NULL,

    FIRST_NAME VARCHAR(15) ,

    LAST_NAME VARCHAR(15) ,

    ADDRESS VARCHAR(164),

    EMAIL_ADDRESS VARCHAR(64)

    );

      1. Tạo 1 ODBC Data source với tên là students

      1. Tạo file (hoặc sửa file) mssql-ds.xml trong thư mục %JBOSS_HOME%\server\default\deploy\

    <?xml version=“1.0” encoding=“UTF-8”?>

    <!– Các Datasource khac neu co nam o day –>

    <datasources>

    <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. Triển khai EJB_BMT.jar bằng cách copy file EJB_CMT.jar vào thư mục %JBOSS_HOME%\server\default\deploy\

    Kết quả:

    14:40:39,012 INFO [EjbModule] Deploying Student

    14:40:39,105 INFO [ProxyFactory] Bound EJB Home ‘Student’ to jndi ‘bmt/MyStudentBMT’

    14:40:39,121 INFO [EJBDeployer] Deployed: file:/C:/javaSoft/jboss-4.2.2.GA/server/default/deploy/EJB_BMT.jar

    1. Thiết kế client
      1. Tạo thư mục client, copy thư mục bmt vào đó, sau đó xóa bỏ file StudentBean.class
      2. Tạo file Client.java có nội dung sau

    package client;

    import javax.naming.Context;

    import javax.naming.InitialContext;

    import bmt.Student;

    import bmt.StudentHome;

    import bmt.StudentInfo;

    public class Client {

    public final static String id = “100”;

    public static StudentInfo info = null;

    public static void main (String[] argv) {

    System.out.print(“\nDemonstration the use of BMT\n”);

    try{

    //set environment

    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” );

    // get handle to the Student object

    System.out.println (“Connecting to a Student EJB..”);

    Context ctx = new InitialContext();

    Object obj = ctx.lookup(“bmt/MyStudentBMT”);

    StudentHome studentHome = (StudentHome)

    javax.rmi.PortableRemoteObject.narrow(obj, StudentHome.class);

    Student student = (Student) studentHome.create ();

    student.setupDB();

    try{

    System.out.println (“Try deleting student with id=”+id);

    student.deleteStudent(id);

    }catch (Exception e){

    System.out.println(“Record does not exist…”);

    }

    System.out.println (“Try adding a new student”);

    info = new StudentInfo(id, “Snow”, “White”, “161 MAIN ST, ELK GROVE, CA”);

    student.addStudent(info);

    System.out.println (“Requesting the student info…”);

    info = student.getStudent(id);

    System.out.println (“Student Info = “ +

    info.id + “, “ +

    info.fname + “, “ +

    info.lname + “, “ +

    info.address);

    // Modify student info

    info.id = id;

    info.fname = “John”;

    info.lname = “Doe”;

    info.address=“111 CASPER DR, SACRAMENTO, CA”;

    // Update student in the database

    System.out.println (“Updating the student info…”);

    student.updateStudent (info);

    info = student.getStudent (id);

    System.out.println (“Student Info = “ +

    info.id + “, “ +

    info.fname + “, “ +

    info.lname + “, “ +

    info.address);

    }catch ( Exception e){

    System.out.println(“Student transaction failed…”);

    e.printStackTrace();

    }

    }

    }

      1. Tạo file build.bat

    javac -d . *.java

    pause

      1. Tạo file run.bat

    java Client

    pause

    1. Thử nghiệm
      1. Chạy file run.bat. Kết quả sẽ cho như sau

    Demonstration the use of BMT

    Connecting to a Student EJB..

    Try deleting student with id=100

    Try adding a new student

    Requesting the student info…

    Student Info = 100, null, null, null

    Updating the student info…

    Student Info = 100, null, null, null

    CHÚC THÀNH CÔNG!

    One Response to “TẠO TRANSACTION VỚI BEAN-MANAGED TRANSACTION”

    1. boboca86 said

      hay qua

    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: