How to define two persistence units (one for production, one for unit testing)?

后端 未结 4 970
一整个雨季
一整个雨季 2020-12-31 14:25

This is my stateless bean:

@Stateless
public class Finder {
  @PersistenceContext(unitName = \"production\")
  EntityManager em;
  [...]
}

相关标签:
4条回答
  • 2020-12-31 14:46

    I had a similar problem and I want to provide another approach. I wanted to run test an prod, but I don't use two persistence.xml or code modifications. I just have one persistence unit, but different runtime environments (standalone.xml, Wildfly). Let's say that I want run against my development database, I start Wildfly with the test runtime environment. When I want simulate it as real user I run against the prod environment. The only difference is the datasource entry in standalone.xml. The descriptor is always the same (e.g. myappDS, so the persistence unit declaration in persistence.xml is always the same too), but in test server the datasource entry points to my test database, in prod the datasource entry points to my prod database.

    0 讨论(0)
  • 2020-12-31 14:48

    I use the same persistent unit name but different persistence.xml files (how are you going to automate testing if you need to edit the code to enable the "test mode"?).

    If you're still using Maven, Maven supports natively having testing versions of configuration files:

    • the "production" persistence.xml goes under src/main/resources/META-INF
    • the "test" persistence.xml goes under src/test/resources/META-INF and is used for testing.
    0 讨论(0)
  • 2020-12-31 14:53

    I simply created another <persistence-unit> element in persistence.xml.

    0 讨论(0)
  • 2020-12-31 14:54

    You can create a second persistence unit in your configuration, but that doesn't necessarily mean you should. Multiple PUs are of course entirely right and proper, but I'd steer clear of mixing them up when they're specifically for different environments, e.g. production versus test.

    In your instance, I'd have two persistence configuration files, and have Ant / Maven / build tool of choice copy / rename the correct one when appropriate.

    0 讨论(0)
提交回复
热议问题