上一篇是简单配置了一下SpringBoot前端的页面的支持,现在看看后端服务器与数据库的交互。
首先,没的说,一定是jar引入和数据源设置,这里使用的是Hikari连接工具,有兴趣的用户可以自行百度看看
maven:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<!-- 版本号可以不用指定,Spring Boot会选用合适的版本 -->
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
application.properties:
#数据库连接信息
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
然后创建目录结构
注意一下,xml的映射文件需要放在resource目录下才能被识别
在启动类中加上mapper所在的包扫描注解
创建实体类Demo.java
package com.example.demo.entry;
public class Demo {
private Long id;
private String name;
private String des;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
}
实体类对应的表格和数据也应被创建
创建Dao层Mapper接口
package com.example.demo.mapper;
import com.example.demo.entry.Demo;
public interface TestMapper {
Demo getOne(Long id);
}
application.properties中设置xml目录地址
#Mybatis Mapper映射文件地址
mybatis.mapper-locations=classpath:mapXml/*.xml
创建Mapper对应的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="com.example.demo.mapper.TestMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entry.Demo" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="des" property="des" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, name, des
</sql>
<select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM demo
WHERE id = #{id}
</select>
</mapper>
最后,创建一个Controller测试方法查看测试结果