Skip to content

How to use Spring CRUD Generator v1.2.0 to generate Spring Boot APIs in minutes

Purpose

This post demonstrates how to use Spring CRUD Generator v1.2.0 to automate Spring Boot backend development.

The Spring CRUD Generator allows you to generate complete Spring Boot CRUD backends from YAML/JSON configuration files. It creates entities, DTOs, mappers, services, and controllers - eliminating hours of boilerplate coding.

There are 5 main goals:

  • Generate entities with validation annotations
  • Create DTOs with proper mapping
  • Build MyBatis or JPA repositories
  • Generate REST controllers with OpenAPI documentation
  • Create database migrations and Docker resources

We will use YAML configuration to generate a complete backend for a user management system.

Environment

  • Spring Boot 2.7+
  • Java 17+
  • Maven 3.6+
  • MySQL 8.0 (or any supported database)
  • v1.2.0 of the plugin

The Maven Plugin Setup

First, add the plugin to your pom.xml:

pom.xml
<build>
<plugins>
<plugin>
<groupId>com.bswen</groupId>
<artifactId>spring-crud-generator-maven-plugin</artifactId>
<version>1.2.0</version>
<configuration>
<configDir>src/main/resources/crud-generator</configDir>
<basePackage>com.example.demo</basePackage>
<projectName>UserManagementAPI</projectName>
<includeSwagger>true</includeSwagger>
<includeFlyway>true</includeFlyway>
<includeDocker>true</includeDocker>
</configuration>
</plugin>
</plugins>
</build>

I can explain the key parts:

  • configDir: Directory where YAML/JSON configuration files are stored
  • basePackage: Java package for generated code
  • projectName: Name used for documentation and resources
  • includeSwagger: Generate OpenAPI/Swagger documentation
  • includeFlyway: Generate Flyway database migrations
  • includeDocker: Generate Docker resources

The Configuration

Here’s the entity configuration file:

src/main/resources/crud-generator/entities.yaml
entities:
- name: User
fields:
- name: id
type: Long
nullable: false
id: true
generatedValue: true
- name: username
type: String
nullable: false
length: 50
unique: true
- name: email
type: String
nullable: false
length: 100
unique: true
- name: firstName
type: String
nullable: false
length: 50
- name: lastName
type: String
nullable: false
length: 50
- name: createdAt
type: LocalDateTime
nullable: false
- name: updatedAt
type: LocalDateTime
nullable: false
- name: active
type: Boolean
nullable: false
defaultValue: true
- name: Role
fields:
- name: id
type: Long
nullable: false
id: true
generatedValue: true
- name: name
type: String
nullable: false
length: 50
unique: true
- name: description
type: String
nullable: true
length: 200
- name: UserRole
fields:
- name: id
type: Long
nullable: false
id: true
generatedValue: true
- name: userId
type: Long
nullable: false
- name: roleId
type: Long
nullable: false
relationships:
- entity: User
type: ManyToOne
field: user
- entity: Role
type: ManyToOne
field: role
database:
type: mysql
host: localhost
port: 3306
database: user_management
username: root
password: password
url: jdbc:mysql://localhost:3306/user_management?useSSL=false&serverTimezone=UTC
api:
basePath: /api/v1
pagination:
defaultPageSize: 10
maxPageSize: 100

Here’s the database configuration file:

src/main/resources/crud-generator/database-config.yaml
validation:
- entity: User
fields:
- name: email
pattern: "^[A-Za-z0-9+_.-]+@(.+)$"
message: "Invalid email format"
- name: username
pattern: "^[a-zA-Z0-9_]{4,20}$"
message: "Username must be 4-20 characters alphanumeric with underscores"
apiEndpoints:
- entity: User
include: ["GET", "POST", "PUT", "DELETE"]
customEndpoints:
- name: getByUsername
path: "/users/{username}"
method: GET
description: "Get user by username"
- entity: Role
include: ["GET", "POST", "PUT", "DELETE"]
- entity: UserRole
include: ["GET", "POST", "PUT", "DELETE"]

How It Works

When I run this command:

Terminal window
mvn clean install crud-generator:generate

I get this output:

Terminal window
[INFO] --- spring-crud-generator-maven-plugin:1.2.0:generate (default-cli) @ UserManagementAPI ---
[INFO] Generating entities...
[INFO] - Generated User entity in com.example.demo.entity.User
[INFO] - Generated Role entity in com.example.demo.entity.Role
[INFO] - Generated UserRole entity in com.example.demo.entity.UserRole
[INFO] Generating DTOs...
[INFO] - Generated UserDto in com.example.demo.dto.UserDto
[INFO] - Generated RoleDto in com.example.demo.dto.RoleDto
[INFO] - Generated UserRoleDto in com.example.demo.dto.UserRoleDto
[INFO] Generating repositories...
[INFO] - Generated UserRepository in com.example.demo.repository.UserRepository
[INFO] - Generated RoleRepository in com.example.demo.repository.RoleRepository
[INFO] - Generated UserRoleRepository in com.example.demo.repository.UserRoleRepository
[INFO] Generating services...
[INFO] - Generated UserService in com.example.demo.service.UserService
[INFO] - Generated RoleService in com.example.demo.service.RoleService
[INFO] - Generated UserRoleService in com.example.demo.service.UserRoleService
[INFO] Generating controllers...
[INFO] - Generated UserController in com.example.demo.controller.UserController
[INFO] - Generated RoleController in com.example.demo.controller.RoleController
[INFO] - Generated UserRoleController in com.example.demo.controller.UserRoleController
[INFO] Generating migrations...
[INFO] - Generated V1__Create_user_management_tables.sql
[INFO] Generating Docker resources...
[INFO] - Generated Dockerfile
[INFO] - Generated docker-compose.yml
[INFO] Generation completed successfully!

But when I go into the generated code directory, I can see all the generated files:

Terminal window
ls -la src/main/java/com/example/demo/

You can see that I succeeded to generate a complete backend structure.

The generated code includes:

  • Entity classes with JPA annotations
  • DTO classes for API requests/responses
  • Repository interfaces with CRUD methods
  • Service classes with business logic
  • REST controllers with OpenAPI documentation
  • Flyway migration scripts
  • Docker configuration files

What It Generates

Entities

// Generated User entity
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 50, unique = true)
private String username;
@Column(nullable = false, length = 100, unique = true)
private String email;
@Column(nullable = false, length = 50)
private String firstName;
@Column(nullable = false, length = 50)
private String lastName;
@Column(nullable = false)
private LocalDateTime createdAt;
@Column(nullable = false)
private LocalDateTime updatedAt;
@Column(nullable = false)
private Boolean active = true;
// getters and setters
}

Controllers

// Generated UserController with OpenAPI documentation
@RestController
@RequestMapping("/api/v1/users")
@Tag(name = "User Management", description = "Operations for managing users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
@Operation(summary = "Get all users")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved list"),
@ApiResponse(responseCode = "500", description = "Internal server error")
})
public ResponseEntity<Page<UserDto>> getAllUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
Page<UserDto> users = userService.getAllUsers(page, size);
return ResponseEntity.ok(users);
}
@PostMapping
@Operation(summary = "Create a new user")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "User created successfully"),
@ApiResponse(responseCode = "400", description = "Invalid input"),
@ApiResponse(responseCode = "409", description = "Username or email already exists")
})
public ResponseEntity<UserDto> createUser(@Valid @RequestBody UserDto userDto) {
UserDto createdUser = userService.createUser(userDto);
return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
}
}

Migration Scripts

-- Generated Flyway migration
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
active BOOLEAN NOT NULL DEFAULT true
);
CREATE TABLE roles (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL UNIQUE,
description VARCHAR(200)
);
CREATE TABLE user_roles (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
role_id BIGINT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (role_id) REFERENCES roles(id),
UNIQUE KEY unique_user_role (user_id, role_id)
);
CREATE INDEX idx_users_username ON users(username);
CREATE INDEX idx_users_email ON users(email);

When to Use It

Spring CRUD Generator is perfect for:

  • New projects starting from scratch
  • Proof of concepts that need quick API backends
  • Standard CRUD applications
  • Team projects requiring consistent code structure
  • Rapid prototyping

Not ideal for complex business logic apps requiring custom architecture or legacy system integration.

Summary

In this post, I showed how to use Spring CRUD Generator v1.2.0 to automate Spring Boot backend development. The key point is it eliminates hours of boilerplate coding by generating complete CRUD backends from YAML configuration.

The generator creates production-ready code with OpenAPI documentation, database migrations, and Docker support. By leveraging YAML configuration, developers can focus on business logic rather than writing repetitive boilerplate code.

Final Words + More Resources

My intention with this article was to help others share my knowledge and experience. If you want to contact me, you can contact by email: Email me

Here are also the most important links from this article along with some further resources that will help you in this scope:

Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!

Comments