在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"),
})
這樣雖然會解決問題,可是無疑增長了代碼量,下面會爲你們介紹一種簡便快捷的方式,來解決上述問題
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
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
public interface SMapper {
@Insert("insert into s(zname, z) values(#{zName}, #{z})")
int insertStation(Station station);
@Select("select * from s")
List<S> selectAll();
}
package com.service;
public interface SService {
boolean isInsertS(S s);
List<S> 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<S> selectAllS() {
List<Station> sList = sMapper.selectAll();
return sList;
}
}
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<S> selectAllS(@RequestBody String json) {
List<S> sList = new ArrayList<>();
try {
sList = sService.selectAll();
} catch (Exception e) {
return sList;
}
return sList;
}
}