OpenEJB - configuring datasource for JUnit
-
12-06-2021 - |
سؤال
I have problem with proper configuration of datasource for OpenEJB 3.1.3. I try to configure connection to postgres db, but hen I debug test I get default hsql connection parameters.
Here is my test class:
@RunWith(ApplicationComposer.class)
public class OpenEJBTest {
@EJB
Files fb;
@Test
public void testSth() {
List<UploadSession> uploadNotFinishedSessions = fb.getUploadNotFinishedSessions();
}
@Module
public EjbJar beans() {
EjbJar ejbJar = new EjbJar("beans");
ejbJar.addEnterpriseBean(new StatelessBean(FilesBean.class));
ejbJar.addEnterpriseBean(new StatelessBean(FilesUtilBean.class));
ejbJar.addEnterpriseBean(new StatelessBean(ServerFilesBean.class));
ejbJar.addEnterpriseBean(new StatelessBean(UserUtilBean.class));
return ejbJar;
}
@Module
public PersistenceUnit persistence() {
PersistenceUnit unit = new PersistenceUnit("postgresPU", HibernatePersistence.class.getName());
String simpleXml = SimpleXmlUtil.toSimpleXml(unit);
System.out.println(simpleXml);
unit.setJtaDataSource("PostgresDS");
unit.setNonJtaDataSource("PostgresDSUnmanaged");
return unit;
}
}
I tried to:
- add jndi.properties to classpath:
postgresPU=new://Resource?type=DataSource postgresPU.JdbcDriver=org.postgresql.Driver postgresPU.JdbcUrl=jdbc:postgresql:/localhost:5433/pdb postgresPU.JtaManaged=true postgresPU.DefaultAutoCommit=false postgresPU.UserName=...
- Configure datasources via openejb.xml (located on classpath)
<Resource id="PostgresDS" type="DataSource"> JdbcDriver org.postgresql.Driver JdbcUrl jdbc:postgresql://localhost:5433/pdb UserName user Password pass JtaManaged true </Resource> <Resource id="PostgresDSUnmanaged" type="DataSource"> JdbcDriver org.postgresql.Driver JdbcUrl jdbc:postgresql://localhost:5433/pdb UserName user Password pass JtaManaged false </Resource>
But neither of it works - datasources are not being configured at all, the default version of datasource remains. Because of default hsql connection I get following bug:
WARN - SQL Error: -22, SQLState: S0002
ERROR - Table not found in statement [select top ? user0_.id as col_0_0_ from tusers user0_ where user0_.login=?]
What am I possibly doing wrong?
المحلول
The ApplicationComposer
doesn't use JNDI to bootstrap the container so the jndi.properties
file is never seen.
What you can do instead is use the org.apache.openejb.junit.Configuration
annotation on a method to have it return the properties you want to use to configure the test.
@Configuration
public Properties properties() {
//...
}
I'd rename jndi.properties
to something else so it isn't confusing, then you can use code like this to find it in the classpath.
final URL url = this.getClass().getResource("/config.properties");
final Properties props = new Properties();
final InputStream in = url.openStream();
try {
props.load(in);
} finally {
close(in);
}