VadOs VadOs - 5 months ago 9
Java Question

obtain datasource from resource 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 folowing 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 null pointer exception. does anybody know how to resolve this?

thank you

Answer

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");