1,首先在pom文件中加入spring boot的父依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.15</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
注意Java的版本与spring boot版本兼容,这里使用java8
2,引入web和数据库驱动
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
yml配置
server:
port: 8006
spring:
application:
name: project
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/booklib?useUnicode=true&characterEncoding=UTF-8
username: root
password: root
mybatis:
mapper-locations: classpath:mapper/*.xml
添加注解
@SpringBootApplication
@MapperScan(basePackages = "com.nisha.project.dao") //扫描mapper对应的dao层
public class ProjectApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectApplication.class, args);
}
}
添加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.nisha.project.dao.CommodityDao" >
<insert id="add" parameterType="com.nisha.project.pojo.Commodity">
insert into commodity (name)
values (#{name})
</insert>
<insert id="addBatch" parameterType="com.nisha.project.pojo.Commodity">
insert into commodity (name) values
<foreach collection="list" index="index" item="item" separator=",">
(#{item.name})
</foreach>
</insert>
<select id="queryAll" resultType="com.nisha.project.pojo.Commodity">
select * from commodity
</select>
</mapper>
引入分页插件
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
分页查询
public PageInfo<Commodity> queryAll(int page, int pageSize) {
PageHelper.startPage(page, pageSize);
List<Commodity> result = commodityDao.queryAll();
return new PageInfo<>(result);
}