Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

java - 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...