如何连接两个数据库实例?

时间:2014-03-07 09:10:26

标签: java spring hibernate jpa

无法从多对一的关系中获得结果  我有两个数据库:

@PersistenceContext(unitName = "admin")
    public void setAdminEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

@PersistenceContext(unitName = "user")
    public void setUserEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

----------------------------------------------

@Entity
@Table(name = "cd_state")
@NamedQueries({ 
    @NamedQuery(name = "State.findAll", query = "Select s from State s order by s.stateName ASC "),  

})
public class State {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long stateId;
    private String stateCode;
    private String stateName;

    @ManyToOne
    @JoinColumn(name = "countryId", insertable = false, updatable = false)
    private Country country;
    private Boolean isActive;
    private Long countryId;
getters and setters//
}

country belongs to admin databases::
-----------------------------

public List<User> getAllUsers() {
        TypedQuery<User> query = getuserEntityManager().createNamedQuery(FIND_ALL_USERS, User.class);

        List<User> list = query.getResultList();

        return list;
    }

it throws exception.not connecting to admin database.

2 个答案:

答案 0 :(得分:0)

创建两个@PersistenceContext,它有两种不同的数据库配置。

答案 1 :(得分:0)

我在上一个问题中提供的答案提供了演示如何操作的代码示例:

Multiple jpa:repositories in xml config, how to configure with @EnableJPARepositories using Spring java config?