優化mybatis的Mapper依賴,service層優化
阿新 • • 發佈:2018-12-13
1.專案結構
2.新增IService.class、BaseService.class
package com.xpf.service; import org.springframework.stereotype.Service; import java.util.List; /** * 通用介面 */ @Service public interface IService<T> { T selectByKey(Object key); int save(T entity); int delete(Object key); int updateAll(T entity); int updateNotNull(T entity); List<T> selectByExample(Object example); //TODO 其他... }
package com.xpf.service.impl; import com.xpf.service.IService; import org.springframework.beans.factory.annotation.Autowired; import tk.mybatis.mapper.common.Mapper; import java.util.List; public abstract class BaseService<T> implements IService<T> { @Autowired protected Mapper<T> mapper; public Mapper<T> getMapper() { return mapper; } @Override public T selectByKey(Object key) { return mapper.selectByPrimaryKey(key); } public int save(T entity) { return mapper.insert(entity); } public int delete(Object key) { return mapper.deleteByPrimaryKey(key); } public int updateAll(T entity) { return mapper.updateByPrimaryKey(entity); } public int updateNotNull(T entity) { return mapper.updateByPrimaryKeySelective(entity); } public List<T> selectByExample(Object example) { return mapper.selectByExample(example); } //TODO 其他... }
2.新增service
package com.xpf.service;
import com.xpf.domain.UserInfo;
public interface UserService extends IService<UserInfo> {
}
package com.xpf.service;
import com.xpf.domain.UserInfo;
public interface UserService extends IService<UserInfo> {
}
3.測試
package com.xpf; import com.xpf.domain.SysRoles; import com.xpf.domain.UserInfo; import com.xpf.mapper.SysRolesMapper; import com.xpf.mapper.UserInfoMapper; import com.xpf.service.UserService; import org.apache.catalina.User; import org.junit.Test; import org.junit.runner.RunWith; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootMapperApplicationTests { @Autowired UserInfoMapper userInfoMapper; @Autowired SysRolesMapper sysRolesMapper; @Autowired UserService userService; @Test public void contextLoads() { } @Test public void tsetfindUser(){ System.out.println(userInfoMapper.selectByPrimaryKey(1)); System.out.println(sysRolesMapper.selectByPrimaryKey(1)); System.out.println(userService.selectByKey(1)); /* UserInfo userInfo=new UserInfo(); userInfo.setUid(1); System.out.println(userInfoMapper.selectOne(userInfo));*/ } }
4.結果