如何使用Spring MVC和Hibernate的几个数据库?

时间:2010-11-09 01:31:23

标签: hibernate spring spring-mvc

例如,我有一个类映射到第一个数据库中的表,第二个类映射到第二个数据库中的表。 我想在一个应用程序中同时使用它们。 我在dispatcher-servlet.xml

中定义了一个数据源bean
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.example.model.Article</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>             
            </props>
        </property>
    </bean>

这是我的Mapped类

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "article")
public class Article {

    @Id
    @GeneratedValue
    @Column(name = "article_id")
    private Long articleId;

    @Column(name = "article_name", nullable = false, length=20)
    private String articleName;

    @Column(name = "article_desc", nullable = false)
    private String articleDesc;

    @Column(name = "date_added")
    private Date addedDate;

    public Article() {      
    }

    public Long getArticleId() {
        return articleId;
    }

    public void setArticleId(Long articleId) {
        this.articleId = articleId;
    }

    public String getArticleName() {
        return articleName;
    }

    public void setArticleName(String articleName) {
        this.articleName = articleName;
    }

    public String getArticleDesc() {
        return articleDesc;
    }

    public void setArticleDesc(String articleDesc) {
        this.articleDesc = articleDesc;
    }

    public Date getAddedDate() {
        return addedDate;
    }

    public void setAddedDate(Date addedDate) {
        this.addedDate = addedDate;
    }   
}

如何将此类映射到第一个数据库,将第二个类映射到第二个数据库? 非常感谢您的回复!

1 个答案:

答案 0 :(得分:4)

您必须定义两个数据源和两个会话工厂。一个会话工厂持有一个数据源的引用。