Search code examples
javajakarta-eedatasourceapache-tomeetomee-7

How to obtain datasource from resource(s) in TomEE 7?


I'm doing java EE web application with deployment to TomEE 7 and I need to get datasource from tomee.xml. tomee.xml is located in WEB-INF directory and has the following content:

<?xml version="1.0" encoding="UTF-8"?>
<tomee>
    <Resource id="rss_db_datasource" type="javax.sql.DataSource">
        JdbcDriver = org.hsqldb.jdbcDriver
        JdbcUrl = jdbc:hsqldb:file:/rss_db
        UserName = sa
        Password =
    </Resource>
</tomee>

I'm trying to inject Datasource using this code:

@Resource(name="rss_db_datasource", type = javax.sql.DataSource.class)
    private DataSource dataSource;

When I try to get connection from the datasource I get NullPointerException. does anybody know how to resolve this?

thank you


Solution

  • META-INF -> context.xml

    <?xml version='1.0' encoding='utf-8'?>
    <Context>
        <Resource name="rss_db_datasource" type="javax.sql.DataSource"
                  username="sa" password=""
                  driverClassName="org.hsqldb.jdbcDriver" url="jdbc:hsqldb:file:D:/rss_db"
                />
    </Context>
    

    and then getting DataSource object

            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            dataSource = (DataSource) envCtx.lookup("rss_db_datasource");