欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot整合tk.mybatis入门2 通用service

程序员文章站 2022-07-15 10:11:38
...

之前讲的就不说了 现在直接到通用service

1.首先创建service通用类

/**
 * 
 * @author 	cyf
 * @date	2018/10/30 上午10:36:34
 * @param <T>
 */
public interface BaseService<T> {

    T selectByKey(Object key);
    
    T selectOne(T entity);

    int save(T entity);

    int delete(Object key);

    int updateAll(T entity);

    int updateNotNull(T entity);

    List<T> selectPage(int pageNum, int pageSize);

    List<T> selectPage(int pageNum, int pageSize, T entity);
    
}

2.现写一下通用service的实现

package com.orhonit.common.service.impl;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.orhonit.common.service.CommonService;

import tk.mybatis.mapper.common.Mapper;

/**
 * 
 * @author 	cyf
 * @date	2018/10/30 上午10:39:36
 * @param <T>
 */
@Service
public abstract class CommonServiceImpl<T> implements CommonService<T> {

    @Autowired
    protected Mapper<T> mapper;

    @Override
    public T selectByKey(Object key) {
        return mapper.selectByPrimaryKey(key);
    }
    
    @Override
    public T selectOne(T entity){
    	return mapper.selectOne(entity);
    }

    @Override
    public int save(T entity) {
        return mapper.insert(entity);
    }

    @Override
    public int delete(Object key) {
        return mapper.deleteByPrimaryKey(key);
    }

    @Override
    public int updateAll(T entity) {
        return mapper.updateByPrimaryKey(entity);
    }

    @Override
    public int updateNotNull(T entity) {
        return mapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public List<T> selectPage(int pageNum,int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        return mapper.selectAll();
    }

    @Override
    public List<T> selectPage(int pageNum, int pageSize, T entity) {
        PageHelper.startPage(pageNum,pageSize);
        return mapper.select(entity);
    }

}

注意:这里我将通用service做成抽象接口,也就意味着抽象方法可以让其子类实现(通用)

3.到目前为止tk.mybaits的通用mapper和service就讲解完毕了

直接在service层用就可以了
例如:


public interface UserService extends CommonService<SysUser> {
}
	

@Service
public class UserServiceImpl extends CommonServiceImpl<SysUser>  implements UserService {
}