15 Prompts for Java Developers: From Legacy Code to High-Load Microservices

When I first tried using neural networks to write code, I thought it was just a toy for generating hello world. But after I used prompts to refactor a legacy project on Java 8, I realized: this is a tool that really saves hours. In this article, I've collected 15 proven prompts that will help you go from idea to production, using Spring Boot, microservices, and optimization. Each prompt is accompanied by an example and an explanation of how to adapt it to your task.

1. Generate a CRUD Controller in Minutes

Task: Create a REST controller for the User entity with basic operations.

Prompt:

Generate a Spring Boot controller for the User entity with fields id, name, email. Include methods GET /users, GET /users/{id}, POST /users, PUT /users/{id}, DELETE /users/{id}. Use ResponseEntity for error handling and validation via @Valid.

Example result:

@RestController
@RequestMapping("/users")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return userService.findById(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
        User saved = userService.save(user);
        return ResponseEntity.status(HttpStatus.CREATED).body(saved);
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @Valid @RequestBody User user) {
        return userService.update(id, user)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.delete(id);
        return ResponseEntity.noContent().build();
    }
}

Why it works: The prompt sets the structure and expectations; the neural network generates boilerplate code that you can adapt to your logic.

2. Designing a Database Schema

Task: Design a schema for an online store with relationships.

Prompt:

Create a database schema for an online store with tables: Product, Category, Order, OrderItem. Specify fields, types, constraints (PRIMARY KEY, FOREIGN KEY, NOT NULL). Use PostgreSQL syntax.

Example result:

CREATE TABLE category (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL UNIQUE
);

CREATE TABLE product (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    price NUMERIC(10, 2) NOT NULL CHECK (price > 0),
    category_id INTEGER NOT NULL REFERENCES category(id)
);

CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE order_item (
    id SERIAL PRIMARY KEY,
    order_id INTEGER NOT NULL REFERENCES orders(id),
    product_id INTEGER NOT NULL REFERENCES product(id),
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    price NUMERIC(10, 2) NOT NULL
);

Tip: Specify the DBMS you are using in the prompt to get accurate syntax.

3. Writing Unit Tests with Mockito

Task: Cover the service layer with tests.

Prompt:

Write unit tests for UserService using JUnit 5 and Mockito. Test the create, update, delete methods. Use @ExtendWith(MockitoExtension.class).

Example result:

@ExtendWith(MockitoExtension.class)
class UserServiceTest {
    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Test
    void createUser_shouldReturnSavedUser() {
        User user = new User("John", "john@example.com");
        when(userRepository.save(user)).thenReturn(user);

        User result = userService.create(user);

        assertNotNull(result);
        assertEquals("John", result.getName());
        verify(userRepository).save(user);
    }

    @Test
    void updateUser_shouldUpdateFields() {
        User existing = new User("John", "john@example.com");
        existing.setId(1L);
        User updated = new User("Johnny", "johnny@example.com");
        updated.setId(1L);

        when(userRepository.findById(1L)).thenReturn(Optional.of(existing));
        when(userRepository.save(existing)).thenReturn(updated);

        Optional<User> result = userService.update(1L, updated);

        assertTrue(result.isPresent());
        assertEquals("Johnny", result.get().getName());
    }

    @Test
    void deleteUser_shouldCallDelete() {
        userService.delete(1L);
        verify(userRepository).deleteById(1L);
    }
}

Important: Tests are not a luxury but a necessity. Prompts help quickly generate test scenarios, but don't forget to adapt them to your cases.

4. Refactoring Legacy Code

Task: Improve readability and structure of old code.

Prompt:

Refactor the following code: [insert code]. Break into methods, use Stream API, avoid duplication. Explain the changes.

Example result:
Before:

List<String> names = new ArrayList<>();
for (User user : users) {
    if (user.getAge() > 18) {
        names.add(user.getName().toUpperCase());
    }
}

After:

List<String> names = users.stream()
        .filter(user -> user.getAge() > 18)
        .map(user -> user.getName().toUpperCase())
        .collect(Collectors.toList());

Why it's useful: The prompt allows you to quickly get clean code, but always check the logic.

5. Optimizing SQL Queries

Task: Find and fix slow queries.

Prompt:

Explain why the following query is slow: [insert SQL]. Suggest optimizations: indexes, rewriting, using EXISTS instead of IN.

Example result:
For the query:

SELECT * FROM orders WHERE user_id IN (SELECT id FROM users WHERE name = 'John');

Optimized version:

SELECT o.* FROM orders o JOIN users u ON o.user_id = u.id WHERE u.name = 'John';

Tip: Use EXPLAIN ANALYZE to verify.

6. Writing a Dockerfile for Spring Boot

Task: Create a Dockerfile for multi-stage build.

Prompt:

Create a Dockerfile for a Spring Boot application using multi-stage build: first stage - build with Maven, second - run with JRE. Use OpenJDK 17.

Example result:

FROM maven:3.8.4-openjdk-17 AS build
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn clean package -DskipTests

FROM openjdk:17-jre-slim
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

Note: Make sure the versions match your project.

7. Creating a Microservice with Spring Cloud

Task: Generate a microservice skeleton with Eureka registration.

Prompt:

Create a Spring Boot application with dependencies: spring-cloud-starter-netflix-eureka-client, spring-boot-starter-web. Add configuration for connecting to Eureka.

Example result:
File application.yml:

spring:
  application:
    name: user-service
server:
  port: 8081
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

8. Generating Docker Compose for a Stack

Task: Create docker-compose for an application with PostgreSQL and Redis.

Prompt:

Write docker-compose.yml for a Spring Boot application, PostgreSQL 14, and Redis 7. Add healthcheck for each service.

Example result:

version: '3.8'
services:
  db:
    image: postgres:14
    environment:
      POSTGRES_DB: mydb
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U user"]
      interval: 5s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

  app:
    build: .
    ports:
      - "8080:8080"
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy

9. Writing a CI/CD Pipeline

Task: Create a GitHub Actions workflow for build and deploy.

Prompt:

Create a GitHub Actions workflow for a Java project with Maven: run tests, build JAR, publish to Docker Hub.

Example result:

name: CI/CD

on:
  push:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Set up JDK 17
        uses: actions/setup-java@v3
        with:
          java-version: '17'
      - name: Build with Maven
        run: mvn clean package
      - name: Login to DockerHub
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
      - name: Build and push Docker image
        uses: docker/build-push-action@v4
        with:
          push: true
          tags: ${{ secrets.DOCKER_USERNAME }}/my-app:latest

10. Profiling and Performance Optimization

Task: Find bottlenecks in a Java application.

Prompt:

Suggest methods for profiling a Java application with JProfiler or VisualVM. Explain how to find memory leaks and thread issues.

Example result:
Use JVisualVM to monitor heap memory, thread dumps. For leaks, analyze heap dump with Eclipse MAT.

11. Writing Asynchronous Code with CompletableFuture

Task: Implement parallel calls.

Prompt:

Write an example of using CompletableFuture to call two services in parallel and combine the results.

Example result:

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> service1.call());
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> service2.call());

String result = future1.thenCombine(future2, (r1, r2) -> r1 + r2).join();

12. Generating OpenAPI Documentation

Task: Create an OpenAPI specification for a REST API.

Prompt:

Generate an OpenAPI specification for the UserController with CRUD methods. Specify User and Error schemas.

Example result:

openapi: 3.0.0
info:
  title: User API
  version: 1.0.0
paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        email:
          type: string

13. Error and Exception Handling

Task: Create a global exception handler.

Prompt:

Create a @RestControllerAdvice to handle exceptions in Spring Boot. Include handling for ResourceNotFoundException, ValidationException, and general Exception.

Example result:

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(new ErrorResponse(ex.getMessage()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return ResponseEntity.badRequest().body(new ErrorResponse(message));
    }
}

14. Writing Migrations with Flyway

Task: Create a migration to add a table.

Prompt:

Write a SQL migration for Flyway that creates the product table if it doesn't exist.

Example result:

CREATE TABLE IF NOT EXISTS product (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    price NUMERIC(10, 2) NOT NULL
);

15. Optimizing JSON Serialization

Task: Speed up Jackson serialization.

Prompt:

How to optimize Jackson serialization in Spring Boot? Suggest settings: enabling WRITE_DATES_AS_TIMESTAMPS, using post-processing, disabling fatal issues.

Example result:
In application.properties:

spring.jackson.serialization.write-dates-as-timestamps=false
spring.jackson.deserialization.fail-on-unknown-properties=false

Conclusion

These prompts are not a silver bullet, but they really speed up routine tasks. The main thing is to always check the generated code, adapt it to your context, and use neural networks as a tool, not a replacement for thinking. Start with something simple, like generating CRUD, and gradually move to complex scenarios. Happy coding!

← All posts

Comments