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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…