上一篇是通過Jdbc訪問資料庫,本篇來寫通過MyBatis資料訪問。
首先在pom.xml中加入MyBatis依賴。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
複製程式碼
可以不新增spring-boot-starter-jdbc。因為,mybatis-spring-boot-starter依賴中存在spring-boot-starter-jdbc。
mysql的依賴還是要在的,不然怎麼連線資料庫呢。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.14</version>
</dependency>
複製程式碼
修改resource下的application.properties
## 資料來源配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
## Mybatis 配置
mybatis.typeAliasesPackage=org.spring.springboot.domain
mybatis.mapperLocations=classpath:mapper/*.xml
複製程式碼
結構圖
在MySQL中建立City表,並在src/domain/下建立City實體類
public class City {
private Long id;
private Long provinceId;
private String cityName;
private String description;
// 省略getter和setter
}
複製程式碼
在resource中建立mapper資料夾,在mapper資料夾下建立CityMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="org.spring.springboot.dao.CityDao">
<resultMap id="BaseResultMap" type="org.spring.springboot.domain.City">
<result column="id" property="id" />
<result column="province_id" property="provinceId" />
<result column="city_name" property="cityName" />
<result column="description" property="description" />
</resultMap>
<parameterMap id="City" type="org.spring.springboot.domain.City"/>
<sql id="Base_Column_List">
id, province_id, city_name, description
</sql>
<select id="findByName" resultMap="BaseResultMap" parameterType="java.lang.String">
select
<include refid="Base_Column_List" />
from city
where city_name = #{cityName}
</select>
</mapper>
複製程式碼
Controller層
@RestController
public class CityRestController {
@Autowired
private CityService cityService;
@RequestMapping(value = "/api/city", method = RequestMethod.GET)
public City findOneCity(@RequestParam(value = "cityName", required = true) String cityName) {
return cityService.findCityByName(cityName);
}
}
複製程式碼
Service層
/**
* 城市業務邏輯介面類
*/
public interface CityService {
/**
* 根據城市名稱,查詢城市資訊
* @param cityName
*/
City findCityByName(String cityName);
}
/**
* 城市業務邏輯實現類
*/
@Service
public class CityServiceImpl implements CityService {
@Autowired
private CityDao cityDao;
@Override
public City findCityByName(String cityName) {
return cityDao.findByName(cityName);
}
}
複製程式碼
Dao層
/**
* 城市 DAO 介面類
*/
@Component
public interface CityDao {
/**
* 根據城市名稱,查詢城市資訊
*
* @param cityName 城市名
*/
City findByName(@Param("cityName") String cityName);
}
複製程式碼
全部搞定後,執行專案,並在postman中測試介面即可。