I want to work with 2+ beans with database access, but I'm having problem accessing same database.
My first connection works fine, I'm getting the results I want.
@DataSourceDefinition(
name = "java:global/***/***",
className = "org.apache.derby.jdbc.ClientDataSource",
url = "jdbc:derby://localhost:1527/***",
databaseName = "***",
user = "***",
password = "***"
)
@Named(value = "userRepo")
@SessionScoped
public class UserRepo implements Serializable {
@Resource(lookup = "java:global/***/***")
DataSource dataSource;
public boolean validate() throws SQLException {
ResultSet rs = null;
if (dataSource == null) {
throw new SQLException("Unable to obtain DataSource");
}
Connection connection = dataSource.getConnection();
if (connection == null) {
throw new SQLException("Unable to connect to DataSource");
}
try {
PreparedStatement ps = connection.prepareStatement("select
email, password from customer " + "where email=? and
password=?");
ps.setString(1, getEmail());
ps.setString(2, getPassword());
rs = ps.executeQuery();
while (rs.next()) {
tempEmail = rs.getString("email");
tempPassword = rs.getString("password");
}
} // end try
finally {
connection.close();
}
}
When I try to use this on another bean with same method, it doesn't return wanted results (even with exact same query)
@DataSourceDefinition(
name = "java:global/***/***",
className = "org.apache.derby.jdbc.ClientDataSource",
url = "jdbc:derby://localhost:1527/***",
databaseName = "***",
user = "***",
password = "***"
)
@Named(value = "customer")
@SessionScoped
public class Customer implements Serializable {
@Resource(lookup = "java:global/***/***")
DataSource dataSource;
...
...
}
I tried: removing connection closing, injecting "UserRepo" bean with @Inject
and use its datasource with userRepo.dataSource
but no luck.
I guess, I can create all queries in "UserRepo" bean, but that seems awfully bad coding practice and godclasses are hard to handle.
Is there any way I can work on these 2 separate beans? Injection won't be problem.