开发者

How to use several databases with Spring MVC and Hibernate?

For example I have one class mapped to a table in first database and the second class mapped to a table in the second database. I would like to use them simultaneously in one application. I have a datasource bean defined in my dispatcher-servlet.xml

    <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>

and here is my Mapped class

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;
    }开发者_如何学Go

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

How can I map this class to the first database and the second class to the second? Thank you very much for your replies!


You will have to define two datasources and two session factory. One session factory holding the reference of one datasource.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜