在 IntelliJ IDEA 下创建 Spring Boot 3.4 项目并集成 Microsoft SQL Server 驱动依赖的步骤如下。本文将详细介绍如何创建项目、配置依赖、连接到 MS SQL Server 数据库,以及进行一些基本的数据库操作。
引入依赖包,添加以下依赖:
<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>
application.properties
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
说明:
jdbc:sqlserver://主机名:端口号;databaseName=数据库名
。默认的 SQL Server 端口是 1433
。update
表示自动更新。确保 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; -- 赋权
创建一个实体类 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;
}
创建一个接口 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);
}
}
在 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);
}
}
创建新客户:
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