user1817081
user1817081

Reputation: 1193

hibernate multiple schema mapping

I have a Hibernate project, and multiple entities. Each entity needs to connect to several database. (table1, table2, table3, table4) same schema.

Can this be accomplish? or do I need to create a separate entity for each of those?

My entity look something like this

@Entity
public class table1{
     @Id
     @Column(name="name")
     private String name;

     @Column(name="age")
     private String age;

     //getters setters
}

Upvotes: 1

Views: 5259

Answers (1)

Nayan Wadekar
Nayan Wadekar

Reputation: 11612

You can use same entity for different databases having similar schema, but have to create EntityManager pointing to the specific database.

  • Creating persistence unit for each database.

Below is the sample code for persistence.xml

<persistence-unit name="DB_X"> 
<jta-data-source>java:/OracleDS</jta-data-source>  
... 
</persistence-unit>
<!-- Other Persistence Units -->

Creating EntityManager for specific unit

@PersistenceContext(unitName="DB_X")
private EntityManager xEM;

@PersistenceContext(unitName="DB_Y")
private EntityManager yEM;
  • Else, can also create it at runtime as below.

EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName); EntityManager em = emf.createEntityManager();

Afterwards, you can use same entity with different databases having similar schema ,table structure with appropriate EntityManager.


Edit : Based on your comments, which differed from what you had posted as question, it seems you are trying to use same entity for multiple tables. Below is the sample code for it.

@MappedSuperClass
public class abstract BaseEntity {
     @Id
     @Column(name="name")
     private String name;

     @Column(name="age")
     private String age;

     //-- accessor methods
}

@Entity
@Table(name = "XTable")
public class XEntity extends BaseEntity {
    public XEntity(){}
}

@Entity
@Table(name = "YTable")
public class YEntity extends BaseEntity {

    public YEntity(){}
}

Here, XEntity & YEntity are similar, but points to their respective tables.

Upvotes: 2

Related Questions