开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 3 天,点击查看活动详情
1.如何使用TKMybatis
经过上两篇文章,我们大致的介绍了 TKmybatis的配置如何与spring boot项目使用配置 我们也能够使用generator来简化SQL操作了,通过generator我们可以生成Mapper文件,xml文件及UserInfoPO文件 今天我们开始 实战,介绍具体的操作
1.1 启动项目
首先我们要启动项目,application-properteis 中还缺少一部分配置Druid数据库连接池的信息 application-properties 配置druid配置
server.port=8800
#Druid db链接配置
# 数据库地址
spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
# 数据库用户名
spring.datasource.druid.username=root
# 数据库密码
spring.datasource.druid.password=xxx
# 数据库连接池最大值
spring.datasource.druid.max-active=20
# 数据库连接池初始值
spring.datasource.druid.initial-size=5
# 数据库连接池最小空闲值
spring.datasource.druid.min-idle=5
# 池中空闲连接大于minIdle且连接空闲时间大于该值,则关闭该连接,单位毫秒(5分钟,默认30分钟)
spring.datasource.druid.min-evictable-idle-time-millis=300000
# 获取连接时最大等待时间,单位毫秒(1分钟)
spring.datasource.druid.max-wait=60000
# 检测连接是否有效时执行的sql命令
spring.datasource.druid.validation-query=select 1
# 借用连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
spring.datasource.druid.test-on-borrow=false
# 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
spring.datasource.druid.test-on-return=false
# 连接空闲时检测,如果连接空闲时间大于timeBetweenEvictionRunsMillis指定的毫秒,执行validationQuery指定的SQL来检测连接是否有效
spring.datasource.druid.test-while-idle=true
# 空闲连接检查、废弃连接清理、空闲连接池大小调整的操作时间间隔,单位是毫秒(1分钟)
spring.datasource.druid.time-between-eviction-runs-millis=60000
#开发环境打印 SQL日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
1.2 DataSourceConfiguration 配置注入spring管理
package com.jzj.tdmybatis.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfiguration {
@ConfigurationProperties(prefix = "spring.datasource.druid")
@Bean
public DataSource dataSource(){
return new DruidDataSource();
}
}
2.测试类信息
2.1 TestController 测试
用于 测试 db链接及mapper文件是否生效
package com.jzj.tdmybatis.controller;
import com.jzj.tdmybatis.service.IUserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @ClassName TestController
* @Description
* @Author jiazijie
* @Date 2023/2/2 22:05
*/
@RestController
public class TestController {
@Resource
private IUserService userService;
/**
* 探活接口
*/
@RequestMapping("/temp/ping")
@ResponseBody
public Object ping() {
return "pong";
}
/**
* 探活接口
*/
@RequestMapping("/temp/user")
@ResponseBody
public Object user(String id) {
return userService.getUser("11");
}
}
2.2 服务类Service 用户服务
接口
package com.jzj.tdmybatis.service;
import com.jzj.tdmybatis.domain.po.UserInfoPO;
import java.util.List;
public interface IUserService {
UserInfoPO getUser(String userid);
void insertUser(UserInfoPO userInfoPO);
void batchInsert(List<UserInfoPO> userInfoPOList);
void updateUser(UserInfoPO userInfoPO);
void batchUpdate(List<UserInfoPO> userInfoPOList);
void deleteUser(String userid);
}
实现类
package com.jzj.tdmybatis.service.impl;
import com.jzj.tdmybatis.domain.po.UserInfoPO;
import com.jzj.tdmybatis.repository.mapper.UserInfoMapper;
import com.jzj.tdmybatis.service.IUserService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.util.List;
/**
* @ClassName UserServiceImpl
* @Description
* @Author jiazijie
* @Date 2023/2/2 21:25
*/
@Service
public class UserServiceImpl implements IUserService {
@Resource
private UserInfoMapper mapper;
@Override
public UserInfoPO getUser(String userid) {
Example example = new Example(UserInfoPO.class);
Example.Criteria criteria = example.createCriteria();
//userPO 中有 companyId字段
criteria.andEqualTo("userId", userid);
return mapper.selectOneByExample(example);
}
@Override
public void insertUser(UserInfoPO userInfoPO) {
}
@Override
public void batchInsert(List<UserInfoPO> userInfoPOList) {
}
@Override
public void updateUser(UserInfoPO userInfoPO) {
}
@Override
public void batchUpdate(List<UserInfoPO> userInfoPOList) {
}
@Override
public void deleteUser(String userid) {
}
}
3.启动服务
3.1 application配置mapper包扫描
@SpringBootApplication
@MapperScan(basePackages="com.jzj.tdmybatis.repository.mapper")
public class TdmybatisApplication {
public static void main(String[] args) {
SpringApplication.run(TdmybatisApplication.class, args);
}
}
3.2 mysql准备数据
数据库插入测试数据
INSERT INTO `test`.`user_info` (`id`, `user_id`, `user_name`, `age`, `address`, `order_ids`, `goods`, `sort_order`, `is_del`, `addtime`, `modtime`) VALUES (1, '11', 'aa', 1, 'xxx', '[1, 2, 3]', '{\"deptId\": 2, \"deptName\": \"部门2\", \"deptLeaderId\": 4}', 0, 0, 0, 0);
INSERT INTO `test`.`user_info` (`id`, `user_id`, `user_name`, `age`, `address`, `order_ids`, `goods`, `sort_order`, `is_del`, `addtime`, `modtime`) VALUES (2, '22', 'bb', 2, 'xxx', '[4, 5, 6]', '{\"deptId\": 2, \"deptName\": \"部门2\", \"deptLeaderId\": 4}', 0, 0, 0, 0);
INSERT INTO `test`.`user_info` (`id`, `user_id`, `user_name`, `age`, `address`, `order_ids`, `goods`, `sort_order`, `is_del`, `addtime`, `modtime`) VALUES (3, '33', 'cc', 3, 'xxx', '[7, 5, 6]', '{\"deptId\": 2, \"deptName\": \"部门2\", \"deptLeaderId\": 4}', 0, 0, 0, 0);
INSERT INTO `test`.`user_info` (`id`, `user_id`, `user_name`, `age`, `address`, `order_ids`, `goods`, `sort_order`, `is_del`, `addtime`, `modtime`) VALUES (4, '44', 'dd', 4, 'xxx', '[8, 5, 6]', '{\"deptId\": 2, \"deptName\": \"部门2\", \"deptLeaderId\": 4}', 0, 0, 0, 0);
3.3 启动成功
日志信息 端口8800, 启动时长1.764 s
2023-02-03 23:23:30.138 INFO 17176 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8800 (http) with context path ''
2023-02-03 23:23:30.145 INFO 17176 --- [ main] com.jzj.tdmybatis.TdmybatisApplication : Started TdmybatisApplication in 1.764 seconds (JVM running for 2.486)
3.4 测试http请求CURL
curl 127.0.0.1:8800/temp/user
{"id":1,"userId":"11","userName":"aa","age":1,"address":"xxx","orderIds":"[1, 2, 3]","goods":"{"deptId": 2, "deptName": "部门2", "deptLeaderId": 4}","sortOrder":0,"isDel":0,"addtime":0,"modtime":0} 可以看到的确把db数据查询出来
4.启动报错 PageHelper的错误
springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration':
Invocation of init method failed;
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration':
Requested bean is currently in creation: Is there an unresolvable circular reference?
可以看出来是pagehelper出的问题, 我们只需要把Pom文件的 注释掉即可
<!-- <!–pagehelper–>-->
<!-- <dependency>-->
<!-- <groupId>com.github.pagehelper</groupId>-->
<!-- <artifactId>pagehelper-spring-boot-starter</artifactId>-->
<!-- <version>${pagehelper.version}</version>-->
<!-- </dependency>-->
我们现在已经启动成功,并且controller请求可以正常的 从db中查询出来 user信息