前言:实现代码复用,简化代码是非常有必要的,我觉得jeesite这个开源项目非常不错,代码中使用的技术非常全面,而且是一个完整的项目,基本包含了项目的所有知识点,大家有兴趣可以到官网看看,地址在这
现在项目基本的分层一般有 service,dao,entity,web,utils 等,java 有些属性非常适合去开发公共的接口,例如继承,封装,多态,抽象类,泛型等。
目前主流使用的是springboot+mybatis技术,关于mybatis也有一些常用的接口实现,例如mybatis-plus 里面也是有一些现成的接口实现。
这里用自己的方式实现。
dao 层
public interface BaseDao<T> {
int deleteByPrimaryKey(Integer id);
int insert(T record);
int insertSelective(T record);
T selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(T record);
int updateByPrimaryKey(T record);
}
public interface LpProductDao extends BaseDao<LpProduct> {
}
对应的mapper xml文件添加上。
service 层
package com.fengdu.service.base;
import com.fengdu.dao.base.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;
public class BaseService{
}
package com.fengdu.service.base;
import com.fengdu.dao.base.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Transactional(readOnly = false)
public abstract class CrudService <D extends BaseDao<T>,T extends Object> extends BaseService {
@Autowired
protected D dao;
public int deleteByPrimaryKey(Integer id){
return dao.deleteByPrimaryKey(id);
}
public int insert(T record){
return dao.insert(record);
}
public int insertSelective(T record){
return dao.insertSelective(record);
}
public T selectByPrimaryKey(Integer id){
return dao.selectByPrimaryKey(id);
}
public int updateByPrimaryKeySelective(T record){
return dao.updateByPrimaryKeySelective(record);
}
public int updateByPrimaryKey(T record){
return dao.updateByPrimaryKey(record);
}
}
package com.fengdu.service.impl;
import com.fengdu.dao.LpProductDao;
import com.fengdu.dao.base.BaseDao;
import com.fengdu.entity.LpProduct;
import com.fengdu.service.base.CrudService;
import org.springframework.stereotype.Service;
@Service("lpProductService")
public class LpProductService extends CrudService<LpProductDao,LpProduct> {
}
这样就可以 比较简洁的方式实现增删改查的调用