在 Spring 中为持久单元使用不同的数据源
好吧,我对此很陌生。我想做的是说“这些类保存在这里(数据库a),这些类保存在那里(数据库b)”。我认为我应该在不同的持久性单元组下显式定义类,这些类还可以保存带有驱动程序信息的属性集合。
<persistence-unit name="nytdModel" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>gov.vermont.dcf.nytd.model.AbstractElementImpl</class>
...
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver_class" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:jtds:sqlserver://localhost;..."/>
<property name="hibernate.connection.username" value="..."/>
<property name="hibernate.connection.password" value="..."/>
</properties>
</persistence-unit>
然后在我的 Dao 类中,我应该只提供上下文:
@Repository
public class AFCARSJpaDao
{
@PersistenceContext(unitName = "nytdModel")
private EntityManager entityManger;
}
但是,我收到了 No unique bean of type [javax.persistence.EntityManagerFactory] is Defined: Expected single bean but find 2
错误。我做错了什么?
我正在使用Spring 3.0.4
Ok, I' new to this. What I want to do is say "these classes are persisted over here (database a), and these classes over there (database b)". I think I'm supposed to define the classes explicitly under different persistence-unit groups, which can also hold a collection of properties with the driver info.
<persistence-unit name="nytdModel" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>gov.vermont.dcf.nytd.model.AbstractElementImpl</class>
...
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver_class" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:jtds:sqlserver://localhost;..."/>
<property name="hibernate.connection.username" value="..."/>
<property name="hibernate.connection.password" value="..."/>
</properties>
</persistence-unit>
Then in my Dao classes, I should just provide the context:
@Repository
public class AFCARSJpaDao
{
@PersistenceContext(unitName = "nytdModel")
private EntityManager entityManger;
}
However, I'm getting a No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 2
error. What am I doing wrong?
I'm using Spring 3.0.4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您尝试在某处注入带有
@Autowired
的EntityManagerFactory
。始终使用
@PersistenceContext
注入EntityManager
和@PersistenceUnit
注入EntityManagerFactory
,它们应该处理多个持久化的情况单位正确(如果您指定了unitName
属性)。It looks like you try to inject an
EntityManagerFactory
with@Autowired
somewhere.Always use
@PersistenceContext
to injectEntityManager
and@PersistenceUnit
to injectEntityManagerFactory
, they should handle the case of multiple persistence units correctly (if you specifyunitName
attribute on them).