Skip to lesson

Practice: Java Backend Interview Drill

A backend technical round mixes everything: quick questions on REST, Spring, JPA, SQL, security and testing, a few SQL queries, buggy snippets to fix and one request to walk through aloud. The interviewer checks that you answer crisply and can connect the layers. Say each answer out loud first, then check it.

Round 1: rapid-fire backend questions

Rapid-fire rounds reward short, exact answers: a one-sentence definition, one detail that shows depth, then stop. Name the layers in order: controller, service, repository.

Java
@RestController @RequestMapping("/api/v1/orders")class OrderController {    private final OrderService service;    OrderController(OrderService service) { this.service = service; }
    @PostMapping    ResponseEntity<OrderResponse> place(@Valid @RequestBody PlaceOrderRequest request) {        OrderResponse created = service.place(request);        return ResponseEntity.created(URI.create("/api/v1/orders/" + created.id())).body(created);    }}@Service class OrderService { @Transactional OrderResponse place(PlaceOrderRequest r) { /* rules + repositories */ } }interface OrderRepository extends JpaRepository<Order, Long> { }

Your one-line answers, topic by topic:

  • REST: PUT replaces, PATCH changes part; GET, PUT and DELETE are idempotent, POST is not; create gives 201 + Location, delete gives 204.
  • Spring: IoC means the container creates and wires objects; prefer constructor injection; two beans of one type need @Primary or @Qualifier.
  • Spring Boot: starters + auto-configuration with conditions; @SpringBootApplication = configuration + auto-configuration + component scan.
  • JPA: JPA is the specification, Hibernate the implementation; to-one is EAGER by default, to-many LAZY; LazyInitializationException = lazy access after the session closed.
  • @Transactional: proxy-based, rolls back on unchecked exceptions only, skipped by self-invocation.
  • SQL and JDBC: WHERE filters rows, HAVING filters groups; indexes speed reads and slow writes; PreparedStatement stops injection.
  • Security: 401 = not authenticated, 403 = not allowed; BCrypt for passwords; a JWT is readable, signed and short-lived.
  • Testing: Mockito for unit tests, @WebMvcTest for controllers, @DataJpaTest for repositories.

Revise: REST and HTTP (opens in a new tab), Spring Boot and DI (opens in a new tab), JPA and Hibernate (opens in a new tab).

Find the bug

Review this controller

Find the line a reviewer would flag.

Which line is the injection smell?

Round 1 of 2

Round 2: three SQL queries on the ShopLite schema

The ShopLite schema has customers, products, orders and order_items. Say the tables and joins you need before you type. This example runs three classic queries on a small copy of the data.

Example 1 · Three ShopLite queries: top spenders, no orders, revenue per category

Runs in: MySQL 8 or later (any SQL client)

SQL
-- A small copy of the ShopLite store from Section 12's sample databaseCREATE TABLE customers (customer_id INT PRIMARY KEY, name VARCHAR(60), city VARCHAR(40));CREATE TABLE products (product_id INT PRIMARY KEY, name VARCHAR(80), category VARCHAR(30), price DECIMAL(10,2));CREATE TABLE orders (order_id INT PRIMARY KEY, customer_id INT, order_date DATE, status VARCHAR(10));CREATE TABLE order_items (order_id INT, product_id INT, quantity INT, unit_price DECIMAL(10,2),                          PRIMARY KEY (order_id, product_id));INSERT INTO customers VALUES (1, 'Asha Rao', 'Bengaluru'), (2, 'Ravi Kumar', 'Chennai'), (3, 'Meena Iyer', 'Chennai'),  (4, 'Kabir Singh', 'Delhi'), (5, 'Priya Sharma', 'Pune'), (6, 'Arjun Mehta', 'Mumbai'), (10, 'Imran Khan', 'Hyderabad');INSERT INTO products VALUES (1, 'Redmi Note 13', 'Mobiles', 17999), (2, 'Samsung Galaxy M35', 'Mobiles', 19999),  (3, 'iPhone 15', 'Mobiles', 69900), (4, 'Lenovo IdeaPad Slim 3', 'Laptops', 42990), (5, 'HP Victus Gaming', 'Laptops', 64990),  (6, 'boAt Airdopes 141', 'Accessories', 1299), (7, 'Mi Power Bank 20000mAh', 'Accessories', 2199),  (8, 'Logitech M331 Mouse', 'Accessories', 849), (9, 'Clean Code', 'Books', 499), (10, 'Head First Java', 'Books', 650),  (11, 'Atomic Habits', 'Books', 399), (12, 'Cotton Kurta', 'Fashion', 899), (13, 'Running Shoes', 'Fashion', 2499);INSERT INTO orders VALUES (1, 1, '2025-01-05', 'DELIVERED'), (2, 2, '2025-01-18', 'DELIVERED'),  (3, 1, '2025-02-02', 'DELIVERED'), (4, 3, '2025-02-10', 'CANCELLED'), (5, 4, '2025-02-21', 'DELIVERED'),  (6, 5, '2025-03-03', 'DELIVERED'), (7, 2, '2025-03-15', 'SHIPPED'), (8, 6, '2025-03-28', 'DELIVERED');INSERT INTO order_items VALUES (1, 1, 1, 17999), (1, 6, 2, 1299), (2, 9, 1, 499), (2, 10, 1, 650), (2, 11, 2, 399),  (3, 4, 1, 42990), (3, 8, 1, 849), (4, 3, 1, 69900), (5, 2, 1, 19999), (5, 7, 1, 2199),  (6, 12, 3, 899), (6, 13, 1, 2499), (7, 6, 1, 1299), (8, 5, 1, 64990);
-- Query 1: top 3 customers by money spent on delivered ordersSELECT c.name, SUM(oi.quantity * oi.unit_price) AS spentFROM customers cJOIN orders o       ON o.customer_id = c.customer_idJOIN order_items oi ON oi.order_id = o.order_idWHERE o.status = 'DELIVERED'GROUP BY c.customer_id, c.nameORDER BY spent DESCLIMIT 3;
-- Query 2: customers who have never placed an orderSELECT c.customer_id, c.nameFROM customers cLEFT JOIN orders o ON o.customer_id = c.customer_idWHERE o.order_id IS NULLORDER BY c.customer_id;
-- Query 3: delivered revenue per category, only categories above Rs. 10000SELECT p.category, SUM(oi.quantity * oi.unit_price) AS revenueFROM order_items oiJOIN orders o   ON o.order_id = oi.order_idJOIN products p ON p.product_id = oi.product_idWHERE o.status = 'DELIVERED'GROUP BY p.categoryHAVING SUM(oi.quantity * oi.unit_price) > 10000ORDER BY revenue DESC;
Output
+-------------+----------+
| name        | spent    |
+-------------+----------+
| Arjun Mehta | 64990.00 |
| Asha Rao    | 64436.00 |
| Kabir Singh | 22198.00 |
+-------------+----------+
+-------------+------------+
| customer_id | name       |
+-------------+------------+
|          10 | Imran Khan |
+-------------+------------+
+----------+-----------+
| category | revenue   |
+----------+-----------+
| Laptops  | 107980.00 |
| Mobiles  |  37998.00 |
+----------+-----------+

What this code does

  • Query 1 sums item values per customer over delivered orders only, so Meena's cancelled iPhone does not count; Arjun's one laptop beats Asha's two orders. Query 2 is the classic anti-join: Imran has no order row.
  • Query 3 filters rows with WHERE (delivered only) and groups with HAVING (revenue above 10000), so Accessories, Books and Fashion are dropped.

The three tasks: the top 3 customers by money spent on delivered orders (three-table join, WHERE, GROUP BY, ORDER BY ... DESC LIMIT 3), customers who never ordered (LEFT JOIN and IS NULL), and delivered revenue per category above Rs. 10000 (HAVING on the sum). An order's value is SUM(quantity * unit_price). Say the edge cases aloud: cancelled orders, customers with no orders, ties at the cut-off.

Revise: SQL interview questions (opens in a new tab), Report queries (opens in a new tab).

Predict the output

Predict the SQL result

Work out the rows before you pick.

Round 1 of 2

Which rows come back?

-- orders (customer_id, status): (1, DELIVERED), (1, CANCELLED), (2, DELIVERED), (3, CANCELLED)
SELECT customer_id, COUNT(*) AS delivered
FROM orders
WHERE status = 'DELIVERED'
GROUP BY customer_id;

Round 3: spot the problem: N+1, field injection, SQL concatenation

The N+1 problem is one query for a list plus one more query per row for a lazy association. You spot it by a slow page and an SQL log full of identical selects, and fix it with join fetch, an entity graph, a DTO query or batch fetching.

For each snippet give three things: the symptom, the cause and the fix. These four examples show N+1 and two more classic smells.

Example 2 · N+1 in miniature: count the queries

NPlusOneDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Map;
record Customer(long id, String name) { }
/** An order whose customer is loaded lazily, the way Hibernate loads a LAZY @ManyToOne on first access. */class Order {    final long id;    private final long customerId;    private Customer customer;                   // null until first access, unless fetched with the order    private final FakeDatabase db;
    Order(long id, long customerId, Customer customer, FakeDatabase db) {        this.id = id;        this.customerId = customerId;        this.customer = customer;        this.db = db;    }
    Customer getCustomer() {        if (customer == null) {            customer = db.findCustomer(customerId);  // one extra SELECT per order        }        return customer;    }}
/** Prints every "SQL statement" and counts them. */class FakeDatabase {    private final Map<Long, Customer> customers = Map.of(            1L, new Customer(1, "Asha Rao"), 2L, new Customer(2, "Ravi Kumar"),            4L, new Customer(4, "Kabir Singh"), 5L, new Customer(5, "Priya Sharma"));    private final long[][] orderRows = { { 1, 1 }, { 2, 2 }, { 5, 4 }, { 6, 5 } };   // order id, customer id    int queries = 0;
    List<Order> findOrders() {        log("select o.* from orders o");        List<Order> result = new ArrayList<>();        for (long[] row : orderRows) {            result.add(new Order(row[0], row[1], null, this));        }        return result;    }
    List<Order> findOrdersJoinFetchCustomer() {        log("select o.*, c.* from orders o join customers c on c.customer_id = o.customer_id");        List<Order> result = new ArrayList<>();        for (long[] row : orderRows) {            result.add(new Order(row[0], row[1], customers.get(row[1]), this));        }        return result;    }
    Customer findCustomer(long id) {        log("select c.* from customers c where c.customer_id = " + id);        return customers.get(id);    }
    private void log(String sql) {        queries++;        System.out.println("  SQL: " + sql);    }}
public class NPlusOneDemo {
    static void printReport(List<Order> orders) {        for (Order o : orders) {            System.out.println("  order " + o.id + " -> " + o.getCustomer().name());        }    }
    public static void main(String[] args) {        FakeDatabase db = new FakeDatabase();        System.out.println("Buggy: load orders, then touch each lazy customer");        printReport(db.findOrders());        System.out.println("  queries: " + db.queries + "  (1 + N, N = 4 orders)");
        db.queries = 0;        System.out.println("Fixed: one query with JOIN FETCH");        printReport(db.findOrdersJoinFetchCustomer());        System.out.println("  queries: " + db.queries);    }}
Output
Buggy: load orders, then touch each lazy customer
  SQL: select o.* from orders o
  SQL: select c.* from customers c where c.customer_id = 1
  order 1 -> Asha Rao
  SQL: select c.* from customers c where c.customer_id = 2
  order 2 -> Ravi Kumar
  SQL: select c.* from customers c where c.customer_id = 4
  order 5 -> Kabir Singh
  SQL: select c.* from customers c where c.customer_id = 5
  order 6 -> Priya Sharma
  queries: 5  (1 + N, N = 4 orders)
Fixed: one query with JOIN FETCH
  SQL: select o.*, c.* from orders o join customers c on c.customer_id = o.customer_id
  order 1 -> Asha Rao
  order 2 -> Ravi Kumar
  order 5 -> Kabir Singh
  order 6 -> Priya Sharma
  queries: 1

What this code does

  • Loading 4 orders takes one query, then touching each lazy customer adds one more: 5 queries. With 500 orders from 500 customers it would be 501.
  • The fixed version fetches orders and customers together with one join, which is what join fetch or an @EntityGraph makes Hibernate do.

Example 3 · The same N+1 in JPA, and two fixes

Runs in: the ShopLite Spring Boot project (Sections 15 to 17)

Order.javaJava
// --- Order.java (entity) ---------------------------------------------------------------@Entity@Table(name = "orders")public class Order {    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)    @JoinColumn(name = "customer_id")    private Customer customer;
    @Enumerated(EnumType.STRING)    private OrderStatus status;}
// --- OrderService.java: BUGGY -------------------------------------------------------------@Transactional(readOnly = true)public List<OrderSummary> placedOrders() {    return orderRepository.findByStatus(OrderStatus.PLACED).stream()            .map(o -> new OrderSummary(o.getId(), o.getCustomer().getName()))            .toList();}
// --- OrderRepository.java: FIXED, pick one of the two ---------------------------------------public interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findByStatus(OrderStatus status);
    @Query("select o from Order o join fetch o.customer where o.status = :status")    List<Order> findByStatusWithCustomer(@Param("status") OrderStatus status);
    @EntityGraph(attributePaths = "customer")    List<Order> findWithCustomerByStatus(OrderStatus status);}
Sample output
Buggy: 3 PLACED orders from 3 customers (logging.level.org.hibernate.SQL=DEBUG):
select o1_0.id,o1_0.customer_id,o1_0.status from orders o1_0 where o1_0.status=?
select c1_0.id,c1_0.email,c1_0.name from customers c1_0 where c1_0.id=?
select c1_0.id,c1_0.email,c1_0.name from customers c1_0 where c1_0.id=?
select c1_0.id,c1_0.email,c1_0.name from customers c1_0 where c1_0.id=?

Fixed with findByStatusWithCustomer (join fetch):
select o1_0.id,c1_0.id,c1_0.email,c1_0.name,o1_0.status from orders o1_0 join customers c1_0 on c1_0.id=o1_0.customer_id where o1_0.status=?

What this code does

  • The stream calls getCustomer().getName() for every order, and each first touch of a lazy customer is a new select. The log is the evidence you point to in an interview.
  • join fetch and @EntityGraph(attributePaths = "customer") both load the customers in the same query (the entity graph uses a left join). Column lists are shortened.

Example 4 · Field injection vs constructor injection in a unit test

InjectionStyleDemo.javaJava
interface SmsGateway {    String send(String phone, String text);}
/** BAD: field injection. Outside Spring nothing sets the field, and the dependency is hidden. */class FieldInjectedNotifier {    // @Autowired    private SmsGateway gateway;
    String orderShipped(String phone) {        return gateway.send(phone, "Your ShopLite order has shipped");    }}
/** GOOD: constructor injection. The dependency is required, final and easy to replace in a test. */class ConstructorInjectedNotifier {    private final SmsGateway gateway;
    ConstructorInjectedNotifier(SmsGateway gateway) {        this.gateway = gateway;    }
    String orderShipped(String phone) {        return gateway.send(phone, "Your ShopLite order has shipped");    }}
public class InjectionStyleDemo {
    public static void main(String[] args) {        SmsGateway fake = (phone, text) -> "fake SMS to " + phone + ": " + text;
        // A plain unit test, no Spring context: how do you give the field-injected class its gateway?        try {            new FieldInjectedNotifier().orderShipped("9876500001");        } catch (NullPointerException e) {            System.out.println("Field injection in a unit test: NullPointerException");        }
        // With a constructor, the test simply passes the fake in        System.out.println("Constructor injection: " + new ConstructorInjectedNotifier(fake).orderShipped("9876500001"));    }}
Output
Field injection in a unit test: NullPointerException
Constructor injection: fake SMS to 9876500001: Your ShopLite order has shipped

What this code does

  • Outside a Spring context nobody sets the private field, so the field-injected class fails with NullPointerException; its dependency was invisible in its API.
  • The constructor-injected class states its dependency, can keep it final, and takes a lambda fake in one line.

Example 5 · SQL concatenation and the parameterised fix

SqlConcatDemo.javaJava
import java.util.List;
public class SqlConcatDemo {
    /** BUGGY: user input becomes part of the SQL text. */    static String concatenated(String email, String password) {        return "SELECT * FROM users WHERE email = '" + email + "' AND password_hash = '" + password + "'";    }
    /** FIXED: the SQL text is fixed; values travel separately as parameters (PreparedStatement). */    static final String SAFE_SQL = "SELECT id, password_hash FROM users WHERE email = ?";
    public static void main(String[] args) {        System.out.println("Normal login:");        System.out.println("  " + concatenated("asha@clg.in", "x"));
        System.out.println("Attacker types  ' OR '1'='1  as the password:");        System.out.println("  " + concatenated("asha@clg.in", "' OR '1'='1"));        System.out.println("  -> AND binds tighter than OR, so the WHERE is true for every row");
        System.out.println("Fixed:");        System.out.println("  SQL:        " + SAFE_SQL);        System.out.println("  parameters: " + List.of("asha@clg.in"));        System.out.println("  -> the typed password never touches the SQL text");        System.out.println("  -> passwordEncoder.matches(typed, password_hash) checks it in Java: false for the attack");    }}
Output
Normal login:
  SELECT * FROM users WHERE email = 'asha@clg.in' AND password_hash = 'x'
Attacker types  ' OR '1'='1  as the password:
  SELECT * FROM users WHERE email = 'asha@clg.in' AND password_hash = '' OR '1'='1'
  -> AND binds tighter than OR, so the WHERE is true for every row
Fixed:
  SQL:        SELECT id, password_hash FROM users WHERE email = ?
  parameters: [asha@clg.in]
  -> the typed password never touches the SQL text
  -> passwordEncoder.matches(typed, password_hash) checks it in Java: false for the attack

What this code does

  • Concatenation lets the quote in the input end the string and add OR '1'='1', which makes the condition true for every row. The snippet also compares a password inside SQL, a second smell.
  • The fix keeps the SQL text fixed with ? and sends the e-mail as a parameter; the password is checked with the PasswordEncoder in Java.

Field injection (@Autowired on a private field) hides dependencies, prevents final fields and leaves the field null in a plain unit test; constructor injection fixes all three. SQL concatenation lets input change the SQL text; use PreparedStatement parameters, Spring Data method names or @Query with named parameters, and a whitelist for sort columns. FetchType.EAGER everywhere is not a fix for N+1.

Revise: JDBC and SQL injection (opens in a new tab), Fixing N+1 (opens in a new tab).

Find the bug

Name the line

One line in each snippet causes the problem. Click it.

This method runs 1 + N queries. Which line?

Round 1 of 3

Round 4: walk a request from controller to database aloud

"What happens when a request hits your Spring Boot API?" tests whether you understand the whole stack. Walk one concrete request, POST /api/v1/orders with a JSON body and a bearer token, and say what can go wrong at each step.

Example 6 · One request, followed through the logs

Runs in: the ShopLite Spring Boot project (Sections 15 to 17)

Terminal
$ curl -i -X POST http://localhost:8080/api/v1/orders \       -H "Authorization: Bearer $ASHA_TOKEN" -H "Content-Type: application/json" \       -d '{"productId":7,"quantity":2}'
Sample output
HTTP/1.1 201
Location: /api/v1/orders/16
Content-Type: application/json

{"id":16,"status":"PLACED","total":4398.00}

Server log (security, web and SQL at DEBUG, shortened):
[nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Securing POST /api/v1/orders
[nio-8080-exec-3] o.s.s.o.s.r.a.JwtAuthenticationProvider  : Authenticated token
[nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : POST "/api/v1/orders", parameters={}
[nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.shoplite.order.OrderController#place(PlaceOrderRequest)
[nio-8080-exec-3] org.hibernate.SQL                        : select p1_0.id,p1_0.name,p1_0.price,p1_0.stock from products p1_0 where p1_0.id=?
[nio-8080-exec-3] org.hibernate.SQL                        : insert into orders (customer_id,order_date,status) values (?,?,?)
[nio-8080-exec-3] org.hibernate.SQL                        : insert into order_items (quantity,unit_price,order_id,product_id) values (?,?,?,?)
[nio-8080-exec-3] org.hibernate.SQL                        : update products set name=?,price=?,stock=? where id=?
[nio-8080-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [OrderResponse[id=16, status=PLACED, total=4398.00]]
[nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Completed 201 CREATED

What this code does

  • One Tomcat thread (exec-3) carries the request through every step: security filters, DispatcherServlet, handler mapping, the controller, Hibernate's SQL, and the JSON response.
  • The update products comes from dirty checking: the service lowered the stock on a managed entity, and the commit flushed it without an explicit save.

The walk, in order:

  1. The client sends the request; DNS, TCP and TLS come first, then embedded Tomcat gives it a thread.
  2. The security filters run: CORS, then BearerTokenAuthenticationFilter validates the JWT, then AuthorizationFilter checks the URL rules. 401 and 403 stop here.
  3. DispatcherServlet finds the controller method; Jackson turns the JSON into PlaceOrderRequest and @Valid checks it (400 on failure).
  4. The controller calls the service through its @Transactional proxy: a transaction starts and a connection is borrowed from HikariCP.
  5. The service applies the business rules and calls the repositories; Hibernate runs SQL through JDBC PreparedStatements.
  6. The transaction commits (dirty checking flushes changes) or rolls back, and the connection returns to the pool.
  7. The controller maps the entity to a response DTO; Jackson writes JSON with 201 Created and a Location header.
  8. Any exception on the way goes to the @RestControllerAdvice, which returns a Problem Details body.

Revise: JWT and security (opens in a new tab), The security filter chain (opens in a new tab).

Order of execution

The request journey

Put the stops of a POST /api/v1/orders in order.

Practise this answer aloud until it takes about two minutes. Interviewers often interrupt at one step ("how does the token get checked?"), so know each step one level deeper.

Next step

Check your understanding

12 quick questions