spring boot 实现怎删改查
在Spring Boot中实现简单的CRUD(创建、读取、更新、删除)操作,你可以使用Spring Data JPA。以下是一个简单的例子:
- 添加依赖到你的
pom.xml
:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 创建一个实体类(Entity):
import javax.persistence.*;
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// 省略getter和setter方法
}
- 创建一个继承
JpaRepository
的接口:
import org.springframework.data.jpa.repository.JpaRepository;
public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {
}
- 创建一个服务类(Service):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MyEntityService {
@Autowired
private MyEntityRepository repository;
public List<MyEntity> findAll() {
return repository.findAll();
}
public MyEntity save(MyEntity entity) {
return repository.save(entity);
}
public MyEntity findById(Long id) {
return repository.findById(id).orElse(null);
}
public void deleteById(Long id) {
repository.deleteById(id);
}
public MyEntity update(MyEntity entity) {
return repository.save(entity);
}
}
- 创建一个控制器类(Controller):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/myentities")
public class MyEntityController {
@Autowired
private MyEntityService service;
@GetMapping
public List<MyEntity> getAll() {
return service.findAll();
}
@PostMapping
public MyEntity create(@RequestBody MyEntity entity) {
return service.save(entity);
}
@GetMap
评论已关闭