Spring JPA实现增删改查

1. 创建一个Spring工程

2.配置application文件

spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=

3.创建实体类Piano

1.定义好属性并设置setget方法

2.添加@Entity && @Table(name = "piano")注解

3.添加@Id && @GeneratedValue(strategy = GenerationType.IDENTITY)

4.连接数据库

完成

package com.test.piano.entity;

import javax.persistence.*;

@Entity
@Table(name = piano)
public class piano {
    private int id;
    private String brand;
    private String price;
    private String pic;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }
}

5.创建Dao和Service的包

6.在Dao中创建一个接口并继承JpaRepository,然后指定实体类piano和主键的类型Integer

public interface pianoRepository extends JpaRepository<piano,Integer>

7.在Service中创建类PianoService用于实现增删改查

8.添加注解

@Service表示是业务逻辑层
@Transactional(readOnly = false)
readOnly=true表明所注解的方法或类只是读取数据。
readOnly=false表明所注解的方法或类是增加,删除,修改数据。

4.创建Controller类

package com.test.piano.controller;


import com.test.piano.entity.piano;
import com.test.piano.service.PianoService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @date 2020/3/24
 * @author Charlotte
 */

@RestController
@RequestMapping("/piano")
public class PianoController {

    @Resource
    private PianoService pianoService;

    @RequestMapping("/hello")
    public String hello(){
        return "Hello World!";
    }

    @RequestMapping("/add")
    public String add(){
        return "添加成功!";
    }

    @RequestMapping("/list")
    public List<piano> findAll(){
        return this.pianoService.findAll();
    }
}

posted @ 2020-03-24 21:38  两小无猜  阅读(1242)  评论(0编辑  收藏  举报