*
The moose likes EJB and other Java EE Technologies and the fly likes DataSource Connection in ejbCreate? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "DataSource Connection in ejbCreate?" Watch "DataSource Connection in ejbCreate?" New topic
Author

DataSource Connection in ejbCreate?

Brett B Doehr
Greenhorn

Joined: Jun 04, 2001
Posts: 11
I think it should be possible to obtain a Connection from a JDBC DataSource in an ejbCreate, doing the below:
// Resources.java
public class Resources {
private static DataSource dataSource;
static {
try {
dataSource =
(DataSource) new InitialContext().lookup("java:comp/env/jdbc/intersys");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getDBConnection() throws SQLException {
return dataSource.getConnection();
}
}
// EJB class
...
public void ejbCreate(String name)
throws CreateException {
Statement stmt = null;

try {
// This next line causes an SQL exception!!
stmt = Resources.getDBConnection().createStatement();
...
}
}
However, the above line results in:
java.sql.SQLException: Connections can only be accessed during a transaction
The bean is installed in the ObjectSpace Voyager server with transactions Required, so it should create a transaction if no transaction exists. Any thoughts on why the above doesn't work?
--Brett.
Brett B Doehr
Greenhorn

Joined: Jun 04, 2001
Posts: 11
Well, it appeared to be a problem with doing it in the ejbCreate. Must be something peculiar to the ObjectSpace Voyager EJB container, since the J2EE tutorials seem to indicate it should work. Anyway, I moved my DB stuff from the ejbCreate to a business method and it now works.
--Brett.
Steve Chernyak
Ranch Hand

Joined: Oct 19, 2000
Posts: 113
I wonder if putting this code into the ejbPostCreate() method would work.
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

It's because ejbCreate is not a constructor. Not even hypothetically similar.
I ran into this as well.
If you run a business method on 'any old bean'... then maybe the container didn't need to call ejbCreate. That only gets called when you do a brand new bean.
I put my db stuff into the setEntityContext, because that is GUARANTEED to be run once, no matter HOW you came by the particular reference to that particular bean.
Brett B Doehr
Greenhorn

Joined: Jun 04, 2001
Posts: 11
Wait a minute...so you're saying that things like ejbPostCreate and setEntityContext actually have a purpose and aren't intended to always just be empty required functions?!
Thanks for pointing out what should have been obvious. Although it should have been creating a new bean in the situation I was in, using setEntityContext should certainly work, and ejbPostCreate might as well.
 
Consider Paul's rocket mass heater.
 
subject: DataSource Connection in ejbCreate?