001: package com.mockrunner.example.ejb;
002:
003: import java.rmi.RemoteException;
004: import java.sql.Connection;
005: import java.sql.SQLException;
006: import java.sql.Statement;
007:
008: import javax.ejb.CreateException;
009: import javax.ejb.EJBException;
010: import javax.ejb.SessionBean;
011: import javax.ejb.SessionContext;
012: import javax.naming.InitialContext;
013: import javax.sql.DataSource;
014: import javax.transaction.UserTransaction;
015:
016: /*
017: * @ejb:bean name="DBStateful"
018: * display-name="DBStatefulBean"
019: * type="Stateful"
020: * transaction-type="Bean"
021: * jndi-name="com/mockrunner/example/DBStateful"
022: **/
023: /**
024: * A simple BMT stateful session bean with a method that
025: * executes an SQL statement.
026: */
027: public class DBStatefulBean implements SessionBean {
028: private SessionContext sessionContext;
029: private UserTransaction transaction;
030:
031: /*
032: * @ejb:interface-method
033: **/
034: public void beginTransaction() {
035: try {
036: transaction = sessionContext.getUserTransaction();
037: transaction.begin();
038: } catch (Exception exc) {
039: throw new EJBException(exc);
040: }
041: }
042:
043: /*
044: * @ejb:interface-method
045: **/
046: public void executeSQL(String sql) {
047: Connection connection = null;
048: Statement statement = null;
049: try {
050: InitialContext context = new InitialContext();
051: DataSource dataSource = (DataSource) context
052: .lookup("java:/MySQLDB");
053: connection = dataSource.getConnection();
054: statement = connection.createStatement();
055: statement.execute(sql);
056: } catch (Exception exc) {
057: throw new EJBException(exc.getMessage());
058: } finally {
059: try {
060: if (null != statement)
061: statement.close();
062: if (null != connection)
063: connection.close();
064: } catch (SQLException sqlExc) {
065:
066: }
067: }
068: }
069:
070: /*
071: * @ejb:interface-method
072: **/
073: public void endTransaction(boolean commit) {
074: try {
075: if (commit) {
076: transaction.commit();
077: } else {
078: transaction.rollback();
079: }
080: } catch (Exception exc) {
081: try {
082: transaction.rollback();
083: } catch (Exception exc2) {
084: throw new EJBException(exc2);
085: }
086: }
087: }
088:
089: /*
090: * @ejb:create-method
091: **/
092: public void ejbCreate() throws CreateException {
093:
094: }
095:
096: public void ejbActivate() throws EJBException, RemoteException {
097:
098: }
099:
100: public void ejbPassivate() throws EJBException, RemoteException {
101:
102: }
103:
104: public void ejbRemove() throws EJBException, RemoteException {
105:
106: }
107:
108: public void setSessionContext(SessionContext sessionContext)
109: throws EJBException, RemoteException {
110: this.sessionContext = sessionContext;
111: }
112: }
|