2

Suppose the JPA provider is hibernate. Suppose it is not container managed, but application managed.

Given an entity class and correct annotation, is it possible to create table programatically, at runtime, and only for that class? By saying runtime, it means the entity class is not listed in the persistence.xml.

Theoretically, it is possible because we can manually read the annotations and generate SQL, and from the persistence unit we can read database connection url. My question is, is there anyway to do it without duplicating lots of work inside hibernate?

I found in other SO questions that Persistence.createSchema could be used, but I don't see where to specify the class.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Kan Li
  • 8,557
  • 8
  • 53
  • 93
  • As the JPA spec says clear enough, calling Persistence.generateSchema takes in the persistence unit, which would DEFINE which classes are in that unit. – Neil Stockton May 31 '15 at 08:49
  • @NeilStockton, as I said, I would like to see the entity class is not defined in the persistence unit, but specified at runtime. `Persistence.generateSchema` only takes in the persistence unit's name, how can I add the class to the persistence unit at runtime? – Kan Li May 31 '15 at 09:27

1 Answers1

0
  1. If the persistence.xml is not aware of your entity (either from explicitly listing it or from auto-scanning), then no JPA implementation will be able to generate a database schema for t.

  2. You can either generate the whole database schema from the JPA annotation or you don't generate it for any Entity. You can't generate a table definition only for one entity.

Your use case smells like a hack and you should probably address the requirement first.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • The requirement is the system contains plugins that can be loaded at runtime, so the entity can't be hard coded to persistence.xml. And it is not insane to avoid loading all entities in all plugins, but only the plugins that are needed. Whether a plugin should be loaded is specified at runtime. Is this requirement hacks? I don't think so. – Kan Li May 31 '15 at 16:28
  • then do you know how to crate persistence unit on the fly? – Kan Li May 31 '15 at 18:21
  • You can use Spring for that: http://stackoverflow.com/questions/21381943/how-to-configure-spring-without-persistence-xml – Vlad Mihalcea May 31 '15 at 18:26
  • Do I have to introduce another framework? Can't I just stick to hibernate? – Kan Li Jun 01 '15 at 03:54
  • No you can't. No JPA implementation offer such a feature. Spring simply works around it. You can code it yourself but it won't be trivial. Check Spring code and see how they did it. – Vlad Mihalcea Jun 01 '15 at 04:24