Spring Boot SQL Server Example CRUD
Spring Boot SQL Server Example CRUD
docker run ^
-e "ACCEPT_EULA=Y" ^
-e "MSSQL_SA_PASSWORD=Luiscoco123456" ^
-p 1433:1433 ^
-d mcr.microsoft.com/mssql/server:2022-latest
https://md2pdf.netlify.app 1/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
spring-boot-starter-actuator
spring-boot-starter-data-jpa
spring-boot-starter-web
mssql-jdbc
springdoc-openapi-starter-webmvc-ui
spring-boot-starter-test
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<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>
https://md2pdf.netlify.app 3/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.bezkoder.spring.mssql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootSqlServerApplication {
https://md2pdf.netlify.app 4/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
package com.bezkoder.spring.mssql.model;
import jakarta.persistence.*;
@Entity
@Table(name = "tutorials")
public class Tutorial {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "published")
private boolean published;
public Tutorial() {
https://md2pdf.netlify.app 5/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
return published;
}
@Override
public String toString() {
return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=
}
3.5. Repository
TutorialRepository.java
package com.bezkoder.spring.mssql.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.bezkoder.spring.mssql.model.Tutorial;
3.6. Controller
We also configure the Swagger Open API docs for each action inside the controller
TutorialController
package com.bezkoder.spring.mssql.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
https://md2pdf.netlify.app 6/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.bezkoder.spring.mssql.model.Tutorial;
import com.bezkoder.spring.mssql.repository.TutorialRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
// @CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
@Tag(name = "Tutorial", description = "The Tutorial API")
public class TutorialController {
@Autowired
TutorialRepository tutorialRepository;
@Operation(summary = "Test the API", description = "Test endpoint to verify the API is wor
@ApiResponse(description = "Success", responseCode = "200", content = @Content(mediaTy
@GetMapping("/test")
public ResponseEntity<String> test() {
return ResponseEntity.ok("Test endpoint response");
}
if (tutorials.isEmpty()) {
// Add logging here
System.out.println("No tutorials found");
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
https://md2pdf.netlify.app 7/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
if (tutorialData.isPresent()) {
return new ResponseEntity<>(tutorialData.get(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@Operation(summary = "Create a new tutorial", description = "Add a new tutorial to the dat
@ApiResponse(description = "Created", responseCode = "201", content = @Content(mediaTy
@ApiResponse(description = "Internal Server Error", responseCode = "500") })
@PostMapping("/tutorials")
public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) {
try {
Tutorial _tutorial = tutorialRepository
.save(new Tutorial(tutorial.getTitle(), tutorial.getDescription(), false))
return new ResponseEntity<>(_tutorial, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
if (tutorialData.isPresent()) {
Tutorial _tutorial = tutorialData.get();
_tutorial.setTitle(tutorial.getTitle());
_tutorial.setDescription(tutorial.getDescription());
_tutorial.setPublished(tutorial.isPublished());
return new ResponseEntity<>(tutorialRepository.save(_tutorial), HttpStatus.OK);
} else {
https://md2pdf.netlify.app 8/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
@Operation(summary = "Delete all tutorials", description = "Delete all tutorials from the
@ApiResponse(description = "Successful deletion", responseCode = "204"),
@ApiResponse(description = "Internal server error", responseCode = "500")
})
@DeleteMapping("/tutorials")
public ResponseEntity<HttpStatus> deleteAllTutorials() {
try {
tutorialRepository.deleteAll();
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping("/tutorials/published")
public ResponseEntity<List<Tutorial>> findByPublished() {
try {
List<Tutorial> tutorials = tutorialRepository.findByPublished(true);
if (tutorials.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(tutorials, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
3.7. application.properties
https://md2pdf.netlify.app 9/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
spring.datasource.url= jdbc:sqlserver://localhost:1433;encrypt=true;trustServerCertificate=tru
spring.datasource.username= sa
spring.datasource.password= Luiscoco123456
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.SQLServerDialect
spring.jpa.hibernate.ddl-auto= update
#springdoc.api-docs.enabled=false
#springdoc.swagger-ui.enabled=false
#springdoc.packages-to-scan=com.bezkoder.spring.swagger.controller
springdoc.swagger-ui.path=/bezkoder-documentation
springdoc.api-docs.path=/bezkoder-api-docs
#springdoc.swagger-ui.operationsSorter=method
#springdoc.swagger-ui.tagsSorter=alpha
springdoc.swagger-ui.tryItOutEnabled=true
springdoc.swagger-ui.filter=true
bezkoder.openapi.dev-url=http://localhost:8080
bezkoder.openapi.prod-url=https://bezkoder-api.com
package com.bezkoder.spring.mssql.config;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.servers.Server;
@Configuration
public class OpenAPIConfig {
@Value("${bezkoder.openapi.dev-url}")
private String devUrl;
@Value("${bezkoder.openapi.prod-url}")
private String prodUrl;
https://md2pdf.netlify.app 10/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
@Bean
public OpenAPI myOpenAPI() {
Server devServer = new Server();
devServer.setUrl(devUrl);
devServer.setDescription("Server URL in Development environment");
mvn spring-boot:run
https://md2pdf.netlify.app 11/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
We can sent a GET request to see all the tutorials stored in the SQL Sever database
https://md2pdf.netlify.app 12/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
https://md2pdf.netlify.app 13/14
11/4/24, 8:39 Spring Boot + SQL Server example: CRUD Operations Rest API
https://md2pdf.netlify.app 14/14