0% found this document useful (0 votes)
2 views13 pages

Module7 Assignment PromptLibrary

The document outlines a Module 7 assignment for a course on prompt engineering in backend/API development using Java/Kotlin and Spring. It includes five annotated prompts focusing on code generation, code review, debugging, and performance analysis, each with specific roles, contexts, tasks, constraints, and output formats. The assignment emphasizes the importance of constraints to avoid common failure patterns in software development.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Module7 Assignment PromptLibrary

The document outlines a Module 7 assignment for a course on prompt engineering in backend/API development using Java/Kotlin and Spring. It includes five annotated prompts focusing on code generation, code review, debugging, and performance analysis, each with specific roles, contexts, tasks, constraints, and output formats. The assignment emphasizes the importance of constraints to avoid common failure patterns in software development.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Module 7 Assignment — Your Personal Prompt Library: 5 Annotated

Prompts
Course: Vibe Coding with Claude + Cursor Module: 7 — Prompt Engineering for Builders
Domain: Backend / API Development — Java / Kotlin + Spring Date: 2 July 2026 Status:
Submitted

DELIVERABLE 1 — Five Annotated Prompts

PROMPT 1 — Category A: Code Generation


Task: Create a paginated REST endpoint in Spring Boot

ROLE: You are a senior Java backend engineer specialising in Spring Boot REST API design,
with a focus on clean architecture, input validation, and performance.
CONTEXT: This is a Spring Boot 3.2 + Java 21 project using Spring Data JPA with Hibernate,
PostgreSQL 16, and Maven. The project follows a layered architecture: Controller → Service
→ Repository. DTOs are used for all API responses — entities are never exposed directly.
Validation uses [Link] annotations. The existing pattern for paginated
responses uses a generic PageResponse<T> wrapper class at
[Link].

TASK: Create a paginated GET /api/v1/orders endpoint that returns a list of orders for
the authenticated user. The endpoint must: - Accept query parameters: page (default 0),
size (default 20, max 100), status (optional, enum: PENDING / CONFIRMED /
CANCELLED) - Return a PageResponse<OrderSummaryDTO> where OrderSummaryDTO
contains: id, createdAt, status, totalAmount - Filter by the authenticated user’s ID
extracted from the Spring Security context - Filter by status if provided
CONSTRAINTS: - Do NOT expose the Order entity directly — use OrderSummaryDTO only
- Do NOT write raw JPQL or native SQL — use Spring Data JPA Specification or derived
query methods - Do NOT exceed size = 100 — throw a 400 Bad Request if the client
requests more - Follow the existing PageResponse<T> wrapper — do not create a new
response structure - Authentication context comes from SecurityContextHolder — do
not add a new auth mechanism
OUTPUT FORMAT: Produce four complete files with no placeholders: 1.
[Link] — REST controller with the endpoint 2. [Link] —
service layer with filtering and pagination logic 3. [Link] — DTO record
with all fields 4. [Link] — JPA Specification for status filtering
Include Javadoc on all public methods. Use Java records for the DTO.

ANNOTATION:
Primary component emphasised: Constraints — the most critical risk on this task was AI
exposing the entity directly or writing raw SQL. Three hard constraints explicitly block
these: no direct entity exposure, no raw SQL, and no new response wrappers. Without
them, AI would default to the simplest approach, which often skips the DTO layer entirely.
Failure pattern avoided: Failure Pattern #3 — Missing negative constraint. Without
explicit DO NOT statements, AI would almost certainly return the Order entity directly and
write a native JPQL query, both of which violate the project’s architecture conventions.

PROMPT 2 — Category A: Code Generation


Task: Create a Spring Security JWT authentication filter

ROLE: You are a senior Java security engineer specialising in Spring Security and stateless
JWT authentication. Your primary concern is correctness and attack-surface reduction, not
brevity.
CONTEXT: This is a Spring Boot 3.2 + Spring Security 6 project using Java 21. The project is
stateless — no sessions, no HttpSession. JWT tokens are signed with HS256 using a
secret from the JWT_SECRET environment variable. Token expiry is 8 hours. A JwtService
class already exists at [Link] with two methods:
extractUsername(String token): String and isTokenValid(String token,
UserDetails userDetails): boolean. UserDetailsService is implemented at
[Link].

TASK: Create a JwtAuthenticationFilter that extends OncePerRequestFilter. The


filter must: - Extract the JWT from the Authorization: Bearer <token> header - If no
header or header does not start with Bearer, skip filtering and call
[Link]() - Extract the username using
[Link]() - Load UserDetails via UserDetailsServiceImpl
- Validate the token using [Link]() - On valid token, create a
UsernamePasswordAuthenticationToken and set it in SecurityContextHolder - On
any exception during token processing, clear the SecurityContext and continue the filter
chain (do not throw)
CONSTRAINTS: - CRITICAL: Do NOT log the token value at any log level — log only the
username - CRITICAL: Do NOT store anything in HttpSession - Do NOT call JwtService
more than once per request for the same operation - Do NOT add @Component — the filter
will be registered manually in SecurityConfig - Do NOT catch
UsernameNotFoundException silently — log it at WARN level with the message only
OUTPUT FORMAT: Return one complete Java file: [Link].
Include Javadoc. No placeholders. No TODOs. Complete implementation only.

ANNOTATION:
Primary component emphasised: Role + Constraints together. Security prompts need
both: the role activates a security-first decision frame, and the CRITICAL-marked
constraints enforce the two most dangerous failure modes — token leakage in logs and
session storage. The role alone is not enough; without explicit CRITICAL constraints, AI
may still log the token for debugging purposes.
Failure pattern avoided: Failure Pattern #4 — No role. A generic “create a JWT filter”
prompt without a security engineer role would produce functional but insecure code —
most likely logging full token values and missing the SecurityContext clearing on
exceptions.

PROMPT 3 — Category B: Code Review


Task: Security and correctness review of a Spring REST controller

ROLE: You are a senior Java security engineer conducting a code review. Your focus is
security vulnerabilities and correctness issues only. Do not comment on code style, naming
conventions, formatting, or test coverage unless a style issue directly creates a security
risk.
CONTEXT: This is a Spring Boot 3.2 REST API. The controller handles user account
management (update profile, change password, delete account). The app uses Spring
Security with JWT auth. The authenticated user’s ID is available via
SecurityContextHolder.

TASK: Review the following controller code for: 1. Security vulnerabilities (auth bypass,
privilege escalation, mass assignment, sensitive data exposure) 2. Correctness issues
(missing null checks, incorrect HTTP status codes, unhandled exceptions) 3. Spring-specific
anti-patterns (direct entity mutation in controller, missing @Transactional, N+1 risks)
For each issue found, provide: - Location: method name and line reference - Issue: one-
sentence description of the problem - Severity: Critical / High / Medium / Low - Fix: a
specific corrected code snippet (not a description — actual code)
CODE TO REVIEW:
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
@Autowired
private UserRepository userRepository;

@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id,
@RequestBody User user) {
User existing = [Link](id).get();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link](existing);
return [Link](existing);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
[Link](id);
return [Link]().build();
}

@PostMapping("/{id}/change-password")
public ResponseEntity<Void> changePassword(@PathVariable Long id,
@RequestBody String
newPassword) {
User user = [Link](id).get();
[Link](newPassword);
[Link](user);
return [Link]().build();
}
}

CONSTRAINTS: - Review security and correctness only — do not suggest renaming


variables or reformatting - Do not rewrite the entire class — provide targeted fixes per
issue - Rate each issue before suggesting the fix
OUTPUT FORMAT: Numbered list of issues. Each issue: Location / Issue / Severity / Fix
code snippet. End with a one-paragraph summary of the highest-priority action to take
first.

ANNOTATION:
Primary component emphasised: Output format. A code review prompt without a defined
output format produces a narrative essay that is hard to act on. Specifying Location /
Issue / Severity / Fix creates a structured, scannable review where each finding
maps directly to an actionable change.
Failure pattern avoided: Failure Pattern #2 — No output format specified. Without
format constraints, AI defaults to flowing prose interspersed with code snippets —
readable but not directly actionable. The structured format makes this suitable for direct
use in a PR review comment or a Jira ticket.

PROMPT 4 — Category B: Code Review


Task: Performance review of a Spring Data JPA repository layer

ROLE: You are a senior Java performance engineer specialising in Hibernate and Spring
Data JPA query optimisation. Focus exclusively on query performance, N+1 problems,
missing indexes, and fetch strategy issues. Ignore business logic correctness and code style.
CONTEXT: This is a Spring Boot 3.2 application with PostgreSQL 16. Hibernate is the JPA
provider. The application serves up to 10,000 concurrent users. The Order entity has the
following relationships: @ManyToOne to User, @OneToMany to List<OrderItem>, and
@ManyToOne to Address. All relationships default to [Link] as currently
configured. The service layer calls repository methods and maps results to DTOs before
returning to the controller.
TASK: Review the following repository and service code for: 1. N+1 query problems 2.
Incorrect fetch type configurations for the load patterns shown 3. Missing @Query
optimisations (JOIN FETCH where appropriate) 4. Any Hibernate anti-patterns that will
degrade at 10,000 concurrent users
For each issue: Location / Problem / Performance Impact (High/Medium/Low) / Fix with
code.
CODE TO REVIEW:
// Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByUserId(Long userId);
List<Order> findByStatus(OrderStatus status);
}

// Service
public List<OrderDTO> getOrdersForUser(Long userId) {
List<Order> orders = [Link](userId);
return [Link]()
.map(order -> new OrderDTO(
[Link](),
[Link]().getName(),
[Link]().size(),
[Link]().getStreet()
))
.map(this::toDTO)
.collect([Link]());
}
CONSTRAINTS: - Do NOT suggest switching to a different ORM or framework - Do NOT
suggest application-level caching as the primary fix — fix the queries first - Fixes must use
Spring Data JPA @Query with JPQL or @EntityGraph — no native SQL - Do not rewrite
business logic — only the data access layer
OUTPUT FORMAT: Numbered findings with Location / Problem / Impact / Fix. End with a
recommended @Query rewrite for the most critical finding, ready to paste into the
repository interface.

ANNOTATION:
Primary component emphasised: Role + Constraints. The performance engineer role
focuses AI away from business logic and toward query analysis. The constraints are equally
important: without “do NOT suggest caching as the primary fix,” AI almost always leads
with Redis as the solution — which defers rather than fixes the underlying N+1 problem.
Failure pattern avoided: Failure Pattern #7 — Asking AI to make architecture
decisions. Without constraints, AI would suggest migrating to a reactive stack, adding a
caching layer, or switching to native queries — all architectural decisions that belong to the
team. The constraints keep AI’s output within the scope of actionable JPA-level fixes.

PROMPT 5 — Category E: Debugging


Task: Diagnose a Spring Boot application startup failure

ROLE: You are a senior Java debugging engineer specialising in Spring Boot application
context failures, dependency injection errors, and classpath issues. Approach this as a
systematic diagnosis, not a guess.
CONTEXT: This is a Spring Boot 3.2 + Java 21 application using Spring Security 6, Spring
Data JPA, and Flyway for database migrations. The app was working correctly on the main
branch. After merging a feature branch that added a new AuditService bean and a new
Flyway migration (V5__add_audit_table.sql), the application fails to start. The failure
occurs during Spring context initialisation — the app never reaches the main method’s
server start. PostgreSQL is running and reachable. No code changes were made to existing
Security or JPA configuration.
TASK: Analyse the following stack trace and diagnose: 1. The root cause of the startup
failure (not symptoms — the underlying cause) 2. Which specific change (AuditService
bean or Flyway migration) is most likely responsible 3. The exact fix — file name, line, and
corrected code or configuration
STACK TRACE TO ANALYSE:
***************************
APPLICATION FAILED TO START
***************************

Description:
The dependencies of some of the beans in the application context form
a cycle:

auditService -> userRepository -> jpaRepositoriesAutoConfiguration



securityConfig --------------------------

Action:
Relying upon circular references is discouraged and...

Caused by:
[Link]:
Error creating bean with name 'auditService':
Requested bean is currently in creation:
Is there an unresolvable circular reference?

CONSTRAINTS: - Do NOT suggest disabling [Link]-circular-


references=true — this suppresses the symptom, not the cause - Do NOT suggest a
complete rewrite of SecurityConfig — make the minimal fix only - Explain the cycle
before proposing the fix — I need to understand it, not just apply a patch
OUTPUT FORMAT: 1. Cycle explanation: describe the dependency chain causing the cycle
in plain English (2–3 sentences) 2. Root cause: one sentence identifying the specific code
pattern that created the cycle 3. Fix: the exact code change with before/after snippet 4.
Verification: one sentence describing how to confirm the fix worked without restarting
the full app

ANNOTATION:
Primary component emphasised: Task structure + Constraints. Debugging prompts are
high-risk for the “suppress not fix” pattern — AI’s easiest answer for a circular dependency
is always allow-circular-references=true. The explicit CRITICAL-equivalent
constraint ruling this out forces AI to diagnose correctly. The four-part output format (cycle
→ root cause → fix → verification) mirrors a real debugging workflow and prevents AI from
jumping straight to a patch.
Failure pattern avoided: Failure Pattern #1 — Too vague. “Why won’t my Spring app
start?” with a stack trace produces a generic explanation of circular dependencies. Adding
the full context (what changed, what didn’t change, what’s running) lets AI pinpoint the
specific cause rather than explaining the general concept.
DELIVERABLE 2 — Prompt Library Starter File

# MY PROMPT LIBRARY
# Owner: [Your Name]
# Domain: Backend API Development — Java / Kotlin + Spring Boot
# Last updated: 2 July 2026

TEMPLATE 1: Code Generation — Paginated Spring REST Endpoint


Works with: Claude + Cursor Composer Tags: java, spring-boot, rest-api, pagination, jpa,
dto
ROLE:
You are a senior Java backend engineer specialising in Spring Boot
REST API
design, with a focus on clean architecture, input validation, and
performance.

CONTEXT:
This is a Spring Boot [VERSION] + Java [JAVA_VERSION] project using
Spring Data
JPA with Hibernate, PostgreSQL [PG_VERSION], and Maven. Layered
architecture:
Controller → Service → Repository. DTOs for all responses — entities
never
exposed. Validation uses [Link]. Paginated responses use
PageResponse<T> at [PAGERESPONSE_PACKAGE].

TASK:
Create a paginated GET /api/v1/[RESOURCE] endpoint that returns
[DESCRIPTION].
Accept query parameters: page (default 0), size (default 20, max 100),
[OPTIONAL_FILTER] (optional, enum: [ENUM_VALUES]).
Return PageResponse<[DTO_NAME]> where [DTO_NAME] contains:
[DTO_FIELDS].
Filter by authenticated user's ID from SecurityContextHolder.

CONSTRAINTS:
- Do NOT expose the [ENTITY] entity directly — use [DTO_NAME] only
- Do NOT write raw JPQL or native SQL — use JPA Specification or
derived queries
- Do NOT exceed size = 100 — throw 400 Bad Request if exceeded
- Follow existing PageResponse<T> wrapper — do not create a new
structure
- Auth context from SecurityContextHolder — do not add a new mechanism

OUTPUT FORMAT:
Four complete files, no placeholders:
1. [ENTITY][Link]
2. [ENTITY][Link]
3. [DTO_NAME].java (Java record)
4. [ENTITY][Link]
Include Javadoc on all public methods.

ANNOTATION: Primary component: Constraints Failure pattern avoided: #3 — Missing


negative constraint (prevents entity exposure and raw SQL) When to use this template:
Any new paginated list endpoint in a Spring Boot layered-architecture project

TEMPLATE 2: Code Generation — Spring Security JWT Authentication Filter


Works with: Claude + Cursor Composer Tags: java, spring-security, jwt, security, filter,
authentication
ROLE:
You are a senior Java security engineer specialising in Spring
Security 6
and stateless JWT authentication.

CONTEXT:
Spring Boot [VERSION] + Spring Security 6 + Java [JAVA_VERSION].
Stateless —
no sessions. JWT signed with HS256 from JWT_SECRET env variable.
Expiry: [EXPIRY_HOURS] hours. JwtService at [JWTSERVICE_PACKAGE]
provides:
extractUsername(token): String and isTokenValid(token, userDetails):
boolean.
UserDetailsService implemented at [USERDETAILSSERVICE_PACKAGE].

TASK:
Create a JwtAuthenticationFilter extending OncePerRequestFilter.
Extract JWT from Authorization: Bearer header. Skip if
missing/malformed.
Validate via JwtService. Set UsernamePasswordAuthenticationToken in
SecurityContextHolder on success. On any exception, clear
SecurityContext
and continue chain.

CONSTRAINTS:
- CRITICAL: Do NOT log the token value at any log level — log username
only
- CRITICAL: Do NOT store anything in HttpSession
- Do NOT call JwtService more than once per request per operation
- Do NOT add @Component — filter registered manually in SecurityConfig
- Log UsernameNotFoundException at WARN level — do not swallow
silently
OUTPUT FORMAT:
One complete Java file: [Link]
Javadoc included. No placeholders. No TODOs. Complete implementation.

ANNOTATION: Primary component: Role + Constraints Failure pattern avoided: #4 — No


role (security role prevents token logging and session storage mistakes) When to use this
template: Any new JWT filter in a stateless Spring Security 6 project

TEMPLATE 3: Code Review — Spring REST Controller Security and Correctness


Works with: Claude Tags: java, spring-boot, security, code-review, rest-controller
ROLE:
You are a senior Java security engineer conducting a code review.
Focus: security vulnerabilities and correctness issues ONLY.
Do not comment on style, naming, or formatting.

CONTEXT:
Spring Boot [VERSION] REST API. [DESCRIBE_CONTROLLER_PURPOSE].
Spring Security with JWT auth. Authenticated user available via
SecurityContextHolder. [ANY_RELEVANT_EXISTING_PATTERNS].

TASK:
Review the following controller code for:
1. Security vulnerabilities (auth bypass, privilege escalation,
mass assignment, sensitive data exposure)
2. Correctness issues (null checks, HTTP status codes, unhandled
exceptions)
3. Spring anti-patterns (entity mutation in controller, missing
@Transactional)

For each issue:


- Location: method name and line reference
- Issue: one-sentence description
- Severity: Critical / High / Medium / Low
- Fix: specific corrected code snippet

<code>
[PASTE CONTROLLER CODE HERE]
</code>

CONSTRAINTS:
- Security and correctness only — no style suggestions
- Targeted fixes per issue — do not rewrite the entire class
- Rate each issue before the fix

OUTPUT FORMAT:
Numbered list: Location / Issue / Severity / Fix code.
End with one paragraph: highest-priority action to take first.

ANNOTATION: Primary component: Output format Failure pattern avoided: #2 — No


output format specified (structured format makes findings directly actionable) When to use
this template: Pre-merge security review of any Spring REST controller touching user data
or auth

TEMPLATE 4: Code Review — Spring Data JPA Performance Review


Works with: Claude Tags: java, jpa, hibernate, performance, n+1, spring-data
ROLE:
You are a senior Java performance engineer specialising in Hibernate
and
Spring Data JPA query optimisation. Focus: query performance, N+1
problems,
fetch strategy issues only. Ignore business logic and code style.

CONTEXT:
Spring Boot [VERSION] + PostgreSQL [PG_VERSION]. Hibernate JPA
provider.
Expected concurrent users: [USER_SCALE]. Key entity relationships:
[DESCRIBE_ENTITY_RELATIONSHIPS_AND_FETCH_TYPES].
Service maps results to DTOs before returning to controller.

TASK:
Review repository and service code for:
1. N+1 query problems
2. Incorrect fetch type configurations
3. Missing @Query optimisations (JOIN FETCH)
4. Hibernate anti-patterns at [USER_SCALE] concurrent users

For each issue: Location / Problem / Impact (High/Medium/Low) / Fix


with code.

<code>
[PASTE REPOSITORY AND SERVICE CODE HERE]
</code>

CONSTRAINTS:
- Do NOT suggest switching ORM or framework
- Do NOT suggest caching as the primary fix — fix queries first
- Fixes must use @Query with JPQL or @EntityGraph — no native SQL
- Do not rewrite business logic — data access layer only

OUTPUT FORMAT:
Numbered findings: Location / Problem / Impact / Fix.
End with recommended @Query rewrite for the most critical finding,
ready to paste into the repository interface.

ANNOTATION: Primary component: Role + Constraints Failure pattern avoided: #7 — AI


making architecture decisions (constraints prevent Redis/migration suggestions) When to
use this template: Performance review of any JPA repository layer before load testing or
production release

TEMPLATE 5: Debugging — Spring Boot Application Startup Failure


Works with: Claude Tags: java, spring-boot, debugging, circular-dependency, startup,
context
ROLE:
You are a senior Java debugging engineer specialising in Spring Boot
application context failures, dependency injection errors, and
classpath
issues. Diagnose systematically — do not guess.

CONTEXT:
Spring Boot [VERSION] + Java [JAVA_VERSION]. Stack:
[LIST_KEY_DEPENDENCIES].
The app was working on [WORKING_BRANCH/STATE]. After
[DESCRIBE_CHANGE_MADE],
the application fails to start during Spring context initialisation.
[WHAT_IS_CONFIRMED_WORKING — e.g., DB is reachable, config is
unchanged].

TASK:
Analyse the following stack trace and diagnose:
1. Root cause of the startup failure (not symptoms — the underlying
cause)
2. Which specific change is most likely responsible
3. The exact fix — file name, line, and corrected code or
configuration

<stack_trace>
[PASTE FULL STACK TRACE HERE]
</stack_trace>

CONSTRAINTS:
- Do NOT suggest [Link]-circular-references=true — symptom
suppression only
- Do NOT suggest a complete rewrite — minimal fix only
- Explain the cycle/error before proposing the fix

OUTPUT FORMAT:
1. Explanation: describe the failure chain in plain English (2–3
sentences)
2. Root cause: one sentence identifying the specific code pattern
3. Fix: before/after code snippet
4. Verification: one sentence on how to confirm the fix without full
restart

ANNOTATION: Primary component: Task structure + Constraints Failure pattern avoided:


#1 — Too vague (full context prevents generic explanation; constraint blocks the easy
wrong answer) When to use this template: Any Spring Boot startup failure involving
BeanCreationException, circular dependencies, or context initialisation errors

Module 7 Assignment — Vibe Coding with Claude + Cursor | TalentLMS Edition

You might also like