当前位置: 首页 > article >正文

SpringBoot依赖之Microsoft SQL Server Driver

写在前面:坚持是件有意思的事情。

概念

MS SQL Server Driver
  • 依赖名称: MS SQL Server Driver
  • 功能描述: A JDBC and R2DBC driver that provides access to Microsoft SQL Server and Azure SQL Database from any Java application.
  • 中文释义:JDBC 和 R2DBC 驱动程序,提供从任何 Java 应用程序对 Microsoft SQL Server 和 Azure SQL 数据库的访问。

在 IntelliJ IDEA 下创建 Spring Boot 3.4 项目并集成 Microsoft SQL Server 驱动依赖的步骤如下。本文将详细介绍如何创建项目、配置依赖、连接到 MS SQL Server 数据库,以及进行一些基本的数据库操作。

一、环境准备

  1. IntelliJ IDEA 代码编辑器,开发利器。
  2. JDK: JDK 17 或更高版本, Spring Boot 3.4
  3. 安装 MS SQL Server:确保已经安装并配置好 Microsoft SQL Server 数据库。如果没有,可以通过 Docker 或直接安装在本地/服务器上使用。这个自行安装,推荐本地化Docker部署,支持一键卸载,干净又卫生。
  4. 获取 SQL Server 驱动:Spring Boot 项目中会自动通过 Maven 或 Gradle 管理 MS SQL Server 的依赖,无需手动下载。

二、通过 Spring Initializr 创建 Spring Boot 项目

1. 创建项目

引入依赖包,添加以下依赖:

  • Spring Web:用于构建 Web 应用。
  • Spring Data JPA:用于使用 JPA 进行数据库操作。
  • MS SQL Server Driver:用于连接 Microsoft SQL Server 数据库。
  • lombok 超级工具包
<properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

三、配置 MS SQL Server 数据库连接

1. 配置 application.properties

项目创建完成后,在 src/main/resources 目录下找到 application.propertiesapplication.yml 文件,并进行数据库连接的配置。

我使用的是 application.properties,我觉得这个看起来更舒服。.yml配置格式空格每次我都对不齐层级:
spring.application.name=spring-ms-sql-server-sql-driver

# MS SQL Server 数据库连接配置
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=spring-dependencies
spring.datasource.username=db_username
spring.datasource.password=db_password
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.SQLServerDialect

说明

  • spring.datasource.url:数据库的 JDBC 连接 URL,格式为 jdbc:sqlserver://主机名:端口号;databaseName=数据库名。默认的 SQL Server 端口是 1433
  • spring.datasource.usernamespring.datasource.password:MS SQL Server 的用户名和密码。
  • spring.jpa.hibernate.ddl-auto:用于控制 Hibernate 是否自动创建和更新数据库表结构。update 表示自动更新。
  • spring.jpa.show-sql:显示 SQL 语句,放鞭调试。
  • spring.jpa.database-platform:指定 SQL Server 使用的 Hibernate 方言。
2. 确保 MS SQL Server 数据库已启动

确保 SQL Server 已启动,并且能够接受连接。可以使用 SQL Server Management Studio 或命令行创建数据库及用户:

CREATE DATABASE your_database;

为用户赋予访问权限:

CREATE LOGIN your_username WITH PASSWORD = '你的密码';
USE your_database;--你的数据库名称
CREATE USER your_username FOR LOGIN your_username; -- 数据库账户名
ALTER ROLE db_owner ADD MEMBER your_username; -- 赋权

四、创建实体类和仓库

1. 创建实体类

创建一个实体类 Customer,也就是常说的pojo,可以是数据库实体类,也可以是自定义的对象:

package com.dependencies.springmssqlserversqldriver.entity;

import jakarta.persistence.*;
import lombok.Data;

/**
 * @author zhizhou   2024/9/24 18:57
 */
@Data
@Entity
@Table(name = "users") // 数据库中的表名
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String email;
}

2. 创建 JPA 仓库接口

创建一个接口 CustomerRepository 实现数据库基本操作,因为jpa中已经实现了大部分方法,相对简单很多:

package com.dependencies.springmssqlserversqldriver.repository;

import com.dependencies.springmssqlserversqldriver.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * @author zhizhou   2024/9/24 19:00
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    User findByName(String username);
    
    // 可以添加自定义查询方法
    User findByEmail(String email);
}

五、创建控制器测试数据库操作

创建一个控制器 UserController:

package com.dependencies.springmssqlserversqldriver.controller;

import com.dependencies.springmssqlserversqldriver.entity.User;
import com.dependencies.springmssqlserversqldriver.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author zhizhou   2024/9/24 19:01
 */
@RestController
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserRepository userRepository;
    
    // 获取所有用户
    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    // 根据 ID 获取用户
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userRepository.findById(id).orElse(null);
    }
    
    // 创建新用户
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }
    
    // 更新用户
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        User user = userRepository.findById(id).orElse(null);
        if (user != null) {
            user.setName(userDetails.getName());
            user.setEmail(userDetails.getEmail());
            return userRepository.save(user);
        }
        return null;
    }
    
    // 删除用户
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userRepository.deleteById(id);
    }
}

六、运行项目并测试

1. 运行 Spring Boot 应用

在 IntelliJ IDEA 中,运行Application 并运行项目。

package com.dependencies.springmssqlserversqldriver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringMsSqlServerSqlDriverApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(SpringMsSqlServerSqlDriverApplication.class, args);
    }
}
2. 使用 Postman 或 cURL 测试 API
  • 创建新客户

    curl -X POST http://localhost:8080/customers \
         -H "Content-Type: application/json" \
         -d '{"name": "一周一志程序员", "email": "zhouzhi@csdn.com"}'
    
  • 获取所有客户

    curl http://localhost:8080/customers
    
  • 获取特定客户

    curl http://localhost:8080/customers/1
    
  • 更新客户信息

    curl -X PUT http://localhost:8080/customers/1 \
         -H "Content-Type: application/json" \
         -d '{"name": "Jane Doe", "email": "jane@example.com"}'
    
  • 删除客户

    curl -X DELETE http://localhost:8080/customers/1
    

http://www.kler.cn/news/325935.html

相关文章:

  • 谈谈Redisson分布式锁的底层实现原理
  • 怎么提取视频里的音频?非常简单的提取音频方法
  • 上下位关系自动检测方法(论文复现)
  • Stargazers Ghost Network在GitHub平台上的隐性威胁
  • 大数据复习知识点4
  • 深度估计任务中的有监督和无监督训练
  • leetcode45:跳跃游戏||
  • 超详细超实用!!!AI编程之cursor编写设计模式开闭原则实例(四)
  • Javase学习day1-前置知识
  • 【Android 源码分析】Activity短暂的一生 -- 目录篇 (持续更新)
  • 记一次教学版内网渗透流程
  • Proteus如何添加数码管
  • [遇到问题] Word中插入公式横线“-”变成了长连字符
  • 匿名管道 Linux
  • 2024年软考网络工程师中级题库
  • 汽车总线之----J1939总线
  • elementUI表格中某个字段(state)使用计算属性进行转换为对应中文显示
  • 【Linux】进程周边之优先级、调度与切换
  • 9.29总结
  • linux 命令行删除 整个单词
  • 【QT Quick】基础语法:导入外部QML文件
  • Linux之Docker虚拟化部署
  • STM32移植RT-Thread实现DAC功能
  • Go版数据结构 -【4.1 二叉树】
  • 1688商品API接口:电商数据自动化的新引擎
  • JVM 几种经典的垃圾收集器
  • 解决跨域问题的方法
  • Linux 网络配置 (深入理解)
  • 初识C语言(四)
  • Llama 3.2——同时具备文本和图像处理功能的开源模型