1 添加依赖
在项目的构建工具(以Maven为例)中,添加starter和数据库驱动(以MySQL驱动为例)的依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
2 配置数据源
在application.properties或application.yml文件中配置数据库连接信息,包括URL、用户名、密码和其他设置。
3 实现dao层
3.1 实体类
@Entity //表示这是一个JPA实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long studentId;
private String name;
private int age;
private Long classId;
}
3.2 创建Repository接口
方式1 使用Spring Data JPA提供的接口默认实现
定义一个接口继承Spring Data JPA官方提供的Repository,并指定实体类和主键的类型。Spring Data JPA会自动生成标准的CRUD操作。
CrudRepository<T, ID>:仅提供一些简单的增删查改功能PagingAndSortingRepository<T, ID>:继承于CrudRepository,除了具有CrudRepository接口的能力外,还新增了分页和排序的功能JpaRepository<T, ID>:继承于PagingAndSortingRepository,最常用,包含CRUD操作和分页、排序功能
public interface StudentRepository extends JpaRepository<Student,Long> { }
通过继承上述接口,无需我们显式定义常用方法,以下方法会自动提供:
save(T entity):保存或更新实体。findById(ID id):按主键查找实体。findAll():查询所有记录。deleteById(ID id):按主键删除实体。count():统计总记录数。existsById(ID id):判断某主键对应的记录是否存在。
方式2 自定义方法
除了可以直接使用Spring Data JPA接口提供的基础功能外,Spring Data JPA还允许开发者自定义查询方法,对于符合以下命名规则的方法,Spring Data JPA能够根据其方法名为其自动生成SQL,除了使用示例中的 find 关键字,还支持的关键字有:query、get、read、count、delete等。
除此之外,也可以通过@Query注解手写SQL。
4 实现Service层
4.1 接口
创建一个Service层接口,如StudentService,并在其中定义需要的业务方法。
public interface StudentService {
Student saveStudent(Student student);
List<Student> saveAllStudents(List<Student> studentList);
void deleteById(Long id);
}
4.2 实现类
创建接口的实现类,如StudentServiceImpl,并在类上标明@Service注解。在StudentServiceImpl中通过@Autowired自动注入Repository,使用Repository提供的标准方法实现业务逻辑。
@Service
public class StudentServiceImpl implements StudentService{
@Autowired
private StudentRepository studentRepository;
@Override
public Student saveStudent(Student student) {
return studentRepository.save(student);
}
@Override
public List<Student> saveAllStudents(List<Student> studentList) {
return studentRepository.saveAll(studentList);
}
@Override
public void deleteById(Long id) {
studentRepository.deleteById(id);
}
}
5 实现Controller层
创建一个控制器如StudentController,并在类上标注@RestController注解。在类中使用@RequestMapping或@GetMapping等注解定义API接口。通过@Autowired注入Service层的接口,调用Service层的方法来处理业务逻辑,将结果返回给客户端,通常以JSON格式返回。
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping("/student")
public Student addNewStudent(@RequestBody Student student){
return studentService.saveStudent(student);
}
@PostMapping("/students")
public List<Student> addAllStudents(@RequestBody List<Student> studentList){
return studentService.saveAllStudents(studentList);
}
@DeleteMapping("/student")
public void deleteStudentById(long id){
studentService.deleteById(id);
}
}