SpringData:是Spring为了操作数据库中的数据所提供的自动化框架,JPA只是其中一个基于数据操作的模块。
相同点:
都为持久层框架
不同点:
hibernate是面向对象的,而MyBatis是面向关系的
Mybatis作为半自动化ORM关系映射,需要自己写接口并且写SQL语句。
hibernate作为自动化框架,无需自己写SQL语句,默认会给出常用的SQL,自动实现查询方法。
所需依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>实体类
@Data @Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column private String name; @Column private Double score; @Column private Date birthday; }@Id 表示与数据库中的Id映射起来
@GeneratedValue 表示数据是自增的
@Column 与数据库中的非id字段映射
接口
public interface StudentRepository extends JpaRepository<Student,Long> { public Student getById(Long id); }直接继承父类JpaRepository<Student,Long> Student为实体类,Long为主键字段对应的类型。
在JpaRepository 可以看到常用的数据库查询方法已经给出。
controller层
@RestController public class StudentHandler { @Autowired private StudentRepository studentRepository; @GetMapping("/findAll") public List<Student> findAll() { return studentRepository.findAll(); } @GetMapping("/findById/{id}") public Student findById(@PathVariable("id") Long id) { return studentRepository.getById(id); } @PostMapping("/save") public Student save(@RequestBody Student student) { return studentRepository.save(student); } @PutMapping("/update") public Student update(@RequestBody Student student) { return studentRepository.save(student); } @DeleteMapping("/deleteById/{id}") public void deleteById(@PathVariable("id") Long id) { studentRepository.deleteById(id); } }application.yml
spring: datasource: url: jdbc:mysql://localhost:3306/myspringboot?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver jpa: show-sql: true properties: hibernate: format_sql: ture