Search code examples
databasespringjpaacl

JPA + Spring how to initialize database with custom tables and data


In my application I use Spring context and JPA. I have some set of entities annotated with @Entity and tables for them are created automatically during system startup. Recently I started using Spring ACL, so I have to have the following additional DB schema and I don't want these tables to be mapped to the entities (simply I don't need them to, because Spring ACL manages them independently).

  1. I want to automatically insert e.g. admin user account into the User's entity table. How to do that properly?
  2. I want to initialize Spring ACL custom tables during system startup, but the SQL script file does not seem to be good solution because if I use different database for production and functional testing, the different SQL dialect does not allow me to execute script properly on both engines (e.g. when using MySQL and HSQL).

At first I tried to use ServletListener that during servlet initialization check the db and adds the necessary data and schema, but this does not work for integration tests (because there are no servlet involved at all).

What I want to achieve is the Spring bean (?) that is launched after the JPA has initialized all entity tables, insert all startup data using injected DAOs and somehow creates the Spring ACL schema. Then - I want the bean to be removed from IoC (because I simly don't need it anymore). Is it possible?

Or is there any better way of doing this?


Solution

  • If you are using EclipseLink you could use a SessionEventListener to execute code after JPA login. You could perform your schema creation and setup in a postLogin event.

    You could use the Schema Framework in EclipseLink (org.eclipse.persistence.tools.schemaframework) to create tables and DDL in a database platform independent way. (TableDefinition, SchemaManager classes)