如何创建BaseDAO + JDBC并像@Autowired变量一样使用它?

时间:2016-02-08 09:13:19

标签: java spring jdbc dao

之前我曾使用过HIOnate ORM的DAO并且工作正常。但现在我需要使用DAO和JDBC,我不明白如何创建单个连接点。

我用过这个:

public interface BaseDao<E> {
    public E persist(E e);

    public E get(Long id);

    E get(Integer id);

    public List<E> getAll();

    E merge(E e);

}

和实现

@Repository
@Transactional(propagation = Propagation.REQUIRED)

public abstract class BaseJpaDao<E> implements BaseDao<E> {

    protected Class<?> entityClass;

    @PersistenceContext(unitName = "mainDataBase")
    protected EntityManager entityManager;

    public BaseJpaDao(Class<?> entityClass) {
        this.entityClass = entityClass;
    }

    @Override
    public E persist(E e) {       
        entityManager.persist(e);
        return e;
    }

    @Override
    public E get(Long id) {
        return (E) entityManager.find(entityClass, id);
    }

    @Override
    public E get(Integer id) {
        return (E) entityManager.find(entityClass, id);
    }

    @Override
    public List<E> getAll(){
        return getSession().createCriteria(entityClass).list();
    }

    @Override
    public E merge(E e){
        checkFieldsForNull(e);
        return entityManager.merge(e);
    }

但现在我需要使用JDBC而且我使用它:

  public class BaseDao {
        private DataSource dataSource;
        private JdbcTemplate jdbcTemplate;

        public BaseDao(String serviceName) throws NamingException {
            Context envContext = new InitialContext();
            String jndiUrl = MessageFormat.format("osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/{0})", serviceName);
            dataSource = (DataSource) envContext.lookup(jndiUrl);
        }

    public BaseDao(DataSource dataSource) {
        this.dataSource = dataSource;
    }
}

并实现:

@Repository
public class SubscriberDaoImpl extends BaseDao implements SubscriberDao {

    public SubscriberDaoImpl(String serviceName) throws NamingException {
        super(serviceName);
    }

    @Override
    public List<SubsDetail> getSubsDetils(Long subsId, Date startDate, Date endDate) {
        return null;
    }
}

在此之后我想使用我的DAO类:

public class SubscriberProcessorImpl implements SubscriberProcessor {

    @Autowired
    SubscriberDao subscriberDao;


    @Override
    public String getSubscriberDetail(Long id, Date startDate, Date endDate) {
        List<SubsDetail> subsDetils = subscriberDao.getSubsDetils(id, startDate, endDate);

        return DataFormatUtil.me().prepareResponseJson(subsDetils, ResultCode.SUCCESS, "");
    }
}

但我需要将参数传递给DAO,我不明白它是怎么做的。

0 个答案:

没有答案