利用springboot连接数据库

本文档详细介绍了如何使用SpringBoot连接MySQL数据库,从数据库提取数据,并通过JpaRepository接口进行操作。测试结果显示数据成功从数据库传输到后端。接着,创建Controller将数据传递到前端Vue应用,实现了数据的前端展示。
摘要由CSDN通过智能技术生成

利用springboot连接数据库:

整个过程可以分为两步:

第一步是将数据库的表格数据提取到后端,通过测试抓取数据,判断数据是否已经从数据库传递到后端。

第二步是将数据从后端通过接口传到前端,因为前后端接口不一致,因此需要通过解决跨域问题将后端数据传到前端,实现数据的呈现。

第一步:

一、首先在resources中创建配置文件application.yml(一定要注意缩进,缩进不当会报错):

作用:配置数据库,连接数据库(地址、用户名、密码等)。

spring:
  datasource:
     url: jdbc:mysql://localhost:3306/mysql                   #数据库地址
     username: root                                           #<!--用户名-->
     password:
     driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
     show-sql: true
     properties:
      hibernate:
       format_sql: true                                      #//数据库查询语句不换行,格式清晰
server:
  port: 8181

二、创建car类,属性定义id,type,style。

package com.car.springboottest.entity;

import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
@Data
public class Car {
    @Id
    private Integer id;
    private String type;
    private String style;
}

三、创建CarRespository接口,继承JpaRepository,JpaRepository是简单查询:

package com.car.springboottest.repository;

import com.car.springboottest.entity.Car;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CarRepository extends JpaRepository<Car,Integer> {
}

四、创建测试类:

package com.car.springboottest.repository;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.SQLOutput;

import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class CarRepositoryTest {

    @Autowired
    private CarRepository carRepository;

    @Test
    void findAll(){
        System.out.println(carRepository.findAll());
    }

}

测试结果:

Hibernate: 
    select
        car0_.id as id1_0_,
        car0_.style as style2_0_,
        car0_.type as type3_0_ 
    from
        car car0_
[Car(id=1, type=卡罗拉, style=2021), Car(id=2, type=雷凌, style=2021), Car(id=3, type=亚洲龙, style=2021), Car(id=4, type=朗逸, style=2020), Car(id=5, type=帕萨特, style=2020), Car(id=6, type=捷达, style=2121)]

Process finished with exit code 0

以上测试结果说明数据已经从数据库传到后端,接下来需要把后端的数据传到前端。

第二步:

一、创建controller类

package com.car.springboottest.controller;

import com.car.springboottest.entity.Car;
import com.car.springboottest.repository.CarRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestController
@RequestMapping("/car")
public class CarHandler {
    @Autowired
    private CarRepository carRepository;


    @GetMapping("/findAll")
    public List<Car> findAll(){
        return carRepository.findAll();

    }
}

二、前端代码(.vue):

<template>
      <div>
        <table>
          <tr>
            <td>品牌</td>
            <td>车型</td>
            <td>款式</td>
          </tr>
          <tr v-for="item in cars" >               <!--遍历cars数组中的对象-->
            <td>{{item.brand}}</td>
            <td>{{item.type}}</td>
            <td>{{item.style}}</td>
          </tr>
        </table>
        {{msg}}
      </div>
</template>

<script>
export default {
  name: "Car",
  data() {
    return {
      msg: '欢迎进入易车',
      cars: []
    }
  },
  created() {
    const _this=this
      axios.get('http://localhost:8181/car/findAll').then(function (resp) {
        _this.cars =resp.data
      })
  }
}
</script>

<style scoped>

</style>

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
Spring Boot 是一个流行的轻量级 Java Web 应用框架,它可以简化与数据库交互的过程。连接数据库并执行增删改查操作主要涉及以下几个步骤: 1. **配置数据源**: 在 `application.properties` 或者 `application.yml` 文件中配置数据源信息,如数据库URL、用户名和密码等。例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=password ``` 2. **启用 JPA(Java Persistence API)或 MyBatis**: Spring Boot 支持多种持久层技术,JPA 是其中一种,如果选择 JPA,你需要添加依赖并创建一个或多个实体类(Entity)代数据库。 JPA 示例: ```java @Entity public class User { @Id private Long id; private String name; // getters and setters } ``` 如果使用 MyBatis,则需要配置 mapper 和 sqlSessionFactory。 3. **编写Repository接口**: 使用 Spring Data JPA 创建 Repository 接口,这将自动生成 CRUD 方法。对于 JPA,只需定义基本的方法名称即可,如 `save()`, `findById()`, `deleteById()` 等。 ```java public interface UserRepository extends JpaRepository<User, Long> {} ``` 4. **服务层操作数据库**: 在服务类(Service)中注入 Repository,并使用这些方法进行实际的增删改查操作。例如: ```java @Autowired private UserRepository userRepository; public User createUser(User user) { return userRepository.save(user); } public User getUser(Long id) { return userRepository.findById(id).orElse(null); } public void deleteUser(Long id) { userRepository.deleteById(id); } ``` 5. **处理事务**: 可以在 Service 类或 Controller 中管理事务,使用 `@Transactional` 注解。 **相关问题--:** 1. Spring Boot 连接数据库的基本流程是什么? 2. 如何在 Spring Boot利用 JPA 自动生成 CRUD 方法? 3. 在 Spring Boot 中如何配置事务管理?
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肆〇

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

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值