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

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

1.首先创建service通用类

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

    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 selectPage(int pageNum, int pageSize);

    List 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 
 */
@Service
public abstract class CommonServiceImpl implements CommonService {

    @Autowired
    protected Mapper 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 selectPage(int pageNum,int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        return mapper.selectAll();
    }

    @Override
    public List 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 {
}
	

@Service
public class UserServiceImpl extends CommonServiceImpl  implements UserService {
}

你可能感兴趣的:(tk.mybatis,使用过程中的问题解决)