tags:

views:

48

answers:

3

This is my stateless bean:

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

It explicitly defines that the name of persistence unit is production. This unit is configured in persistence.xml, and everything is fine. When I'm unit testing this class I have to use another persistence unit, with different set of properties and configuration settings. How should I organize it? Create another <persistence-unit> element in persistence.xml? Does any best practice exist for this?

+1  A: 

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

willcodejavaforfood
@willcodejavaforfood And how do you instruct container to use another persistence unit?
Vincenzo
@Vincenzo - I use Spring to configure that, I have a applicationContext.xml and a testApplicationContext :)
willcodejavaforfood
+3  A: 

I use the same persistent unit name but different persistent.xml (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.
Pascal Thivent
@Pascal Thanks, this is what I was looking for (test copy of `persistence.xml`). Of course I'm using Maven, what else? :)
Vincenzo
@Vincenzo Exactly, what else? :)
Pascal Thivent
A: 

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.

Ben Poole