0

我正在使用 Eclipse Juno IDE 和 phpMyAdmin。

我有 java 应用程序,对于这个应用程序,我在 phpMyAdmin 中创建了一个数据库。现在,我有一个 DB 方法的接口。可以说接口是这样的:

public interface DBInterface{
  public Vector<Employees> getAllEmplyess();
  public void addNewEmployee(int ID, String name,String department);
}

现在我需要通过两种方式实现这个接口:

1) JPA

2) JDBC

假设我以上述两种方式实现了接口。

如何在 applicationContext.xml 文件中使用 spring 机制进行选择?它是如何工作的?

4

2 回答 2

2

为什么需要 JPA 和 JDBC 实现(JPA 基于 JDBC)?

区分两者的方法是创建2个单独的DAO类(都实现你的接口)

public class JDBCDao implements DBInterface {...}
public class JPADao implements DBInterface {...}

并在需要时在 spring xml(应用程序上下文文件)中注入适当的 DAO bean。

例如,应用程序上下文 xml 看起来像:(daoEmployeeService 类的成员是 type DBInterface

<bean id="JPADAO" class="com.yourpackage.JPADao".../>
<bean id="JDBCDAO" class="com.yourpackage.JDBCDao".../>

<bean id="EmployeeService" class ....>
    <property name="dao" ref="JDBCDAO" />
    ...
</bean>

或者,您可以在代码中注入 DAO。

ApplicationContext ctx = AppContext.getApplicationContext();  
EmployeeService svc = (EmployeeService) ctx.getBean("EmployeeService");  
DBInterface dao = (DBInterface) ctx.getBean("JPADAO");
svc.setDao(dao);
于 2012-09-03T11:14:51.167 回答
1

除了 JPA 依赖于 JDBC 的事实之外......

如果您想通过ApplicationContext XML 文件来控制它,最简单的方法是简单地定义您选择的实现。假设您有两个实现

 public class JpaDB implements DBInterface { ... }
 public class JdbcDB implements DBInterface { ... }

和一个期望 a 的服务DBInterface,比如说

 public class Service {
     private DBInterface db;

     public void setDBInterface(DBInterface db) {
        this.db = db;
     }
 }

然后你的 spring 配置文件可能看起来像

...
<bean id="service" class="com.company.service">
    <!-- Select either "jpa" or "jdbc" depending on preference -->
    <property name="dbInterface" ref="jpa"/> 
</bean>

<bean id="jpa" class="com.company.JpaDB"/>
<bean id="jdbc" class="com.company.JpaDB"/>
于 2012-09-03T11:14:05.000 回答