Tuesday, February 18, 2014

Hibernate JPA 2.1 Use multiple database schemas : One database, two schemas

Removed
I was working with JPA2.1, Hibernate implementation when I have figured a problem. I have a database with two different schema.

Step 1: Remove validation

If JPA validation is not removed, you will get errors


Step 2:  Define persistence.xml

In the persistence.xml define two persistence-unit each for one schema



Step 3: Define the mapping file

Now we define the two mapping files with schema name.


Step4: Create Entities


Once the entities created, make sure that the class description is located in the right persistence-unit. I have seen that generated with eclipse, by default all classes description will be in the first persistence-unit. 

In the entity itself, you can add also the schema name (You can use the auto-completion as eclispe recognize the two schemas)

@Table(name="myTable", schema="myschema1")

Step 5: Specify the unitName

Every time that you use @PersistenceContext or @PersistenceUnit annotation in your code, you should specify the persistence unit name that you are using.

@PersistenceContext(unitName="urm_mdd_module_schema")


2 comments :

  1. How do you map the .java classes? in persistence.xml? inside the mapping-file?

    Thanks you Mariem.
    This article is very useful for me.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete

Articles les plus consultés