Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
949 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...