springboot整合jpa

创建springboot项目添加相关依赖

  • 添加jpa依赖
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
  • 添加mysql数据库依赖
<dependency>
  <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

配置数据源

  • 注意:为配置显示更清晰简洁,把application.properties改为yml文件
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
    username: gaoce
    password: gaoce
  jpa:
    hibernate:
      ddl-auto: update  #第一次建表用create,后面用update
    show-sql: true
server:
  port: 8090

创建实体对象

  • 通过@Entity 表明是一个映射的实体类, @Id表明id, @GeneratedValue 字段自动生成
@Entity
public class Student {
    @Id
    @GeneratedValue
    private int id;
    private String userName;
    private String age;
    private String gender;
    ....set and get

dao层

  • 继承JpaRepository,即可使用一组JPA规范相关的方法
public interface StudentDao extends JpaRepository<Student,Integer> {
}

Web层

@RestController
public class StudentController {
    @Autowired
    StudentDao studentDao;
    @GetMapping("/hi")
    public String index(){
        return "hello world";
    }
    /**
     *保存学生
     * @param student
     * @return
     */
    @PostMapping("/save")
    public Student save(@RequestBody Student student){
        return studentDao.save(student);
    }

    /**
     * 查询学生集合
     * @return
     */
    @GetMapping("/students")
    public List<Student> getStudents(){
        return studentDao.findAll();
    }
    /**
     * 根据ID查询学生
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Optional<Student> getStudentById(@PathVariable int id){
        return studentDao.findById(id);
    }
    /**
     * 修改学生信息
     * @param id
     * @param age
     * @param userName
     * @return
     */
   @PutMapping("/{id}")
    public Student updateStudent(@PathVariable int id, @RequestParam  String age,@RequestParam  String userName){
        Student student = new Student();
        student.setId(id);
        student.setAge(age);
        student.setUserName(userName);
       return  studentDao.saveAndFlush(student);
   }
}

猜你喜欢

转载自blog.csdn.net/qq_30065395/article/details/79584456
今日推荐