Scrivio Interview library
ScenarioFoundations7 min read · updated 12 November 2026

You use an AI coding assistant to write a Spring Data repository and a service method. What do you check before committing the generated code?

We check generated code the way we would check a colleague's, only more carefully: compile it, run the tests and read every line, because assistants can invent methods or use outdated APIs such as javax instead of jakarta packages. Then we look for security problems (injection in native queries, missing authorization checks, secrets in code), performance problems (N+1 queries, missing pagination, loading whole tables), and large verbatim snippets of unknown origin. Finally we write or extend tests for the behaviour itself, not just accept generated tests that mirror the implementation.

Why this question is asked

AI coding assistants are very good at producing a Spring Data repository and a service method in seconds, and the result usually looks right. That is exactly the danger: code that looks right gets less scrutiny, and the problems in generated code are often the quiet kind, a query that is fine on 100 test rows and takes down the database on 10 million, or a method that returns any customer's orders to any logged-in user. Interviewers ask this to see whether we take ownership of what we commit. In this answer, we will take a realistic generated example and walk through the checks in order: correctness, security, performance, provenance and tests, fixing each problem as we find it.

1A Realistic Generated Example

Suppose we asked the assistant for a repository and a service method that returns a customer's recent orders with their item counts, and a search by customer name. It produced the following. It compiles in the assistant's imagination, and some of it may even pass a quick manual test.

Java
import javax.persistence.EntityManager; // problem 1: javax, not jakarta
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByCustomerIdOrderByCreatedAtDescLimit(Long id); // problem 2: not a valid derived query
}
@Service
class OrderService {
@Autowired OrderRepository repo;
@Autowired EntityManager em;
private static final String API_KEY = "sk-live-..."; // problem 3: secret in code
List<OrderDto> recentOrders(Long customerId) {
return repo.findAll().stream() // problem 4: loads the whole table
.filter(o -> o.getCustomer().getId().equals(customerId)) // problem 5: lazy load per order (N+1)
.map(o -> new OrderDto(o.getId(), o.getItems().size())) // problem 5 again: items per order
.toList();
}
List<Order> searchByName(String name) {
return em.createNativeQuery(
"SELECT * FROM orders o JOIN customer c ON c.id = o.customer_id WHERE c.name = '" + name + "'",
Order.class).getResultList(); // problem 6: SQL injection
}
// problem 7: no check that the caller may see this customer's orders
}

2Check 1: Does It Compile, Run and Do What It Says?

The first check is mechanical: build it and run the existing tests. In Spring Boot 3 and later, JPA lives in the jakarta.persistence package; javax.persistence imports come from older examples the assistant learned from, and they will not compile against a current Hibernate. The derived query method name is also invented: Spring Data understands findFirst10By or findTop10By, not a Limit suffix like this, so the application fails at startup when Spring parses the repository.

Then we read the code line by line. Assistants confidently use methods that do not exist, mix APIs from different library versions, or handle the happy path only. Reading is not optional; if we cannot explain a line, we should not commit it.

3Check 2: Security

Three security problems are in this code, and all three are common in generated code. The native query builds SQL by concatenating the user-supplied name, so a name such as x' OR '1'='1 returns every order in the database. The fix is always parameter binding. A live API key is hard-coded in the class, which means it is now in the Git history; it belongs in configuration from a secret store, and if it was ever pushed, it must be rotated. And nothing checks that the logged-in user may see the requested customer's orders, so any user could request any customer id, an insecure direct object reference.

Assistants generate what we ask for, and we rarely ask for authorization, so it is usually missing. Reviewing generated code means asking explicitly: who is allowed to call this, and where is that enforced?

4Check 3: Performance

The recentOrders method calls findAll(), which loads every order in the table into memory and then filters in Java. On a development database with 50 rows it is instant; in production with millions of rows it exhausts memory. Inside the loop, o.getCustomer() and o.getItems() are lazy associations, so each access fires another query: one query for the orders plus two per order, the N+1 problem. There is also no limit or pagination, so even a correct query could return thousands of rows.

The fix moves the filtering, sorting and limiting into the database, and fetches only what the DTO needs. A JPQL constructor expression with a count does it in one query.

Java
import jakarta.persistence.*; // fixed package
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("""
select new com.example.OrderDto(o.id, count(i))
from Order o left join o.items i
where o.customer.id = :customerId
group by o.id, o.createdAt
order by o.createdAt desc""")
List<OrderDto> recentOrders(@Param("customerId") Long customerId, Pageable page);
@Query(value = "SELECT o.* FROM orders o JOIN customer c ON c.id = o.customer_id WHERE c.name = :name",
nativeQuery = true)
List<Order> searchByName(@Param("name") String name, Pageable page); // bound parameter, no injection
}
@Service
class OrderService {
private final OrderRepository repo;
OrderService(OrderRepository repo) { this.repo = repo; }
@PreAuthorize("@access.canViewCustomer(authentication, #customerId)") // only allowed callers
List<OrderDto> recentOrders(Long customerId) {
return repo.recentOrders(customerId, PageRequest.of(0, 20)); // 1 query, at most 20 rows
}
}

Notice that every problem from the generated version has a specific fix: jakarta imports, a query Spring Data can actually run, parameter binding, no secret in the class, the database doing the filtering with a single query and a page of 20, and an explicit authorization rule. Native queries with Pageable need care with sorting and counting, so check your Spring Data version's documentation.

5Check 4: Where Did This Code Come From?

For a repository like this, provenance is rarely an issue, since it is ordinary code. But assistants can reproduce larger snippets close to code they were trained on, including code under licences that impose obligations, such as copyleft licences. When a generated block is long, unusually specific or contains distinctive comments, we treat it as code of unknown origin: we do not paste large verbatim pieces we cannot account for, and we follow the company's policy, which may include licence-scanning tools or assistant settings that block suggestions matching public code.

6Check 5: Tests That Check Behaviour

Assistants are happy to generate tests too, but generated tests often mirror the implementation: they mock the repository to return a list and assert that the service returns the same list. Such a test passes for the broken version above. What we need are tests of the behaviour we care about: with a real database (for example PostgreSQL in Testcontainers), only the requested customer's orders come back, newest first, at most 20, item counts are right, a name containing a quote does not break the query, and a user without access is refused.

A useful habit is to write or at least outline these tests before accepting the generated code. If the tests describe the behaviour, the generated implementation has to earn its place.

Review checklist for generated data-access code
AreaWhat to look forFix in our example
CorrectnessInvented methods, javax imports, startup errorsjakarta imports, valid query method
SecurityString-built SQL, secrets, missing authorizationBound parameters, secret store, @PreAuthorize
PerformancefindAll(), N+1 lazy loads, no pagingOne JPQL query with count and Pageable
ProvenanceLong verbatim blocks of unknown originRewrite or check licence policy
TestsTests that mirror the implementationBehaviour tests with a real database

7Follow-up questions

How do you detect N+1 queries in a review?

By reading for lazy associations accessed in loops, and by measuring: enabling Hibernate statistics or SQL logging in a test and asserting the number of statements, or using a library that counts queries. A test that asserts one query for the recent-orders call stops the problem coming back.

Is it acceptable to commit generated code at all?

Yes, if we own it. The rule is the same as for any code: the author understands every line, it passes review and tests, and it meets our security and quality standards. Who or what typed it does not change who is responsible.

What prompt would have produced better code?

One that states the context: Spring Boot 3 with jakarta packages, PostgreSQL, results must be paginated, parameters bound, the caller's access checked, and tests with Testcontainers. Better prompts help, but they never replace the review.

8Conclusion

In this answer, we reviewed a generated Spring Data repository and service and found the typical problems: javax imports and an invented query method, SQL injection in a native query, a hard-coded secret, missing authorization, findAll() with in-memory filtering, N+1 lazy loading and no pagination. We fixed each one, considered where long verbatim snippets come from, and wrote behaviour tests against a real database rather than accepting tests that mirror the implementation.

What to say in the interviewAbout 90 seconds aloud

Open with

I treat generated code as if a new colleague wrote it, and I own every line I commit. First correctness: I compile it and run the tests, then read each line, because assistants invent methods and use outdated APIs, for example javax.persistence imports where Spring Boot 3 needs jakarta, or derived query names Spring Data cannot parse.

Then, if they want more

Second security: I look for string-concatenated SQL in native queries and replace it with bound parameters, check that no secrets are hard-coded, and ask who is allowed to call the method, because generated code almost never includes an authorization check, so I add one, for example with @PreAuthorize.

Third performance: I look for findAll followed by filtering in Java, lazy associations accessed in loops that cause N+1 queries, and missing pagination, and I push the filtering, sorting and limits into one query with a Pageable.

Fourth provenance: if a block is long and very specific, I do not paste it verbatim without knowing where it came from, and I follow our licence policy. Finally tests: I do not just accept generated tests that mock the repository and mirror the implementation.

I write behaviour tests, ideally against PostgreSQL in Testcontainers, for the right rows, ordering, page size, a name with a quote in it, and an unauthorized caller.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring AI reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You use an AI coding assistant to write a Spring Data repository and a service method....": https://scrivio-interview-library.netlify.app/spring-boot/llm-fundamentals/c4a97fc97e/