I have a Spring/JPA/Hibernate application that maintains state data in a mysql table. The application is dependent on that state data being initialized properly. That is, when the application initializes, I want to ensure that a known table includes two rows-- one each with two known primary key values.
The table is "JPA managed" (sorry if that term is not correct)-- I have an @Entity
class that maps each row in the table to an instance of that class and a corresponding DAO class that manipulates (persists, retrieves) instances of that @Entity
.
My (unsuccessful) attempt to solve this problem used an initialize()
method on the DAO annotated with @PostConstruct
(as well as @Transactional(read-only = false)
). That method instantiates two instances of the @Entity
and has calls the EntityManager
to persist them (I use persist instead of merge to avoid overwriting existing state and catch the EntityExistsException
that's expected if the row(s) already exist).
I've confirmed that the initialize()
method is being invoked and is calling the persist(...)
method on the EntityManager
but the database rows are not being inserted-- I've examined the mysql statement log and the expected INSERT
statements are not present.
I can't be the first person who wants to initialize data in a JPA-managed table, right? Is there a "best-practice" for doing this sort of initialization?
Thanks!
PS: Although the table is "JPA-managed" it is not created by Hibernate. The table is assumed (by the application) to already exist.