Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jpa

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?

like image 990
yegor256 Avatar asked Oct 05 '10 09:10

yegor256


People also ask

How is persistence unit defined?

A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application. This set of entity classes represents the data contained within a single data store. Persistence units are defined by the persistence.xml configuration file.

Can we have multiple persistence xml?

xml files. Have multiple persistence units in one persistence.


2 Answers

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

like image 32
willcodejavaforfood Avatar answered Nov 03 '22 19:11

willcodejavaforfood


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.
like image 84
Pascal Thivent Avatar answered Nov 03 '22 19:11

Pascal Thivent