栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot整合tk-mybatis框架搭建

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot整合tk-mybatis框架搭建

项目结构截图放在文末了,图片太大怕影响观看体验,想模仿搭建项目的可以拉到底看下截图再动手不迟。 第一步:依赖

        UTF-8
        UTF-8
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        

        
        
            mysql
            mysql-connector-java
            runtime
        

        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            tk.mybatis
            mapper-spring-boot-starter
            2.1.5
        
        
        
            com.alibaba
            druid
            1.1.3
        
        
        
            org.projectlombok
            lombok
        
    
第二步:配置数据库信息,开启执行SQL打印
server:
  port: 6677
spring:
  #数据源配置
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource #Druid连接池
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root  #数据库用户名
    password: 123456  #数据库密码
    driver-class-name: com.mysql.cj.jdbc.Driver #mysql驱动
    initialSize: 10 #初始化连接池大小
    minIdle: 10 #初始化最小连接池数量
    maxActive: 100 #初始化最大连接池数量
    maxWait: 6000 #配置获取连接等待超时的时间
    timeBetweenEvictionRunsMills: 6000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    minEvictableIdleTimeMillis: 30000 #配置一个连接在池中最小生存的时间,单位是毫秒
    validationQuery: SELECt 'x' #测试连接

#tk-mybatis执行数据库操作的时候打印SQL日志(debug前面的key是mapper文件的包名,一定不能写错,否则打印不出日志)
logging:
  level:
    com.slm.tkmybatis.project.dao: debug
mybatis:
  mapper-locations: classpath:/mapper
@Configuration
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class MapperScannerConfig {
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        //mapper类的包名--即操作数据库的对应到数据表的Mapper.java类的包名
        mapperScannerConfigurer.setbasePackage("com.slm.tkmybatis.project.dao");
        Properties properties = new Properties();
        properties.setProperty("mappers", baseMapper.class.getName());
        properties.setProperty("notEmpty","false");
        properties.setProperty("IDENTITY", "MYSQL");
        properties.setProperty("ORDER","BEFORE");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }
}

②基础删除功能mapper

public interface DeleteMapper extends Marker,
        tk.mybatis.mapper.common.base.delete.DeleteMapper,
        DeleteByPrimaryKeyMapper,
        DeleteByConditionMapper,
        DeleteByIdsMapper{
}

③基础新增功能mapper

public interface InsertMapper extends Marker,
        tk.mybatis.mapper.common.base.baseInsertMapper,
        InsertSelectiveMapper,
        MySqlMapper{
}

④基础查询功能mapper

public interface SelectMapper extends Marker,
        SelectOneMapper,
        tk.mybatis.mapper.common.base.select.SelectMapper,
        SelectAllMapper,
        SelectCountMapper,
        SelectByPrimaryKeyMapper,
        ExistsWithPrimaryKeyMapper,
        SelectByIdsMapper,
        SelectByConditionMapper,
        SelectCountByConditionMapper,
        SelectByExampleMapper
{
}

⑤基础修改功能mapper

public interface UpdateMapper extends Marker,
        UpdateByPrimaryKeyMapper,
        UpdateByPrimaryKeySelectiveMapper,
        UpdateByConditionMapper,
        UpdateByConditionSelectiveMapper,
        UpdateByExampleSelectiveMapper {
}

⑥基础增删改查功能mapper

public interface baseMapper extends InsertMapper,DeleteMapper,UpdateMapper,SelectMapper, ConditionMapper, IdsMapper, ExampleMapper, InsertListMapper{
}

第四步:创建业务mapper(这里只是创建业务mapper,先不写具体接口,继承baseMapper后就可以使用baseMapper的基础方法了)
@Mapper
public interface UserMapper extends baseMapper {

}
第五步:创建实体类
@Data
@Table(name="user")
public class User implements Serializable {
    //在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常。
    private static final long serialVersionUID = 190783327737397579L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY,generator = "JDBC")
    private Integer id;
    @Column
    private String userName;
    @Column
    private String userPhone;

}
第六步:创建controller
@RestController
@RequestMapping("tk")
public class TKMybatisController {
    @Resource
    UserMapper userMapper;


    @GetMapping("getUser")
    public Map getUser(){
        Map result = new HashMap<>();
        //selectByPrimaryKey是框baseMapper中的方法,我并没有在mapper中写这个方法
        User user = userMapper.selectByPrimaryKey(1);
        result.put("code",200);
        result.put("data",user);
        return result;
    }
}

数据库脚本

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `user_phone` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `user_name_index`(`user_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '比比东', '123456');
INSERT INTO `user` VALUES (2, '千仞雪', '123456');
第七步:测试

第八步:三种 写法 ①调用baseMapper基础方法
User user = userMapper.selectByPrimaryKey(1);

在上面的测试接口getUser中我用基础mapper中的selectByPrimaryKey写了个接口

②xml文件中写原生SQL(mapper.xml和mapper.java文件分别在哪个路径下创建不知道的可以拉到文末看截图)

mapper接口==(文件名:UserMapper.java)==

@Mapper
public interface UserMapper extends baseMapper {

   User selectById(@Param("id") Integer id);
   
}

mapper.xml (文件名:UserMapper.xml)