springboot整合spring-data jpa

springboot整合sprign-data-jpa

maven依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-tomcatartifactId>
            
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.16.20version>
            <scope>providedscope>
        dependency>
    dependencies>

项目结构图

springboot整合spring-data jpa_第1张图片

demo代码(简单例子没加service业务层,具体视情况自己定)

entity

import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Data
@Entity
public class Boot {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

dao

import org.springframework.data.repository.CrudRepository;
public interface BootRepository extends CrudRepository<Boot, Long> {
}

controller

@RestController
@RequestMapping("/web")
public class QueryController {

    @Autowired
    private BootRepository bootRepository;

    @RequestMapping("/hello")
    public String say(String name) {
        return "hell:" + name;
    }

    @RequestMapping("/")
    public Iterable get() {
        return bootRepository.findAll();
    }

    @GetMapping("/{id}")
    public Optional getById(@PathVariable Long id){
      return bootRepository.findById(id);
    }

    @RequestMapping("/add")
    public String add(){
        Boot boot=new Boot();
        boot.setName("admin");
        bootRepository.save(boot);
        return "good";
    }

    @GetMapping("/delete/{id}")
    public void delete(@PathVariable Long id){
        bootRepository.deleteById(id);
    }
    }

访问http://localhost:8080/web/1
这里写图片描述

你可能感兴趣的:(java)