java dao public <t> t execute_Java EE DAO / DTO(数据传输对象)设计模式

我通常倾向于创建一个基本的dao接口,其中包含我所有域实体共有的方法的定义,例如:

// marker interface

public interface DomainEntity extends Serializable { }

// common dao methods

public interface DAO {

public T findById(Long id);

public List findAll();

public T save(T entity);

public boolean update(T entity);

public boolean delete(T entity);

}

然后根据我的要求提供一个或多个实现:

// implementation of common dao methods using JPA

public class JpaDAO implements DAO {

private EntityManager em;

public JpaDao(EntityManager em) { this.em = em; }

// Default implementations using JPA...

}

// implementation of common dao methods using JDBC

public class JdbcDAO implements DAO {

private Connection conn;

public JdbcDao(Connection conn) { this.conn = conn; }

// Default implementations using JDBC

}

现在,假设我有以下人员类:

public class Person implements DomainEntity {

private Long id;

private String firstName;

private String lastName;

// getters/setters...

}

我首先定义一个通用的PersonDAO接口,如下所示:

public interface PersonDAO implements DAO {

public List findByFirstName(String name);

public List findByLastName(String name);

}

请注意,在我上面的特定实体dao接口中,我只包含了特定于我的域实体的额外方法.常用方法由超级接口继承,并使用泛型参数化到我的域实体.

现在剩下的事情是定义我的实体特定方法的不同实现,如下所示:

package mypackage.daos.jpa;

public class PersonDAOImpl extends JpaDAO implements PersonDAO {

// here i implement only the entity specific dao methods

// defined in the last interface.

}

如果我还需要提供替代的DAO实现(比如基于jdbc而不是JPA),那么就像创建第二个类(最好是在一个单独的包中)一样简单:

package mypackage.daos.jdbc;

public class PersonDAOImpl extends JdbcDAO implements PersonDAO {

// again i only implement the entity specific DAO methods since

// defaults have been implemented in the super class...

}

关于这一点的好处是你可以在没有调用代码的情况下切换实现,从而受到影响:

// a service class that uses my dao

public class PersonService {

private PersonDAO dao;

public PersonService(PersonDAO dao) { this.dao = dao }

public void doSomethingUseful() {

// use the dao here...

}

}

通常,在服务创建期间,将通过构造函数注入正确的dao实现(jdbc或jpa).当然,如果你愿意,你只能有一个实现(即jpa).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值