Jdbc使用JSF在另一个bean中重用数据源

时间:2018-05-12 23:42:40

标签: jsf jdbc

我想使用具有数据库访问权限的2+ bean,但我在访问相同数据库时遇到问题。

我的第一个连接工作正常,我得到了我想要的结果。

    @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();
            }
        }

当我尝试在同一个方法的另一个bean上使用它时,它不会返回想要的结果(即使是完全相同的查询)

    @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;
        ...
        ...
    }

我尝试过:删除连接关闭,注入" UserRepo"使用@Inject的bean并将其数据源与userRepo.dataSource一起使用,但没有运气。

我想,我可以在" UserRepo"中创建所有查询bean,但这似乎非常糟糕的编码练习和教堂很难处理。

我有什么方法可以处理这两个独立的bean吗?注射不会成为问题。

1 个答案:

答案 0 :(得分:-1)

我尝试使用DriverManager连接第二次并且它有效。无法在互联网上找到任何其他答案连接到使用多个bean的Derby DB DataSource