Spring Boot中简单使用jpa操作数据库

去官网下载或者直接使用IDEA创建

直接下载

操作mysql数据库

1.依赖

       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-jpa</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-thymeleaf</artifactId>
       </dependency>

2. 写一个接口继承JpaRepository

public interface DescImgRep extends JpaRepository<DescImg,Integer> {
}

3.写Service接口 、实现类、model

public interface DescImgService {
    List<DescImg> findAll();
    DescImg findById(Integer id);
    void save(DescImg descImg);
    void update(DescImg descImg);
    void deleteById(Integer id);
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service//此注解十分重要
public class DescImgServiceImpl implements DescImgService{

    @Autowired
    DescImgRep descImgRep;

    @Override
    public List<DescImg> findAll() {
        List<DescImg> list = descImgRep.findAll();
        return list;
    }

    @Override
    public DescImg findById(Integer id) {
        Optional<DescImg> descImgRepById = descImgRep.findById(id);
        return descImgRepById.get();
    }

    @Override
    public void save(DescImg descImg) {
        descImgRep.save(descImg);
    }

    @Override
    public void update(DescImg descImg) {
    }
    
    @Override
    public void deleteById(Integer id) {
    }
}

import javax.persistence.*;
@Entity
@Table(name = "desc_img")
public class DescImg {
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Id
    @Column(name = "id")
    Integer id = 0;
    String descs;
    String imgUrl;
    String uploadTime;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getDescs() {
        return descs;
    }
    public void setDescs(String descs) {
        this.descs = descs;
    }
    public String getImgUrl() {
        return imgUrl;
    }
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
    public String getUploadTime() {
        return uploadTime;
    }
    public void setUploadTime(String uploadTime) {
        this.uploadTime = uploadTime;
    }
}

4.写Controller

@RestController
public class DescImgController {

    @Autowired
    DescImgService service;//搞不清为啥不是实现类而是那个接口

    @RequestMapping("/getDescImgList")
    @ResponseBody
    public List<DescImg> Hello() {
        List<DescImg> all = service.findAll();
        return all;
    }

    @RequestMapping(value = "/saveDescImgInfo", method = RequestMethod.POST)
    @ResponseBody
    public String saveDescImgInfo(@RequestBody DescImg descImg) {
        try {
            service.save(descImg);
            return "成功";
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return "失败";
        }
    }

    @RequestMapping(value = "/saveImg",method = RequestMethod.POST)
    public String saveImg(@RequestParam MultipartFile params, Integer id) {
        String path = "D://mysql_img/uploads/";
        String fileType = params.getOriginalFilename().substring(params.getOriginalFilename().indexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-", "");
        DescImg serviceById = service.findById(id);
        String fileEndPath = path + fileName + fileType;
        serviceById.setImgUrl(fileEndPath);
        //保存路劲到数据库
        service.save(serviceById);
        //保存文件到本地(数据库或者硬盘上面)
        try {
            params.transferTo(new File(fileEndPath));
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return fileEndPath;
    }
	
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public DescImg getInfoById(Integer id) {
        return service.findById(id);
    }
	//映射图片
    @RequestMapping(value = "/getPic", method = RequestMethod.POST, produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity getPic(Integer id) {
        try {
            String imgUrl = service.findById(id).getImgUrl();
            System.out.println(imgUrl);
            FileInputStream stream = new FileInputStream(imgUrl);
            byte[] byteArray = getByteArray(stream);

            HttpHeaders headers = new HttpHeaders();
            String fileType = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
            System.out.println(fileType);
            if (fileType == "png" || fileType == "PNG") {
                headers.setContentType(MediaType.IMAGE_PNG);
            }else if (fileType == "gif") {
                headers.setContentType(MediaType.IMAGE_GIF);
            } else {
                headers.setContentType(MediaType.IMAGE_JPEG);
            }
            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public byte[] getByteArray(FileInputStream inputStream) {
        try {
            int b;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            byte[] byteTemp = new byte[1024];
            while ((b = inputStream.read(byteTemp)) != -1) {
                byteArrayOutputStream.write(byteTemp, 0, b);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return new byte[]{};
        }
    }
}
  • 0
    点赞
  • 0
    评论
  • 1
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:深蓝海洋 设计师:CSDN官方博客 返回首页

打赏作者

且白

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值