spring boot 连接数据库

第一步 新建yml文件

spring boot 连接jpa数据库yml文件
在这里插入图片描述

第二步在该位置创建你需要用到的表模型

选择Java class

在这里插入图片描述
例:

package com.example.springboottest.entity;

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
@Data
public class Book {
    @Id
    private Integer id;
    private String name;
    private String author;
}
//注解记得添加

第三步创建接口

选择interface
在这里插入图片描述

package com.example.springboottest.repository;

import com.example.springboottest.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book,Integer> {
}
//需要继承JpaRepository

第四步测试repository

在这里插入图片描述选择你刚刚创建的repository类右键该处选择 go to → test,创建

在这里插入图片描述会在该处生成一个test类,举例代码:

package com.example.springboottest.repository;

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

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
class BookRepositoryTest {
    @Autowired
    private BookRepository bookRepository;
    @Test
    void findAll(){
        System.out.println(bookRepository.findAll());
    }
}

然后你运行一下看看是否能够查询到数据库的信息

最后一步

在这里插入图片描述在controller下创建handler

例码

package com.example.springboottest.controller;

import com.example.springboottest.entity.Book;
import com.example.springboottest.repository.BookRepository;
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 java.util.List;

@RestController
@RequestMapping("/book")
public class BookHandler {
    @Autowired
    private BookRepository bookRepository;
    @GetMapping("/findAll")
    public List<Book>findAll(){
        return bookRepository.findAll();
    }
}
//记得添加注解

最后运行该文件
在这里插入图片描述
浏览器输入

http://localhost:8181/book/findAll

正常情况下该页面会显示数据库的信息,到此spring boot和数据库就调通了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值