Hi Marc,
Yes it’s possible and probably it’s the simplest way to work with external data in your case: if you have a repository with a hashmap storing entities, the same can be done with in-memory database, although a bit more CPU cycles will be involved And you will have the full power of generic framework mechanisms like Filter for free. The way with a custom DataStore implementation is also possible, but it will require a lot more efforts and I will try to explain it later.
So just go to the Studio UI and define an additional data store. At the moment, Studio won’t allow you to define a HSQL database as an additional store, because it will conflict with the main database (if it’s also HSQL). Probably we should add support for in-memory HSQL, based on your use case. Define a Postgres database, then edit your datasource definition in context.xml
as follows:
<!--Data store 'inmem' connection-->
<Resource driverClassName="org.hsqldb.jdbc.JDBCDriver"
maxIdle="2"
maxTotal="20"
maxWaitMillis="5000"
name="jdbc/inmem"
password=""
type="javax.sql.DataSource"
url="jdbc:hsqldb:mem:inmem"
username="sa"/>
Now you need to create DB schema in the in-mem database at the server startup. Create a DDL script somewhere in the core
module and a bean that executes the script at startup:
drop schema public cascade^
create table foo (
id bigint not null primary key,
name varchar(100)
)^
@Component
public class InMemDbInitializer {
private static final Logger log = LoggerFactory.getLogger(InMemDbInitializer.class);
@EventListener
private void onAppContextStarted(AppContextStartedEvent event) {
log.info("Initializing in-mem DB...");
try {
QueryRunner queryRunner = new QueryRunner(AppBeans.get("cubaDataSource_inmem", DataSource.class));
InputStream stream = getClass().getResourceAsStream("create-inmem-db.sql");
String content = IOUtils.toString(stream, StandardCharsets.UTF_8);
for (String sql : Splitter.on("^").omitEmptyStrings().trimResults().split(content)) {
log.debug("Executing SQL on in-mem DB:\n" + sql);
queryRunner.update(sql);
}
} catch (Exception e) {
log.error("Cannot create in-mem DB schema", e);
}
}
}
That’s all. You can create entities for the additional data store and work with them as usual. The only difference is that all data will be lost after server shutdown.
When I prepared the example, I found that “contains” filter conditions do not work with in-memory entities for some reason. So I’ve just upgraded HSQL to the latest version and now it works, see build.gradle
:
configure(coreModule) {
dependencies {
// ...
jdbc('org.hsqldb:hsqldb:2.4.1')
}
Make sure you have only this version of HSQL in tomcat/lib
after deployment.
Attached the example project: inmem-datastore.zip (85.2 KB)
Regards,
Konstantin