文章说明
在java编码过程中变量属性一般使用驼峰命名如
实体类属性:groupId
数据库表列:group_id
mybatis默认是属性名和数据库字段名一一对应的,即
数据库表列:group_id
实体类属性:group_id
两者有差别,在不加处理情况下,不对应字段查询时会为null,
在以前人们通常会写一大段代码来构建这种映射关系
@Results(id="id",
value = {
@Result(property = "groupId", column = "group_id", id = true),
@Result(property = "userName", column = "user_name"),
})
这样虽然会解决问题,但是无疑增加了代码量,下面会为大家介绍一种简便快捷的方式,来解决上述问题
maven引入依赖包
com.alibaba
druid-spring-boot-starter
1.1.10
mysql
mysql-connector-java
runtime
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.1
springboot链接mysql数据库
spring:
# datasource:
# driver-class-name: com.mysql.cj.jdbc.Driver
# url: jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=UTC
# username: root
# password: root
# hikari:
# minimum-idle: 5
# # 连接池最大连接数,默认是10
# maximum-pool-size: 10
# # 空闲连接存活最大时间,默认600000(10分钟)
# idle-timeout: 600000
# # 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
# max-lifetime: 1800000
# # 数据库连接超时时间,默认30秒,即30000
# connection-timeout: 30000
java代码实体类驼峰式命名,数据库表字段以“_”分割,查询语句映射出问题解决
在yml文件中加入如下代码
mybatis:
configuration:
map-underscore-to-camel-case: true
Mapper层代码
@Mapper
public interface SMapper {
@Insert("insert into s(zname, z) values(#{zName}, #{z})")
int insertStation(Station station);
@Select("select * from s")
List selectAll();
}
Service层代码
package com.service;
public interface SService {
boolean isInsertS(S s);
List selectAllS();
}
package com.service.impl;
import java.util.List;
@Service
public class SServiceImpl implements SService {
@Autowired
private SMapper sMapper;
@Override
public boolean isInsertStationSucc(S s) {
return sMapper.insertStation(s);
}
@Override
public List selectAllS() {
List sList = sMapper.selectAll();
return sList;
}
}
Controller层代码
package com.controller;
@RestController
@RequestMapping(value = "/api", produces = {"application/json;charset=UTF-8"}) //中文乱码
@CrossOrigin //跨域
public class StationController {
@Autowired
private SService sService;
@PostMapping("/selectAll")
public List selectAllS(@RequestBody String json) {
List sList = new ArrayList<>();
try {
sList = sService.selectAll();
} catch (Exception e) {
return sList;
}
return sList;
}
}