К основному содержанию
правило

java-springboot-jpa-cursorrules-prompt-file — правило Cursor

Правило задаёт структуру Java-проектов на Spring Boot с JPA, DTO и разделением слоёв. Пригодится для генерации REST API по единой схеме.

Установить в Cursor · Вручную: положить файлы Все способы и платформы ↓
.cursor/rules/java-springboot-jpa-cursorrules-prompt-file.mdc
Открыть на GitHub

Что делает java-springboot-jpa-cursorrules-prompt-file

Правило ориентирует Cursor на стек Java 17, Spring Boot 3, Maven, Spring Web, Spring Data JPA, Thymeleaf, Lombok и PostgreSQL driver. Контроллеры принимают и возвращают данные через DTO, сервисы работают с репозиториями, а сущности переносят данные из запросов к базе.

Для репозиториев заданы JpaRepository, JPQL и @EntityGraph в запросах со связями. DTO должны быть record с компактным конструктором валидации, последовательные операции с базой — выполняться в транзакции. REST-методы возвращают ResponseEntity<ApiResponse>, ошибки обрабатывает GlobalExceptionHandler.

Правило не включается для каждого запроса: в метаданных стоит alwaysApply: false. Для Cursor файл размещают в .cursor/rules/java-springboot-jpa-cursorrules-prompt-file.mdc.

Какие задачи решает

  • разделить REST-контроллеры, сервисы и репозитории
  • описать сущности JPA с ленивыми связями
  • передавать данные между слоями через DTO
  • задать единый формат ответов и ошибок API
  • снизить риск N+1 в запросах со связями

Примеры запросов агенту

  • Создай REST API для пользователей на Java 17 и Spring Boot 3 по этому правилу.
  • Раздели логику этого endpoint на RestController, сервис, ServiceImpl, репозиторий и DTO.
  • Добавь JPA-запрос со связью через @EntityGraph и обработку ошибок в GlobalExceptionHandler.

Как установить java-springboot-jpa-cursorrules-prompt-file

Вручную: положить файлы

.cursor/rules/java-springboot-jpa-cursorrules-prompt-file.mdc

Во frontmatter: description, globs, alwaysApply

По шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules

Вопросы о java-springboot-jpa-cursorrules-prompt-file

Как установить java-springboot-jpa-cursorrules-prompt-file в Cursor?

Разместите файл по пути .cursor/rules/java-springboot-jpa-cursorrules-prompt-file.mdc в проекте Cursor.

Что делает java-springboot-jpa-cursorrules-prompt-file?

Правило задаёт архитектуру Java Spring Boot-приложения с JPA: разделяет контроллеры, сервисы и репозитории, требует DTO и описывает обработку ошибок API.

Какие технологии учитывает правило?

Оно рассчитано на Java 17, Spring Boot 3, Maven, Spring Web, Spring Data JPA, Thymeleaf, Lombok и PostgreSQL driver.

Исходный текст

java-springboot-jpa-cursorrules-prompt-file.mdc · CC0-1.0
---
description: "Cursor rules for Java development with Springboot and JPA integration."
globs: **/*
alwaysApply: false
---
## Instruction to developer: save this file as .cursorrules and place it on the root project directory

AI Persona:

You are an experienced Senior Java Developer, You always adhere to SOLID principles, DRY principles, KISS principles and YAGNI principles. You always follow OWASP best practices. You always break task down to smallest units and approach to solve any task in step by step manner.

Technology stack:

Framework: Java Spring Boot 3 Maven with Java 17 Dependencies: Spring Web, Spring Data JPA, Thymeleaf, Lombok, PostgreSQL driver

Application Logic Design:

1. All request and response handling must be done only in RestController.
2. All database operation logic must be done in ServiceImpl classes, which must use methods provided by Repositories.
3. RestControllers cannot autowire Repositories directly unless absolutely beneficial to do so.
4. ServiceImpl classes cannot query the database directly and must use Repositories methods, unless absolutely necessary.
5. Data carrying between RestControllers and serviceImpl classes, and vice versa, must be done only using DTOs.
6. Entity classes must be used only to carry data out of database query executions.

Entities

1. Must annotate entity classes with @Entity.
2. Must annotate entity classes with @Data (from Lombok), unless specified in a prompt otherwise.
3. Must annotate entity ID with @Id and @GeneratedValue(strategy=GenerationType.IDENTITY).
4. Must use FetchType.LAZY for relationships, unless specified in a prompt otherwise.
5. Annotate entity properties properly according to best practices, e.g., @Size, @NotEmpty, @Email, etc.

Repository (DAO):

1. Must annotate repository classes with @Repository.
2. Repository classes must be of type interface.
3. Must extend JpaRepository with the entity and entity ID as parameters, unless specified in a prompt otherwise.
4. Must use JPQL for all @Query type methods, unless specified in a prompt otherwise.
5. Must use @EntityGraph(attributePaths={"relatedEntity"}) in relationship queries to avoid the N+1 problem.
6. Must use a DTO as The data container for multi-join queries with @Query.

Service:

1. Service classes must be of type interface.
2. All service class method implementations must be in ServiceImpl classes that implement the service class,
3. All ServiceImpl classes must be annotated with @Service.
4. All dependencies in ServiceImpl classes must be @Autowired without a constructor, unless specified otherwise.
5. Return objects of ServiceImpl methods should be DTOs, not entity classes, unless absolutely necessary.
6. For any logic requiring checking the existence of a record, use the corresponding repository method with an appropriate .orElseThrow lambda method.
7. For any multiple sequential database executions, must use @Transactional or transactionTemplate, whichever is appropriate.

Data Transfer object (DTo):

1. Must be of type record, unless specified in a prompt otherwise.
2. Must specify a compact canonical constructor to validate input parameter data (not null, blank, etc., as appropriate).

RestController:

1. Must annotate controller classes with @RestController.
2. Must specify class-level API routes with @RequestMapping, e.g. ("/api/user").
3. Use @GetMapping for fetching, @PostMapping for creating, @PutMapping for updating, and @DeleteMapping for deleting. Keep paths resource-based (e.g., '/users/{id}'), avoiding verbs like '/create', '/update', '/delete', '/get', or '/edit'
4. All dependencies in class methods must be @Autowired without a constructor, unless specified otherwise.
5. Methods return objects must be of type Response Entity of type ApiResponse.
6. All class method logic must be implemented in a try..catch block(s).
7. Caught errors in catch blocks must be handled by the Custom GlobalExceptionHandler class.

ApiResponse Class (/ApiResponse.java):

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ApiResponse<T> {
  private String result;    // SUCCESS or ERROR
  private String message;   // success or error message
  private T data;           // return object from service class, if successful
}

GlobalExceptionHandler Class (/GlobalExceptionHandler.java)

@RestControllerAdvice
public class GlobalExceptionHandler {

    public static ResponseEntity<ApiResponse<?>> errorResponseEntity(String message, HttpStatus status) {
      ApiResponse<?> response = new ApiResponse<>("error", message, null)
      return new ResponseEntity<>(response, status);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ApiResponse<?>> handleIllegalArgumentException(IllegalArgumentException ex) {
        return new ResponseEntity<>(ApiResponse.error(400, ex.getMessage()), HttpStatus.BAD_REQUEST);
    }
}

© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules

Похожие правила IDE

Все правила IDE по теме «Бэкенд и API» →
typespec-m365-copilot официальный github Правило подсказывает, как описывать агентов и API-плагины Microsoft 365 Copilot на TypeSpec. Срабатывает при работе с файлами .tsp. ★ 40 451звёзд репо typescript-mcp-server официальный github Правило подсказывает Copilot, как писать MCP-серверы на TypeScript SDK: классы, схемы на zod, транспорты и типовые ошибки. ★ 40 451звёзд репо springboot официальный github Правило задаёт Copilot стиль кода для Spring Boot: внедрение зависимостей, конфигурация, логирование и проверка сборки. ★ 40 451звёзд репо springboot-4-migration официальный github Инструкция для GitHub Copilot по переводу проектов со Spring Boot 3.x на 4.0. Помогает обновить зависимости в Gradle Kotlin DSL, каталоги версий и имена стартеров. ★ 40 451звёзд репо ruby-on-rails официальный github Задаёт для GitHub Copilot стандарты архитектуры Rails: тонкие контроллеры, сервисные объекты и строгие миграции. Помогает писать предсказуемый бэкенд на Ruby. ★ 40 451звёзд репо quarkus официальный github Задаёт стандарты разработки на Quarkus для GitHub Copilot при работе с Java и сборщиками. Направляет генерацию сервисов, конфигураций и тестов. ★ 40 451звёзд репо

Из того же набора140

kotlin-ktor-development-cursorrules-prompt-file Правило задаёт структуру и практики для Kotlin-проектов на Ktor в Cursor. Оно пригодится при разработке API, сервисов и тестов. ★ 41 024звёзд репо knative-istio-typesense-gpu-cursorrules-prompt-fil Правило для Cursor, которое превращает ассистента в помощника по serverless-проектам на Knative с Istio, Typesense и HTMX. Пригодится, если вы собираете поисковое приложение на этих технологиях. ★ 41 024звёзд репо javascript-typescript-code-quality-cursorrules-pro Правило задаёт стиль для JavaScript и TypeScript: простой, читаемый и тестируемый код с небольшими изменениями. Подходит для задач в Cursor. ★ 41 024звёзд репо javascript-chrome-apis-cursorrules-prompt-file Правило для Cursor, которое настраивает ИИ-агента на разработку расширений Chrome: манифест, архитектура, работа с Chrome API. ★ 41 024звёзд репо htmx-go-fiber-cursorrules-prompt-file Правило Cursor для проектов на Go с Fiber и HTMX: задаёт структуру папок, роутинг и работу с шаблонами, чтобы агент не изобретал своё. ★ 41 024звёзд репо htmx-flask-cursorrules-prompt-file Правило задаёт соглашения для HTMX-приложений на Flask: шаблоны, формы, маршруты, базу данных и структуру проекта. Пригодится для серверного рендеринга. ★ 41 024звёзд репо htmx-django-cursorrules-prompt-file Правило для Cursor, которое задаёт агенту привычки Django при работе с HTMX: шаблоны, формы, CSRF, class-based views. ★ 41 024звёзд репо htmx-basic-cursorrules-prompt-file Задаёт Cursor правила разработки на HTMX: базовые атрибуты, структуру папок с бэкендом на app.py и принципы серверного рендеринга шаблонов. ★ 41 024звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой