SpringBoot 整合tk.mybatis连接MySQL数据库

一、基本依赖导入

<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<optional>true</optional>
	</dependency>
	<!-- MySQl -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
	</dependency>
	<!-- tk.mybatis -->
	<dependency>
		<groupId>tk.mybatis</groupId>
		<artifactId>mapper-spring-boot-starter</artifactId>
		<version>1.1.2</version>
	</dependency>

配置数据库连接

spring:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/database_name?autoReconnect=true&useUnicode=true&allowMultiQueries=true&characterEncoding=utf-8
    username: xxx
    password: xxxxxx
# 控制台打印日志 com.example.demo.mapper根据自己项目修改
logging:
  level:
    com.example.demo.mapper: DEBUG

三、根据表名创建实体类

实体类根据数据库表字段进行定义
数据库表结构

在这里插入图片描述
实体类

@Table(name = "t_income_expenditure")// 表名
@Data
public class RevenueAndExpenditure {

    private String id;

    private Date daytime;

    private String incometype;

    private String incomesubtype;

    private float incomenum;

    private String expendituretype;

    private String expendituresubtype;

    private float expenditurenum;
}

四、编写mapper

public interface RevenueAndExpenditureMapper extends Mapper<RevenueAndExpenditure> {
}

继承Mapper,Mapper有很多封装好的常用数据库操作方法,例如:
在这里插入图片描述

五、启动类上添加mapper扫描

@MapperScan(basePackages={"com.example.demo.mapper"})

六、编写测试方法

	// 以查询数量为例
	@Autowired
    RevenueAndExpenditureMapper revenueAndExpenditureMapper;
	public int test(){
	     RevenueAndExpenditure revenueAndExpenditure = new RevenueAndExpenditure();
	     revenueAndExpenditure.setId("1");
	     return revenueAndExpenditureMapper.selectCount(revenueAndExpenditure);
	}

七、控制台打印SQL

在这里插入图片描述
虽然参数中的对象只设置了id,但是SQL中依然有incomenum和expenditurenum, 是因为这两个字段是float类型,默认值为0.0,所以在判断是否拼接成查询条件的时候拼接上去了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值