问题描述
我有一个Hibernate项目和多个实体。每个实体需要连接到几个数据库。 (table1,table2,table3,tabl4)相同的模式。这可以完成吗?或者我需要为每一个创建一个单独的实体?
我的实体看起来像这样
@Entity
public class table1 {
@Id
@Column(name =name)
private String name;
@Column(name =age)
private String age;
// getters setters
}
您可以为具有相似模式的不同数据库使用相同的实体,但必须创建指向特定数据库的 EntityManager
。
- 为每个数据库创建持久性单元。
以下是persistence.xml
< persistence-unit name =DB_X>
< jta-data-source> java:/ OracleDS< / jta-data-source>
...
< / persistence-unit>
<! - 其他持久性单位 - >
为特定单位创建EntityManager
@PersistenceContext(unitName =DB_X)
private EntityManager xEM;
@PersistenceContext(unitName =DB_Y)
private EntityManager yEM;
- 否则,也可以在运行时如下创建。 >
此后,您可以使用与具有相似模式的不同数据库相同的实体,表结构适当的 EntityManager
。
/ strong>:根据您的意见,与您发布的问题不同,您似乎试图为多个表使用相同的实体。以下是它的示例代码。
@MappedSuperClass
public class abstract BaseEntity {
@Id
@Column(name =name)
private String name;
@Column(name =age)
private String age;
// - 访问器方法
}
@Entity
@Table(name =XTable)
public class XEntity extends BaseEntity {
public XEntity(){}
}
@Entity
@Table(name =YTable)
public class YEntity extends BaseEntity {
public YEntity(){}
}
XEntity
& YEntity
类似,但指向各自的表格。
I have a Hibernate project, and multiple entities. Each entity needs to connect to several database. (table1, table2, table3, tabl4) 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
}
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.
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.
这篇关于hibernate多个模式映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!