Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 119 ยท Practice and Review

Advanced Java Cheat Sheet

A dense Advanced Java cheat sheet with JDBC, Jackson, JUnit 6, HttpClient, Servlets, JPA annotations, Spring and Spring Boot annotations, and Maven and Gradle commands.

This page condenses the whole Advanced Java course into one place: the classes, annotations, commands and settings you reach for every day as a backend developer. Each block is compact on purpose, so you can scan it in seconds while coding, before a code review or right before an interview.

Every section links to the lesson that explains the topic properly. The four live editors cover the things people most often get wrong from memory: the full JDBC sequence with generated keys, batches and rollback; Jackson configuration; a JUnit test class with parameterized tests; and an HTTP round trip with the JDK's own server and client. Framework code (Spring, JPA, Servlets) is shown read-only, because it can't run here. Versions follow the course: Java 25, JUnit 6, Jackson 2 (with notes on Jackson 3), Hibernate 7 / Jakarta Persistence 3.2, Spring Framework 7 and Spring Boot 4.

Build tools

Maven

Terminal
./mvnw clean verify               # compile, unit tests, package, integration tests
./mvnw test                       # unit tests only (Surefire)
./mvnw test -Dtest=OrderServiceTest#rejectsEmptyCart
./mvnw package -DskipTests        # build the JAR, skip running tests
./mvnw dependency:tree            # who pulls in which version
./mvnw versions:display-dependency-updates
./mvnw -pl api -am install        # one module plus the modules it needs
./mvnw spring-boot:run            # run a Spring Boot app

Lifecycle: validate โ†’ compile โ†’ test โ†’ package โ†’ verify โ†’ install โ†’ deploy. Running a phase runs every phase before it.

Scope Compile Tests Runtime / packaged Typical use
compile (default) yes yes yes Jackson, Spring
provided yes yes no (the server has it) Servlet API in a WAR
runtime no yes yes JDBC drivers
test no yes no JUnit, Mockito, H2 for tests
import - - - a BOM in dependencyManagement

Version conflicts: nearest wins, then first declared. Pin versions with dependencyManagement or a BOM. See Maven in Depth.

Gradle (Kotlin DSL)

Kotlin
plugins {
    java
    application
}

java { toolchain { languageVersion = JavaLanguageVersion.of(25) } }

dependencies {
    implementation("com.fasterxml.jackson.core:jackson-databind:2.22.3")
    runtimeOnly("com.h2database:h2:2.5.252")
    testImplementation(platform("org.junit:junit-bom:6.1.3"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test { useJUnitPlatform() }
Terminal
./gradlew build                   # compile, test, assemble
./gradlew test --tests "*OrderServiceTest"
./gradlew dependencies --configuration runtimeClasspath
./gradlew bootRun                 # run a Spring Boot app
./gradlew build --scan            # detailed build report
Gradle configuration Maven equivalent Meaning
implementation compile needed to compile and run, hidden from consumers
api (java-library) compile part of your public API, visible to consumers
compileOnly provided compile only, supplied at runtime by someone else
runtimeOnly runtime needed only at runtime
testImplementation test test code only

Gradle resolves conflicts to the highest version. See Gradle in Depth.

JDBC

The core sequence

Java
try (Connection con = dataSource.getConnection();
     PreparedStatement ps = con.prepareStatement(
         "select id, title, price from book where author_id = ? order by id")) {
    ps.setLong(1, authorId);                      // parameters start at 1
    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {                       // cursor starts BEFORE the first row
            books.add(new Book(rs.getLong("id"), rs.getString("title"),
                               rs.getBigDecimal("price")));
        }
    }
}                                                  // closed in reverse order
Method Returns Use for
executeQuery() ResultSet SELECT
executeUpdate() int rows affected INSERT, UPDATE, DELETE, DDL
execute() boolean (true = result set) unknown SQL
executeBatch() int[] counts many statements in one round trip
getGeneratedKeys() ResultSet new ids (prepare with new String[] {"id"})
getObject(col, LocalDate.class) typed value dates, times, nullable numbers
wasNull() boolean after a primitive getter: was it NULL?

Connection URLs: jdbc:h2:mem:test, jdbc:postgresql://localhost:5432/shop, jdbc:mysql://localhost:3306/shop. See JDBC Introduction and CRUD with JDBC.

Transactions and isolation

Java
con.setAutoCommit(false);
try {
    debit.executeUpdate();
    credit.executeUpdate();
    con.commit();
} catch (SQLException e) {
    con.rollback();
    throw e;
} finally {
    con.setAutoCommit(true);
}
Savepoint sp = con.setSavepoint();  con.rollback(sp);   // partial rollback
con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
Isolation level Dirty read Non-repeatable read Phantom
READ_UNCOMMITTED possible possible possible
READ_COMMITTED (common default) prevented possible possible
REPEATABLE_READ prevented prevented possible (by the standard)
SERIALIZABLE prevented prevented prevented

Lost updates need SELECT ... FOR UPDATE or a version column. See Transactions with JDBC.

Live: CRUD, keys, batch and rollback

Java JDBC essentials on H2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Book 2 still costs 19.50 at the end: the rollback undid the first UPDATE too. SQLState class 23 means a constraint violation (23513 is H2's code for a failed CHECK).

Pools, DAOs and injection

PROPERTIES
# HikariCP through Spring Boot
spring.datasource.url=jdbc:postgresql://db:5432/shop
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.connection-timeout=3s
spring.datasource.hikari.max-lifetime=30m
spring.datasource.hikari.leak-detection-threshold=20s
  • Get connections from a DataSource, never from DriverManager in applications. close() on a pooled connection returns it to the pool. See Connection Pooling.
  • Every value goes through a ? parameter. Columns and ASC/DESC come from an allow-list. Escape % and _ in LIKE patterns. See PreparedStatement and SQL Injection.
  • Hide SQL behind a DAO or repository interface that returns records, Optional and List. See The DAO and Repository Patterns.

Jackson

ObjectMapper essentials

Java
ObjectMapper mapper = new ObjectMapper()                       // build once, share it
    .registerModule(new JavaTimeModule())                      // java.time support
    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)   // ISO 8601 dates
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

String json  = mapper.writeValueAsString(order);
String nice  = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(order);
Order order  = mapper.readValue(json, Order.class);
List<Order> list = mapper.readValue(json, new TypeReference<List<Order>>() {});
JsonNode tree    = mapper.readTree(json);         // tree.path("a").path("b"), tree.at("/a/b")
Map<String, Object> map = mapper.convertValue(order, new TypeReference<>() {});
Annotation Effect
@JsonProperty("customer_name") rename one property
@JsonAlias({"customer", "client"}) accept extra names when reading
@JsonIgnore never read or write this property
@JsonInclude(Include.NON_NULL) skip null values
@JsonFormat(pattern = "yyyy-MM-dd") format a date or number
@JsonIgnoreProperties(ignoreUnknown = true) tolerate unknown JSON fields
@JsonTypeInfo + @JsonSubTypes polymorphic types with a type id
@JsonValue / @JsonCreator write a type as one value / build it from JSON
@JsonNaming(SnakeCaseStrategy.class) rename every property of a class

Jackson 3 (used by Spring Boot 4) lives in tools.jackson.* packages (annotations keep com.fasterxml.jackson.annotation), centers on JsonMapper, supports java.time out of the box and throws unchecked exceptions. See JSON with Jackson and Advanced Jackson.

Java Jackson in one screen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Testing with JUnit 6

Annotations

Annotation Purpose
@Test a test method (non-private, void, not static)
@BeforeEach / @AfterEach run around every test
@BeforeAll / @AfterAll once per class (static, unless @TestInstance(PER_CLASS))
@DisplayName("...") readable name in reports
@Nested group tests in an inner class
@Disabled("reason") skip a test
@Tag("slow") label tests to include or exclude in the build
@ParameterizedTest + @ValueSource, @CsvSource, @MethodSource, @EnumSource one test, many inputs
@RepeatedTest(5) run the same test several times
@TestFactory build DynamicTests at runtime
@Timeout(2) fail a test that runs too long

Assertions

Java
assertEquals(expected, actual);               // expected FIRST
assertEquals(0.3, 0.1 + 0.2, 1e-9);           // delta for doubles
assertTrue(cart.isEmpty(), "new cart should be empty");
assertNull(found); assertNotNull(order);
assertIterableEquals(List.of(1, 2), result);
var e = assertThrows(IllegalArgumentException.class, () -> parse("x"));
assertEquals("not a number: x", e.getMessage());
assertAll(() -> assertEquals("Ana", u.name()), () -> assertEquals(31, u.age()));
assertTimeout(Duration.ofMillis(200), () -> service.quickCall());
assumeTrue(System.getenv("CI") != null);       // abort (skip), not fail

JUnit creates a new instance of the test class for every test, and the order of tests is not guaranteed. See Unit Testing with JUnit 6, Test Lifecycle and Organization and Parameterized Tests.

Java A complete JUnit test class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Test doubles and Mockito

Double What it does
dummy fills a parameter, never used
stub returns canned answers
fake simple working implementation (in-memory repository)
spy records calls, can wrap a real object
mock verifies that expected calls happened
Java
@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {
    @Mock PaymentGateway gateway;
    @InjectMocks CheckoutService service;

    @Test
    void chargesTheCart() {
        when(gateway.charge(any(), eq(4200L))).thenReturn(Receipt.ok("r-1"));
        service.checkout(cart);
        var captor = ArgumentCaptor.forClass(Long.class);
        verify(gateway).charge(any(), captor.capture());
        assertEquals(4200L, captor.getValue());
        verifyNoMoreInteractions(gateway);
    }
}

Stub queries, verify commands, and don't mock types you don't own. Name integration tests *IT and run them with Failsafe. See Test Doubles and Mockito, Test-Driven Development and Integration Testing.

Logging and tooling

Java
private static final Logger log = LoggerFactory.getLogger(OrderService.class);   // SLF4J

log.info("Order {} placed by {}", order.id(), user.id());   // placeholders, no concatenation
log.warn("Payment retry {} of {}", attempt, max);
log.error("Could not charge order {}", order.id(), exception); // exception LAST
MDC.put("requestId", requestId);  try { ... } finally { MDC.remove("requestId"); }
PROPERTIES
logging.level.root=INFO
logging.level.com.shop=DEBUG
logging.level.org.hibernate.SQL=DEBUG
logging.structured.format.console=ecs
Terminal
jcmd                                  # list JVMs
jcmd <pid> Thread.print               # thread dump
jcmd <pid> GC.heap_info
jcmd <pid> GC.heap_dump /tmp/app.hprof
jcmd <pid> JFR.start duration=60s filename=rec.jfr
java -XX:+HeapDumpOnOutOfMemoryError -XX:MaxRAMPercentage=75 -jar app.jar

See Logging with SLF4J and Logback, Debugging and Profiling Tools and Code Quality and Static Analysis.

HTTP and REST

Status codes you must know

Code Meaning Typical use
200 OK success with a body GET, PUT, PATCH
201 Created new resource, with Location POST
204 No Content success, no body DELETE
304 Not Modified cached copy still valid If-None-Match
400 Bad Request malformed or invalid input validation errors
401 Unauthorized not authenticated missing or bad token
403 Forbidden authenticated, not allowed missing role or scope
404 Not Found no such resource unknown id
405 Method Not Allowed wrong verb (send Allow) DELETE on a read-only resource
409 Conflict state conflict duplicate, version mismatch
415 Unsupported Media Type wrong Content-Type XML sent to a JSON API
422 Unprocessable Content well-formed but invalid some APIs use it for validation
429 Too Many Requests rate limited (send Retry-After) throttling
500 / 503 server bug / temporarily unavailable never leak stack traces
Method Safe Idempotent Body
GET, HEAD, OPTIONS yes yes no
PUT (replace) no yes yes
DELETE no yes usually no
PATCH (partial change) no not guaranteed yes
POST (create, actions) no no (use an idempotency key) yes

Errors use RFC 9457 problem details (application/problem+json with type, title, status, detail, instance). See How HTTP Works and REST API Design.

HttpClient and HttpServer

Java
HttpClient client = HttpClient.newBuilder()                // thread-safe: reuse it
        .connectTimeout(Duration.ofSeconds(2)).build();
HttpRequest request = HttpRequest.newBuilder(URI.create(base + "/books"))
        .timeout(Duration.ofSeconds(5))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(json)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
CompletableFuture<HttpResponse<String>> later =
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString());

A 404 or 500 is not an exception: check statusCode(). Exceptions mean the exchange itself failed (connection refused, HttpTimeoutException). See Calling APIs with HttpClient and Building a REST API with the JDK.

Java HTTP round trip with the JDK

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Web security in one table

Topic Rule
Passwords Argon2id, scrypt, bcrypt or PBKDF2 (600,000+ iterations), salted; compare in constant time
Sessions random id in an HttpOnly; Secure; SameSite=Lax cookie; changeSessionId() after login
JWT header.payload.signature; payload is readable; check algorithm, signature, exp, iss, aud
CSRF needed with cookie authentication; SameSite cookies + tokens; no changes on GET
CORS lets listed origins read responses in browsers; it is not access control
XSS escape output by context; Content-Security-Policy
Transport HTTPS everywhere, HSTS

See Web Security Basics and JWT and OAuth 2.

Servlets and JSP

Java
@WebServlet("/books/*")
public class BookServlet extends HttpServlet {          // jakarta.servlet.http
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getPathInfo();                   // "/42" for /books/42
        String sort = req.getParameter("sort");          // null if missing
        resp.setStatus(200);
        resp.setContentType("application/json;charset=UTF-8");   // before writing
        resp.getWriter().write(json);
    }
}
Concept Remember
Lifecycle init() once, service() per request (โ†’ doGet, doPost...), destroy() once
Threads one instance serves many threads: no mutable instance fields
Forward vs redirect forward = same request inside the server; redirect = new request from the browser
Post/Redirect/Get redirect after a successful form POST (303)
Session req.getSession() creates, getSession(false) only reads, invalidate() logs out
Filter code before chain.doFilter() sees the request, after it sees the response
JSP / EL ${...} does not escape; use <c:out>; avoid scriptlets
Packages Jakarta EE 9+ uses jakarta.*; Tomcat 10.1+/11 needs it

See Servlets, Filters and Listeners and JSTL and Expression Language.

JPA and Hibernate

Mapping annotations

Java
@Entity
@Table(name = "books")
public class Book {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id;
    @Column(nullable = false, length = 200) private String title;
    @Enumerated(EnumType.STRING) private Status status;
    @Version private int version;                                   // optimistic locking
    @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "author_id")
    private Author author;                                          // owning side (has the FK)
    protected Book() {}                                             // required by JPA
}

@Entity
public class Author {
    @Id @GeneratedValue private Long id;
    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Book> books = new ArrayList<>();                   // inverse side
    public void addBook(Book b) { books.add(b); b.setAuthor(this); } // keep both ends in sync
}
Annotation Default fetch Notes
@ManyToOne EAGER make it LAZY; owns the foreign key
@OneToOne EAGER make it LAZY where possible; @MapsId for shared keys
@OneToMany LAZY usually mappedBy the @ManyToOne
@ManyToMany LAZY join table; prefer Set; never cascade REMOVE
@Embedded / @Embeddable - value objects (records allowed)
@Transient - not persisted

EntityManager and queries

Java
em.persist(book);                      // transient -> managed (INSERT at flush)
Book b = em.find(Book.class, 42L);     // null if missing
Book merged = em.merge(detached);      // copies state; USE THE RETURN VALUE
em.remove(b);                          // managed -> removed
b.setTitle("New");                     // dirty checking: UPDATE at flush, no save()

List<BookDto> rows = em.createQuery("""
        select new com.shop.BookDto(b.id, b.title, a.name)
        from Book b join b.author a
        where b.price < :max order by b.id""", BookDto.class)
    .setParameter("max", max)
    .setFirstResult(0).setMaxResults(20)
    .getResultList();

em.createQuery("select a from Author a left join fetch a.books", Author.class);  // fixes N+1

Entity states: transient โ†’ managed โ†’ detached / removed. Lazy access after the session closed throws LazyInitializationException. Fix N+1 with join fetch, entity graphs, @BatchSize or DTO projections. See ORM and JPA Introduction, Entity Relationships, Querying with JPQL and the Criteria API, Fetching Strategies and the N+1 Problem and Entity Lifecycle and Transactions.

Spring Framework

Core annotations

Annotation Purpose
@Component, @Service, @Repository, @Controller register a class as a bean through component scanning
@Configuration + @Bean create beans in factory methods (third-party classes)
@Autowired inject (implicit on a single constructor: leave it out)
@Qualifier("fast") / @Primary pick one of several candidates / the default candidate
@Value("${shop.currency:EUR}") inject one property with a default
@Scope("prototype") new instance per lookup (default: singleton)
@Profile("dev") bean only when the profile is active
@PostConstruct / @PreDestroy lifecycle callbacks (jakarta.annotation)
@Transactional transaction around a method (through a proxy)
@Aspect + @Around("execution(* com.shop..*Service.*(..))") cross-cutting code
@EnableScheduling + @Scheduled(fixedDelay = 5000) periodic jobs (cron has 6 fields)
@EnableCaching + @Cacheable("prices") cache method results
@EnableAsync + @Async run a method on an executor
Java
@Service
public class OrderService {
    private final OrderRepository orders;               // constructor injection
    private final Clock clock;

    public OrderService(OrderRepository orders, Clock clock) {
        this.orders = orders;
        this.clock = clock;
    }

    @Transactional                                       // commit on success,
    public Order place(NewOrder input) { ... }           // rollback on RuntimeException/Error
}

@Transactional, @Cacheable, @Async and @PreAuthorize work through proxies: a call from one method to another in the same object (self-invocation) skips them, and so do private methods. Checked exceptions commit unless you set rollbackFor. See Dependency Injection, Beans, Configuration and Component Scanning, Aspect-Oriented Programming and Scheduling, Caching and Async Tasks.

Spring Boot

Web layer

Java
@RestController
@RequestMapping("/api/books")
public class BookController {
    @GetMapping("/{id}")
    public BookResponse get(@PathVariable long id) { return service.get(id); }

    @GetMapping
    public Page<BookResponse> list(@RequestParam(defaultValue = "0") int page) { ... }

    @PostMapping
    public ResponseEntity<BookResponse> create(@Valid @RequestBody NewBook body) {
        BookResponse created = service.create(body);
        return ResponseEntity.created(URI.create("/api/books/" + created.id())).body(created);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable long id) { service.delete(id); }
}

@RestControllerAdvice
class ApiErrors {
    @ExceptionHandler(BookNotFoundException.class)
    ProblemDetail notFound(BookNotFoundException e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
    }
}

record NewBook(@NotBlank @Size(max = 200) String title, @NotNull @PositiveOrZero BigDecimal price) {}

Data, configuration and tests

Java
public interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByAuthorNameOrderByTitle(String name);          // derived query
    Page<Book> findByPriceLessThan(BigDecimal max, Pageable page);
    @Query("select b from Book b join fetch b.author where b.id = :id")
    Optional<Book> findWithAuthor(@Param("id") long id);
}

@ConfigurationProperties("shop")
record ShopProperties(String currency, @DefaultValue("30s") Duration timeout) {}
YAML
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/shop
  jpa:
    open-in-view: false
  profiles:
    active: dev
server:
  port: 8080
management:
  endpoints:
    web:
      exposure:
        include: health,info,prometheus

Property order (first wins): command-line arguments โ†’ system properties โ†’ environment variables (SPRING_DATASOURCE_URL) โ†’ external files โ†’ application-{profile} โ†’ application.properties in the JAR.

Test annotation Starts Use for
none (plain JUnit) nothing services, rules (most tests)
@WebMvcTest(BookController.class) MVC layer + MockMvc controllers, JSON, status codes
@DataJpaTest JPA + embedded DB, rollback per test repositories, queries
@SpringBootTest(webEnvironment = RANDOM_PORT) whole app a few end-to-end checks
@MockitoBean replaces a bean with a mock slices (@MockBean was removed in Boot 4)
@ServiceConnection + Testcontainers real database in Docker production-like integration tests
Java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    return http
            .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/actuator/health").permitAll()
                    .requestMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN")
                    .anyRequest().authenticated())
            .oauth2ResourceServer(rs -> rs.jwt(Customizer.withDefaults()))
            .build();
}

Starters: spring-boot-starter-webmvc (Boot 4; -web in Boot 3), -data-jpa, -validation, -security, -oauth2-resource-server, -actuator, -test. See Spring Boot Introduction, Configuration, Properties and Profiles, Building REST APIs with Spring Boot, Validation and Error Handling, Spring Data JPA, Testing Spring Boot Applications, Spring Security and Actuator, Metrics and Observability.

Architecture and deployment

Pattern One-line rule
Layers controller (HTTP, DTOs) โ†’ service (rules, transactions) โ†’ repository (SQL); dependencies point down
DTOs never expose entities in the API
Timeouts on every remote call
Retries only idempotent, transient failures; exponential backoff with jitter; a limit
Circuit breaker fail fast while a dependency is down, probe again later
Messaging at-least-once delivery: idempotent consumers, dead-letter queue
Outbox write the event in the same transaction as the data, relay it afterward
Saga a chain of local transactions with compensations instead of a distributed transaction
Reactive vs virtual threads virtual threads for plain request/response; reactive for streaming with backpressure
DOCKERFILE
FROM eclipse-temurin:25-jdk AS build
WORKDIR /app
COPY . .
RUN ./mvnw -q package -DskipTests

FROM eclipse-temurin:25-jre
WORKDIR /app
COPY --from=build /app/target/app.jar app.jar
USER 1000
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75"
ENTRYPOINT ["java", "-jar", "app.jar"]

See Layered Architecture, Microservices, Messaging with Kafka and RabbitMQ, Reactive Programming, Docker for Java Developers and Deploying Java Applications.

Classic traps: rs.getInt() turns SQL NULL into 0; concatenating values into SQL or JPQL; forgetting to use the return value of merge(); @Transactional on a self-invoked or private method; a checked exception that commits instead of rolling back; returning entities from controllers (lazy loading errors, leaked fields); creating a new ObjectMapper or HttpClient per request; and treating a 404 from HttpClient as if it were an exception.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the JDBC example, the second UPDATE breaks a CHECK constraint and the code calls rollback(). What happens to the first UPDATE?

    With autocommit off, both statements belong to one transaction, and rollback() undoes everything since the last commit.
  2. 2. A Spring @Transactional method throws a checked IOException. By default, what does Spring do?

    The default rule rolls back on RuntimeException and Error only. Use rollbackFor to change it.
  3. 3. HttpClient.send() gets a 404 response from the server. What happens?

    HTTP error statuses are normal responses. Exceptions are only for failed exchanges such as refused connections or timeouts.
  4. 4. Which Spring Boot test annotation starts only the web layer and gives you MockMvc?

    @WebMvcTest is a slice test: controllers, JSON conversion and MockMvc, but not services or repositories, which you replace with @MockitoBean.

Summary

  • Build: mvnw clean verify or gradlew build; know scopes and configurations, and pin versions with BOMs.
  • JDBC: PreparedStatement for every value, try-with-resources, autocommit off for transactions, batches for bulk writes, a pooled DataSource.
  • Jackson: one shared ObjectMapper, JavaTimeModule with ISO dates, TypeReference for generics, annotations to shape JSON.
  • JUnit 6: @Test, lifecycle annotations, parameterized tests, assertThrows and assertAll; stub queries, verify commands.
  • HTTP: status codes and method semantics; HttpClient returns error statuses instead of throwing.
  • JPA and Spring: owning sides and lazy fetching, entity states, proxies behind @Transactional, constructor injection, slice tests, and DTOs at the API boundary.

Next: Advanced Java Interview Questions, where you'll practice explaining these topics the way interviewers expect.