|
Using a data source in EJB |
|
|
Connecting to a database via JDBC is essential in many applications. For instance, a session bean needs to access data
to complete a business function, and entity beans with bean-managed persistence require access to a JDBC connection to load
and store data. The application server running the EJB application provides data sources as specified by the deployer.
To retrieve the javax.sql.DataSource object from the application server, we have to complete two steps. First, we have to
configure the deployment descriptor for the bean that will need access to the DataSource object. Second, acquire
the DataSource reference by performing a JNDI lookup.
////////////// configuration in deployment descriptor:
<ejb-jar>
<enterprise-beans>
<session>
<!-- main bean definitions -->
<ejb-name>TestDBEJB</ejb-name>
<home>test.TestDBSourceHome</home>
<remote>test.TestDBSource</remote>
<ejb-class>sample.TestDBSourceBean</ejb-class>
<session-type>Stateless</session-type>
<!-- definition of resources bean referes -->
<resource-ref>
<res-ref-name>ejbDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</session>
</enterprise-beans>
<assembly-descriptor>
</assembly-descriptor>
</ejb-jar>
////////////// EJB code retreiving data source connection:
import javax.ejb.SessionBean;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection ;
public class TestDBSourceBean implements SessionBean {
...
public Connection getConnection() {
try {
// prepare context:
InitialContext context = new InitialContext();
// retreive DB-source
DataSource source = (javax.sql.DataSource)
context.lookup("java:comp/env/ejbDB");
return source.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
...
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.