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);
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值