下面我会详细讲解使用SpringBoot开发Restful服务实现增删改查功能的完整攻略。这个过程可以通过如下步骤实现:
1. 准备工作
在开始本次攻略之前,需要准备如下工具和环境:
- JDK 1.8 或更高版本
- Maven 3.0 或更高版本
- SpringBoot 2.0 或更高版本
2. 创建一个SpringBoot项目
首先,我们需要用Maven创建一个SpringBoot项目,可以通过如下命令行创建:
mvn archetype:generate -DgroupId=com.example -DartifactId=demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
执行完以上命令后,即可创建出一个简单的Maven项目。之后,在pom.xml
文件中添加SpringBoot的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.2</version>
</dependency>
3. 实现增删改查功能
为了实现增删改查功能,我们需要进行如下步骤:
3.1 定义实体类
在项目中创建一个实体类,用于表示需要进行增删改查的数据。例如,定义一个表示学生的实体类:
public class Student {
private Long id;
private String name;
private Integer age;
// 省略 getter 和 setter 方法
}
3.2 创建持久层接口
创建一个持久层接口,用于对数据库进行CRUD操作。例如,定义一个用于对学生数据进行操作的持久层接口:
public interface StudentMapper {
List<Student> findAll();
Student findById(Long id);
int save(Student student);
int update(Student student);
int deleteById(Long id);
}
3.3 实现持久层接口
实现上一步中定义的持久层接口,具体实现可以选择使用MyBatis等框架。以下是一个基于MyBatis的实现示例:
@Repository
public class StudentMapperImpl implements StudentMapper {
private final SqlSessionFactory sqlSessionFactory;
@Autowired
public StudentMapperImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public List<Student> findAll() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
return sqlSession.selectList("com.example.demo.mapper.StudentMapper.findAll");
}
}
@Override
public Student findById(Long id) {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
return sqlSession.selectOne("com.example.demo.mapper.StudentMapper.findById", id);
}
}
@Override
public int save(Student student) {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
return sqlSession.insert("com.example.demo.mapper.StudentMapper.save", student);
}
}
@Override
public int update(Student student) {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
return sqlSession.update("com.example.demo.mapper.StudentMapper.update", student);
}
}
@Override
public int deleteById(Long id) {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
return sqlSession.delete("com.example.demo.mapper.StudentMapper.deleteById", id);
}
}
}
3.4 创建控制器
创建一个控制器,用于接收HTTP请求并调用持久层接口对数据进行CRUD操作。例如,定义一个用于操作学生数据的控制器:
@RestController
@RequestMapping("/api/students")
public class StudentController {
private final StudentMapper studentMapper;
@Autowired
public StudentController(StudentMapper studentMapper) {
this.studentMapper = studentMapper;
}
@GetMapping("")
public List<Student> findAll() {
return studentMapper.findAll();
}
@GetMapping("/{id}")
public Student findById(@PathVariable("id") Long id) {
return studentMapper.findById(id);
}
@PostMapping("")
public int save(@RequestBody Student student) {
return studentMapper.save(student);
}
@PutMapping("/{id}")
public int update(@PathVariable("id") Long id,
@RequestBody Student student) {
student.setId(id);
return studentMapper.update(student);
}
@DeleteMapping("/{id}")
public int deleteById(@PathVariable("id") Long id) {
return studentMapper.deleteById(id);
}
}
在上例中,@RestController
和@RequestMapping
都是SpringMVC中使用的注解,用于定义一个处理HTTP请求的Controller。@PostMapping
、@PutMapping
和@DeleteMapping
等注解用于定义相应的HTTP请求方法,这些方法分别对应HTTP中的POST、PUT和DELETE方法。@RequestBody
注解用于接收请求体中的数据。
3.5 运行程序
在完成以上操作之后,就可以运行程序并进行测试了。例如,使用curl
命令对新增学生数据进行添加:
curl -d '{"name":"张三", "age": 18}' -H 'Content-Type: application/json' http://localhost:8080/api/students
使用curl
命令对查询所有学生数据:
curl http://localhost:8080/api/students
4. 示例
以上是SpringBoot开发Restful服务实现增删改查功能的完整攻略,本节提供两个示例,Student
实体类和StudentMapper
持久层接口的实现如下:
示例1:使用JdbcTemplate实现
@Component
public class JdbcTemplateStudentMapper implements StudentMapper {
private final JdbcTemplate jdbcTemplate;
public JdbcTemplateStudentMapper(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public List<Student> findAll() {
String sql = "select * from student";
return jdbcTemplate.query(sql, new StudentRowMapper());
}
@Override
public Student findById(Long id) {
String sql = "select * from student where id=?";
return jdbcTemplate.queryForObject(sql, new Object[]{id}, new StudentRowMapper());
}
@Override
public int save(Student student) {
String sql = "insert into student(name, age) values(?, ?)";
return jdbcTemplate.update(sql, student.getName(), student.getAge());
}
@Override
public int update(Student student) {
String sql = "update student set name=?, age=? where id=?";
return jdbcTemplate.update(sql, student.getName(), student.getAge(), student.getId());
}
@Override
public int deleteById(Long id) {
String sql = "delete from student where id=?";
return jdbcTemplate.update(sql, id);
}
}
class StudentRowMapper implements RowMapper<Student> {
@Override
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
Student student = new Student();
student.setId(resultSet.getLong("id"));
student.setName(resultSet.getString("name"));
student.setAge(resultSet.getInt("age"));
return student;
}
}
示例2:使用Mybatis实现
<!-- student.xml -->
<mapper namespace="com.example.demo.mapper.StudentMapper">
<select id="findAll" resultType="com.example.demo.entity.Student">
SELECT * FROM student
</select>
<select id="findById" parameterType="java.lang.Long" resultType="com.example.demo.entity.Student">
SELECT * FROM student WHERE id = #{id}
</select>
<insert id="save" parameterType="com.example.demo.entity.Student">
INSERT INTO student (name, age)
VALUES(#{name}, #{age})
</insert>
<update id="update" parameterType="com.example.demo.entity.Student">
UPDATE student SET name=#{name}, age=#{age}
WHERE id=#{id}
</update>
<delete id="deleteById" parameterType="java.lang.Long">
DELETE FROM student WHERE id=#{id}
</delete>
</mapper>
@Repository
public class MybatisStudentMapper implements StudentMapper {
private final SqlSessionTemplate sqlSessionTemplate;
public MybatisStudentMapper(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<Student> findAll() {
return sqlSessionTemplate.selectList("com.example.demo.mapper.StudentMapper.findAll");
}
@Override
public Student findById(Long id) {
return sqlSessionTemplate.selectOne("com.example.demo.mapper.StudentMapper.findById", id);
}
@Override
public int save(Student student) {
return sqlSessionTemplate.insert("com.example.demo.mapper.StudentMapper.save", student);
}
@Override
public int update(Student student) {
return sqlSessionTemplate.update("com.example.demo.mapper.StudentMapper.update", student);
}
@Override
public int deleteById(Long id) {
return sqlSessionTemplate.delete("com.example.demo.mapper.StudentMapper.deleteById", id);
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:使用SpringBoot开发Restful服务实现增删改查功能 - Python技术站