idea Spring Boot项目使用JPA创建与数据库链接

2023-12-28 22:35:53

1.pom.xml文件中添加依赖

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-test</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

2.创建entity文件,用于创建用户类(User)

3.entity文件夹下创建用户类

?User代码如下:

package com.example.demo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tb_user")
public class User {
    @Id
    @Column(name = "f_id")
    private Integer id;

    @Column(name = "f_username", unique = true, nullable = false, length = 16)
    private String username;

    @Column(name = "f_password", length = 32, nullable = false)
    private String password;

    @Column(name = "f_name", length = 64)
    private String name;

    @Column(name = "f_age")
    private Integer age;

    @Column(name = "f_phone", length = 11)
    private String phone;


}

4.resources文件夹下创建application.yml文件?

?

配置数据库连接信息 (一定要保证username、password与自己所使用数据库信息一致)

application.yml文件下代码:

sever:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db_qfnu_test1
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  1. Server 配置:

    server: port: 8080

    这部分配置指定了应用程序的服务器配置,该应用程序将在本地监听8080端口。

  2. Spring 数据源配置:

    spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/db_qfnu_test username: root password: 123456

    这一部分配置了Spring框架中的数据源,用于连接数据库。

    • driver-class-name: 指定数据库驱动类,这里是MySQL的JDBC驱动。
    • url: 数据库连接的URL,包括数据库类型、主机名、端口号和数据库名称。
    • usernamepassword: 数据库连接的用户名和密码。
  3. Spring JPA 配置:

    spring: jpa: hibernate: ddl-auto: update show-sql: true

    这一部分配置了Spring Data JPA,用于简化数据访问层的开发。

    • hibernate.ddl-auto: 指定Hibernate在启动时如何更新数据库表结构。在这里,设置为update表示 Hibernate 将尝试更新数据库表结构,但不会删除表或数据。
    • show-sql: 将此属性设置为 true 将在控制台上打印出Hibernate执行的SQL语句,方便调试。

5.创建数据库

创建数据库代码:

进入数据库:mysql -u root -p
查看数据库:show databases;
创建新表: create database db_qfnu_test1;

6.运行代码

运行出成功截图:?

?7.实现对数据库与前端交互

在User类中创建方法

package com.example.demo.entity;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tb_user")
public class User {
    @Id
    @Column(name = "f_id")
    private Integer id;

    @Column(name = "f_username", unique = true, nullable = false, length = 16)
    private String username;

    @Column(name = "f_password", length = 32, nullable = false)
    private String password;

    @Column(name = "f_name", length = 64)
    private String name;

    @Column(name = "f_age")
    private Integer age;

    @Column(name = "f_phone", length = 11)
    private String phone;

    public Integer getId() {
        return id;
        }

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

    public String getUsername() {
        return username;
        }

    public void setUsername(String username) {
        this.username = username;
        }

    public String getPassword() {
        return password;
        }

    public void setPassword(String password) {
        this.password = password;
        }

    public String getName() {
        return name;
        }

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

    public void setAge(int age) {
        this.age = age;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

创建Dao文件夹,用于创建User接口?

?

Dao文件夹下创建UserDAO接口,选择Interface

UserDAO代码:

package com.example.demo.Dao;

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDAO extends JpaRepository<User, Integer> {
}

创建UserController文件

UserController文件中编写Mapping,代码:

package com.example.demo.controller;

import com.example.demo.Dao.UserDAO;
import com.example.demo.Dao.UserDAO;
import com.example.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private final UserDAO userDao;
    public UserController(UserDAO userDao){
        this.userDao = userDao;
    }

    @GetMapping("findById/{id}")
    public User findById(@PathVariable Integer id){
        Optional<User> userOptional = userDao.findById(id);

        return userOptional.orElse(null); ??get?or?else
    }

    @PostMapping("add")
    public void add(User user){
        userDao.save(user);
    }
    @PostMapping("save")
    public String save(@RequestBody User user){
        userDao.save(user);
        return "success";
    }

    @PostMapping("removeById/{id}")
    public String removeById(@PathVariable Integer id){
        userDao.deleteById(id);
        return "success";
    }
}

数据库中添加表项:?

运行代码,导航栏中输入:http://localhost:8080/user/findById/1查看运行结果

前后端交互成功截图:

文章来源:https://blog.csdn.net/qq_60245590/article/details/135278637
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。