pom.xml
<parent>
<artifactId>spring-boot-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.1.4.RELEASE</version>
</parent>
<properties>
<maven.compiler.source>18</maven.compiler.source>
<maven.compiler.target>18</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
application.yml配置数据库和JPA
spring:
datasource:
url: jdbc:mysql://localhost:3306/mbtest?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: hsp
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
properties:
hibernate:
format_sql:true
实体类要加注释
@Data
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)//自增
private Long id;
@Column
private String name;
@Column
private Double score;
@Column
private Date birthday;
}
repository要继承:
public interface StudentRepository extends JpaRepository<Student,Long> {
//Long是主键类别
}
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.findById(id).get();//调用get方法
}
@PostMapping("/save")
public Student save(@RequestBody Student student){
return studentRepository.save(student);
}
@PutMapping("/put")
public Student update(@RequestBody Student student){
return studentRepository.save(student);
}
@DeleteMapping("/deleteById/{id}")
public void deleteById(@PathVariable("id")Long id){
studentRepository.deleteById(id);
}
}
启动类
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}