一、项目结构
二、pom.xml 和 application.yml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>club.xcreeper</groupId> <artifactId>general-mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <name>general-mybatis</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&allowMultiQueries=true&useSSL=false tomcat: init-s-q-l: SET NAMES utf8mb4 username: username password: password
三、数据库
一张用户表
CREATE TABLE `user` ( `id` bigint(20) NOT NULL, `username` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `create_date_time` datetime DEFAULT NULL, `update_date_time` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
四、通用dao,不能放在dao层,否则扫描后报错,专门建一个包core放通用dao和通用service
package club.xcreeper.generalmybatis.core.dao; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; public interface BaseDao<T> extends Mapper<T> , MySqlMapper<T> { }
通用dao接口只需继承 tk.mybatis 中的 Mapper<T> 和 MysqlMapper<T>
五、通用service接口
package club.xcreeper.generalmybatis.core.service; import club.xcreeper.generalmybatis.core.service.impl.BaseServiceImpl; import org.apache.ibatis.session.RowBounds; import java.util.List; public interface BaseService<T> { int deleteByPrimaryKey(Object o); int delete(T t); int insert(T t); int insertSelective(T t); boolean existsWithPrimaryKey(Object o); List<T> selectAll(); T selectByPrimaryKey(Object o); int selectCount(T t); List<T> select(T t); T selectOne(T t); int updateByPrimaryKey(T t); int updateByPrimaryKeySelective(T t); int deleteByExample(Object o); List<T> selectByExample(Object o); int selectCountByExample(Object o); T selectOneByExample(Object o); int updateByExample(T t, Object o); int updateByExampleSelective(T t, Object o); List<T> selectByExampleAndRowBounds(Object o, RowBounds rowBounds); List<T> selectByRowBounds(T t, RowBounds rowBounds); int insertList(List<? extends T> list); int insertUseGeneratedKeys(T t); BaseServiceImpl<T> page(int page, int rows); int total(); }
六、通用service实现
package club.xcreeper.generalmybatis.core.service.impl; import club.xcreeper.generalmybatis.core.dao.BaseDao; import club.xcreeper.generalmybatis.core.service.BaseService; import com.github.pagehelper.PageHelper; import org.apache.ibatis.session.RowBounds; import java.util.List; public abstract class BaseServiceImpl<T> implements BaseService<T> { private BaseDao<T> dao; // private int page; // // private int rows; public void setBaseDao(BaseDao<T> baseDao) { this.dao = baseDao; } @Override public int deleteByPrimaryKey(Object o) { return dao.deleteByPrimaryKey(o); } @Override public int delete(T t) { return dao.delete(t); } @Override public int insert(T t) { return dao.insert(t); } @Override public int insertSelective(T t) { return dao.insertSelective(t); } @Override public boolean existsWithPrimaryKey(Object o) { return dao.existsWithPrimaryKey(o); } @Override public List<T> selectAll() { // if (rows>0){ // PageHelper.startPage(page,rows); // } List<T> list = dao.selectAll(); // this.rows = 0; return list; } @Override public T selectByPrimaryKey(Object o) { return dao.selectByPrimaryKey(o); } @Override public int selectCount(T t) { return dao.selectCount(t); } @Override public List<T> select(T t) { // if (rows>0){ // PageHelper.startPage(page,rows); // } List<T> list = dao.select(t); // this.rows = 0; return list; } @Override public T selectOne(T t) { return dao.selectOne(t); } @Override public int updateByPrimaryKey(T t) { return dao.updateByPrimaryKey(t); } @Override public int updateByPrimaryKeySelective(T t) { return dao.updateByPrimaryKeySelective(t); } @Override public int deleteByExample(Object o) { return dao.deleteByExample(o); } @Override public List<T> selectByExample(Object o) { // if (rows>0){ // PageHelper.startPage(page,rows); // } List<T> list = dao.selectByExample(o); // this.rows = 0; return list; } @Override public int selectCountByExample(Object o) { return dao.selectCountByExample(o); } @Override public T selectOneByExample(Object o) { return dao.selectOneByExample(o); } @Override public int updateByExample(T t, Object o) { return dao.updateByExample(t,o); } @Override public int updateByExampleSelective(T t, Object o) { return dao.updateByExampleSelective(t,o); } @Override public List<T> selectByExampleAndRowBounds(Object o, RowBounds rowBounds) { // if (rows>0){ // PageHelper.startPage(page,rows); // } List<T> list = dao.selectByExampleAndRowBounds(o,rowBounds); // this.rows = 0; return list; } @Override public List<T> selectByRowBounds(T t, RowBounds rowBounds) { // if (rows>0){ // PageHelper.startPage(page,rows); // } List<T> list = dao.selectByRowBounds(t,rowBounds); // this.rows = 0; return list; } @Override public int insertList(List<? extends T> list) { int result = 0; for (T t : list) { result += dao.insertSelective(t); } return result; } @Override public int insertUseGeneratedKeys(T t) { return dao.insertUseGeneratedKeys(t); } @Override public BaseServiceImpl<T> page(int page,int rows) { // this.page = page; // this.rows = rows; if (rows>0 && page>0) PageHelper.startPage(page,rows); return this; } @Override public int total(){ return this.selectCount(null); } }
七、User 持久化对象
package club.xcreeper.generalmybatis.domain.po; import lombok.Data; import javax.persistence.Id; import java.io.Serializable; import java.util.Date; @Data public class User implements Serializable { @Id private Long id; private String username; private String password; private Date createDateTime; private Date updateDateTime; }
八、UserDao
package club.xcreeper.generalmybatis.dao; import club.xcreeper.generalmybatis.core.dao.BaseDao; import club.xcreeper.generalmybatis.domain.po.User; import org.springframework.stereotype.Component; @Component public interface UserDao extends BaseDao<User> { }
九、UserService
package club.xcreeper.generalmybatis.service; import club.xcreeper.generalmybatis.core.service.BaseService; import club.xcreeper.generalmybatis.domain.po.User; public interface UserService extends BaseService<User> { }
十、UserServiceImpl
package club.xcreeper.generalmybatis.service.impl; import club.xcreeper.generalmybatis.core.service.impl.BaseServiceImpl; import club.xcreeper.generalmybatis.dao.UserDao; import club.xcreeper.generalmybatis.domain.po.User; import club.xcreeper.generalmybatis.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class UserServiceImpl extends BaseServiceImpl<User> implements UserService { @Autowired public void setUserDao(UserDao userDao) { super.setBaseDao(userDao); } }
十一、Application
package club.xcreeper.generalmybatis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import tk.mybatis.spring.annotation.MapperScan; @SpringBootApplication @MapperScan("club.xcreeper.generalmybatis.dao") public class GeneralMybatisApplication { public static void main(String[] args) { SpringApplication.run(GeneralMybatisApplication.class, args); } }
十二、Test
package club.xcreeper.generalmybatis; import club.xcreeper.generalmybatis.domain.po.User; import club.xcreeper.generalmybatis.service.UserService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import tk.mybatis.mapper.entity.Example; import java.util.ArrayList; import java.util.Date; import java.util.List; @SpringBootTest @RunWith(SpringRunner.class) public class GeneralMybatisApplicationTests { @Autowired private UserService userService; @Autowired private ObjectMapper objectMapper; @Test public void contextLoads() { } @Test public void insertSelective(){ User user = new User(); user.setId(System.currentTimeMillis()); user.setUsername("张三"); user.setPassword("123"); Date date = new Date(); user.setCreateDateTime(date); user.setUpdateDateTime(date); userService.insertSelective(user); } @Test public void insertList(){ List<User> userList = new ArrayList<>(); for (int i = 0; i < 10; i++) { User user = new User(); user.setId(System.currentTimeMillis()+i); user.setUsername(i+""+i); user.setPassword("abc"+i+i); Date date = new Date(); user.setCreateDateTime(date); user.setUpdateDateTime(date); userList.add(user); } userService.insertList(userList); } @Test public void updateByExampleSelective(){ Example example = new Example(User.class); example.createCriteria().andEqualTo("username","张三"); User user = new User(); user.setPassword("456"); userService.updateByExampleSelective(user,example); } @Test public void updateByPrimaryKeySelective(){ User user = new User(); user.setId(1571807197078L); user.setPassword("789"); userService.updateByPrimaryKeySelective(user); } @Test public void select() throws JsonProcessingException { User user = new User(); // user.setId(1571812813795L); // user.setPassword("abc11"); user.setUsername("22"); System.out.println(objectMapper.writeValueAsString(userService.select(user))); } @Test public void selectPage() throws JsonProcessingException { // User user = new User(); //// user.setId(1571812813795L); //// user.setPassword("abc11"); // user.setUsername("22"); System.out.println(objectMapper.writeValueAsString(userService.page(0,3).selectAll())); System.out.println(userService.total()); } }