SpringBoot与JPA快速配置

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);

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值