SpringBoot使用JPA实现简单的接口

本文介绍如何在Spring Boot项目中集成MySQL数据库,并通过RESTful API实现增删查改操作,包括配置文件设置、实体类定义、JPA接口创建及控制器编写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.新建项目:Spring Initializr-nex-选择jpa/mysql/web

2.注释Pop.xml下tomcat节点的<scope>provided</scope>节点,测试下本地运行

3.数据库配置

在main/resources/static下新建application.yml,配置信息如下,@JsonIgoreProperties(ignorUnknown=true),表示在json转bean时,忽略json中bean不存在的属性

spring:
  datasource:
    password: admin
    username: admin
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://114.67.143.XX:3306/springboottest?charset=utf8&serverTimezone=UTC

    tomcat:
    #连接池的最大数据库连接数。设为0表示无限制。
      max-active: 20
      test-while-idle: true
      #该选项用来验证数据库连接的有效性。
      #SELECT 1(mysql), select 1 from dual(oracle), SELECT 1(MS Sql Server) 。
      validation-query: select 1
      default-auto-commit: false
      min-idle: 15
      initial-size: 15
      #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
      max-wait:

#是否显示sql语句和自动更新表结构
  jpa:
    database: mysql
    show-sql: true
    hibernate:
      ddl-auto: update
#      服务的端口号
server:
  port: 9000

配置基本信息完毕。

4.数据库映射bean和请求返回bean实体类建立

package com.dxxx.bean;

public class Response {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
package com.dxxx.bean;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "user")
@JsonIgnoreProperties(ignoreUnknown = true)
//@JsonIgnoreProperties({ "internalId", "secretKey" })
//指定的字段不会被序列化和反序列化。
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "name")
    private String name;
    @Column(name = "number")
    private String number;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}

5.数据库映射类所需的jpa建立

package com.dxxx.jpa;

import com.dxxx.bean.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import java.io.Serializable;

public interface UserJpa extends JpaRepository<User,Long>,JpaSpecificationExecutor<User>,Serializable{
}

6.数据请求接口的建立

package com.dxxx.control;

import com.dxxx.bean.Response;
import com.dxxx.bean.User;
import com.dxxx.jpa.UserJpa;
import org.apache.juli.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping(value = "/UserMessageControl")
public class UserMessage {
    @Autowired
    private UserJpa userJpa;

    /**
     * 获取数据库所有用户的方法
     */
    @RequestMapping(value = "/getMessage", method = RequestMethod.GET)
    public List<User> getAllUsers() {
        return userJpa.findAll();
    }

    /**
     * 插入数据的方法
     *
     * @param name
     * @param number
     * @return
     */
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    //如果前端传的名字不一样@RequestParam("account") 表示解析为name
    public User addUser(@RequestParam String name, @RequestParam String number) {
        System.out.print(name + number + "======");
        User user = new User();
        user.setName(name);
        user.setNumber(number);
        System.out.print(user.getId() + "");
        User add = userJpa.save(user);
        return add;
    }

    /**
     * 删除数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
    public Response deleteByid(@RequestParam long id) {
        Response response = new Response();
        userJpa.deleteById(id);
        Optional<User> all = userJpa.findById(id);
        if (all.isPresent()) {
            response.setMessage("删除失败");
            return response;
        } else {
            response.setMessage("删除成功");
            return response;
        }
    }

    /**
     * heard
     *
     * @param accessToken
     * @param name
     */
    @PostMapping(value = "/login")
    public Response login(@RequestHeader("access_token") String accessToken, @RequestParam String name) {
        System.out.println("accessToken:" + accessToken);
        Response response = new Response();
        response.setMessage("accessToken:" + accessToken);
        return response;
    }


    /**
     * 接受json
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/addByJson")
    public User registerUser(@RequestBody User user) {
        User add = userJpa.save(user);
        return add;
    }


    /**
     * 接受带入参数的file,默认情况下static下的文件可以直接使用url访问:url+文件名字,如192.168.2.1:8080/test.jpg
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/upimage", method = RequestMethod.POST)
    @ResponseBody
    public Response handleFileUpload(HttpServletRequest request) {
        Response response = new Response();
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        //表示获取参数名字为image1的文件
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("image1");
        String name = params.getParameter("name");
        System.out.println("name:" + name);
        String id = params.getParameter("id");
        System.out.println("id:" + id);
        System.out.println("文件的个数:" + files.size());
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    System.out.print("图片名字" + file.getOriginalFilename());
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File("src/main/resources/static/" + file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                    response.setMessage(file.getOriginalFilename() + "|" + response.getMessage());
                } catch (Exception e) {
                    stream = null;
                    response.setMessage("You failed to upload " + i + " => "
                            + e.getMessage());
                    return response;
                }
            } else {
                response.setMessage("You failed to upload " + i
                        + " because the file was empty.");
                return response;
            }
        }
        return response;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值