💥 该系列属于【SpringBoot基础】专栏,如您需查看其他SpringBoot相关文章,请您点击左边的连接
目录
一、项目准备
1. 导入依赖
<dependencies>
<!-- Spring Boot的Web起步依赖,提供Spring MVC和Tomcat的集成 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot的测试起步依赖,用于编写和运行单元测试和集成测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <!-- 依赖的作用域仅限于测试,不会被打包到最终的构件中 -->
</dependency>
<!-- MyBatis的Spring Boot起步依赖,用于整合MyBatis框架 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version> <!-- 指定依赖的版本号 -->
</dependency>
<!-- MySQL数据库的JDBC驱动依赖,用于连接MySQL数据库 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope> <!-- 依赖的作用域为运行时,表示该依赖在运行期需要,但编译期不需要 -->
</dependency>
<!-- PageHelper分页插件,用于分页查询 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.2</version>
</dependency>
</dependencies>
2. 修改配置文件
server.port=8080
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=your_password
#mapper配置文件
mybatis.mapper-locations=classpath:mapper/*.xml
3. 数据库
4. 项目结构
5. 初始文件
(1)pojo
public class Person {
private int id;
private String name;
private int age;
// 省略构造函数,getter和setter,以及toString
}
(2)controller
@RestController
public class PersonController {
@Autowired
private PersonService personService;
}
(3)service
接口
public interface PersonService {
}
实体类
@Service
public class PersonServiceImpl implements PersonService {
@Autowired
private PersonMapper personMapper;
}
(4)mapper
@Mapper
public interface PersonMapper {
}
(5)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.mapper.PersonMapper">
</mapper>
(6)Result
public class Result<T> implements Serializable {
private Integer code;
private String msg;
private T data;
public static <T> Result<T> success() {
Result<T> result = new Result<>();
result.code = 1;
return result;
}
public static <T> Result<T> success(T data) {
Result<T> result = new Result<>();
result.code = 1;
result.data = data;
return result;
}
public static <T> Result<T> error(String msg) {
Result<T> result = new Result<>();
result.code = 0;
result.msg = msg;
return result;
}
//省略getter和setter
}
(7)PageResult
public class PageResult implements Serializable {
private long total; //总记录数
private List records; //当前页数据集合
// 省略有参构造、无参构造、getter和setter
}
二、基本操作
1. 增加用户
(1)controller
@RequestMapping("/add")
public Result add(Person person) {
personService.add(person);
return Result.success();
}
(2)service
void add(Person person);
@Override
public void add(Person person) {
personMapper.add(person);
}
(3)mapper
@Insert("INSERT INTO person VALUES (#{id},#{name},#{age})")
void add(Person person);
(4)测试
2. 根据id删除用户
由于controller,service代码与之前类似,这里开始仅仅展示mapper。
(1)Mapper
@Delete("DELETE FROM person WHERE id = #{id}")
void deleteById(int id);
(2)测试
3. 根据id查询用户
(1)controller
@RequestMapping("/findPerson")
public Result<Person> findPersonById(int id) {
Person person = personService.findPersonById(id);
return Result.success(person);
}
(2)service
Person findPersonById(int id);
@Override
public Person findPersonById(int id) {
return personMapper.findPersonById(id);
}
(3)mapper
@Select("SELECT * FROM person WHERE id = #{id}")
Person findPersonById(int id);
(4)测试
4. 根据id修改用户
(1)controller
@RequestMapping("/updatePerson")
public Result update(Person person) {
personService.updatePerson(person);
return Result.success();
}
(2)service
void updatePerson(Person person);
@Override
public void updatePerson(Person person) {
personMapper.updatePerson(person);
}
(3)mapper
@Update("UPDATE person SET name = #{name}, age = #{age} WHERE id =#{id}")
void updatePerson(Person person);
(4)测试
5. 条件查询
新增数据库:
(1)controller
@RequestMapping("/findPersonByNameAge")
public Result<List<Person>> findPersonByNameAge(String name, Integer age) {
List<Person> list = personService.findPersonByNameAge(name, age);
return Result.success(list);
}
(2)service
List<Person> findPersonByNameAge(String name, Integer age);
@Override
public List<Person> findPersonByNameAge(String name, Integer age) {
return personMapper.findPersonByNameAge(name,age);
}
(3)mapper
@Param注解要加上,否则会报错,MyBatis可能没有识别传入的两个参数。
查找名字带有name,且年龄小于age的Person
@Select("SELECT * FROM person WHERE name LIKE CONCAT('%',#{name},'%') AND age < #{age}")
List<Person> findPersonByNameAge(@Param(value = "name") String name, @Param(value = "age") Integer age);
(4)接口测试
6. 动态查询——<where><if>
(0)xml中的特殊字符
特殊字符 替代符号
& &
< <
> >
" "
' '
a<=b a <= b
a>=b a >= b
a!=b a <![CDATA[ <> ]]>b a <![CDATA[!= ]]>b
(1)mapper
List<Person> findPersonDynamically(@Param(value = "name") String name, @Param(value = "age") Integer age);
(2)mapper/*.xml
注意要添加"AND"
<select id="findPersonDynamically" resultType="com.example.pojo.Person">
SELECT * FROM person
<where>
<if test="age != null">AND age < #{age}</if>
<if test="name != null">AND name LIKE CONCAT('%',#{name},'%')</if>
</where>
</select>
(3)接口测试
7. 动态更新——<set><if>
(1)mapper
void updatePersonDynamically(Person person);
(2)mapper/*.xml
注意要添加",",在Java中,int
类型的字段默认值是0,而不是null
。
<update id="updatePersonDynamically">
UPDATE person
<set>
<if test="age != null and age != 0">age = #{age},</if>
<if test="name != null">name = #{name},</if>
</set>
WHERE id = #{id}
</update>
(3)接口测试
仅仅修改姓名
仅仅修改年龄
同时修改姓名和年龄
8. 根据id批量删除——<foreach>
(1)controller
@RequestMapping("/deleteBatchPerson/{ids}")
public Result deleteBatchPerson(@PathVariable List<Integer> ids) {
personService.deleteBatchPerson(ids);
return Result.success();
}
(2)service
void deleteBatchPerson(List<Integer> ids);
@Override
public void deleteBatchPerson(List<Integer> ids) {
personMapper.deleteBatchPerson(ids);
}
(3)mapper
void deleteBatchPerson(@Param(value = "ids") List<Integer> ids);
(4)mapper/*.xml
<delete id="deleteBatchPerson">
DELETE FROM person
WHERE id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
(5)接口测试
9. 分页查询
pom.xml中导入分页查询插件依赖,见第一节1导入依赖。
pageBean类,见第一节5初始文件。
(1)controller
@RequestMapping("/pageQuery")
public Result<PageResult> pageQuery(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "3") Integer pageSize) {
PageResult pageResult = personService.pageQuery(page, pageSize);
return Result.success(pageResult);
}
(2)service
PageResult pageQuery(Integer page, Integer pageSize);
@Override
public PageResult pageQuery(Integer page, Integer pageSize) {
//设置分页参数
PageHelper.startPage(page, pageSize);
List<Person> list = personMapper.findAllPerson(); //查找所有人的信息
Page<Person> p = (Page<Person>) list;
PageResult pageResult = new PageResult(p.getTotal(), p.getResult());
return pageResult;
}
(3)mapper
List<Person> findAllPerson();
(4)mapper/*.xml
<select id="findAllPerson" resultType="com.example.pojo.Person">
SELECT * FROM person
</select>
(5)接口测试
要查询的数据库表单:
10. 条件分页查询
(1)controller
@RequestMapping("/pageQueryByNameAge")
public Result<PageResult> pageQueryByNameAge(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "3") Integer pageSize,
String name,
Integer age) {
PageResult pageResult = personService.pageQueryByNameAge(page, pageSize, name, age);
return Result.success(pageResult);
}
(2)service
PageResult pageQueryByNameAge(Integer page, Integer pageSize, String name, Integer age);
@Override
public PageResult pageQueryByNameAge(Integer page, Integer pageSize, String name, Integer age) {
PageHelper.startPage(page, pageSize);
List<Person> list = personMapper.findlist(name, age); //查找所有符合条件的人的信息
Page<Person> p = (Page<Person>) list;
PageResult pageResult = new PageResult(p.getTotal(), p.getResult());
return pageResult;
}
(3)mapper
List<Person> findlist(@Param(value = "name") String name, @Param(value = "age") Integer age);
(4)mapper/*.xml
<select id="findlist" resultType="com.example.pojo.Person">
SELECT * FROM person
<where>
<if test="name!=null">
AND name = #{name}
</if>
<if test="age!=null and age!=0">
AND age < #{age}
</if>
</where>
</select>
(5)接口测试
要查询的数据库表单: