Spring Boot is the most common way to build Java back ends, and the skill that turns Core Java knowledge into a job-ready Java Full Stack profile. This guide walks through building a real REST API: the build tool, your first endpoints, a MySQL database with Spring Data JPA, entity relationships, error handling, configuration profiles, security and testing, finishing with the backend questions interviewers ask freshers.
If you are still learning the language itself, start with our Core Java guide; Spring Boot relies heavily on interfaces, generics, lambdas, Optional and records.
Contents
- 1. Maven: the build tool
- 2. Your first REST API
- 3. MySQL basics for Java developers
- 4. Connecting MySQL with Spring Data JPA
- 5. Hibernate and JPA explained
- 6. Entity relationships: @OneToMany and @ManyToOne
- 7. Exception handling with @ControllerAdvice
- 8. Profiles and application properties
- 9. Spring Security basics
- 10. Testing with Mockito and MockMvc
- 11. Java backend interview questions
1. Maven: the build tool
Maven downloads the libraries your project needs, compiles the code, runs the tests and packages the application. Every Maven project has a pom.xml that names the project, lists its dependencies and defines the build; adding a library usually means adding a few lines there. (Gradle is an alternative that does the same job.)
mvn compile: compile the code.mvn test: run the unit tests.mvn package: build a JAR or WAR file.mvn clean: remove old build files.
Maven makes the build identical on every laptop and on the build server. Common problems are clashing dependency versions, tests that fail only on the server because they rely on local files, and forgetting to run clean after changing the project structure.
2. Your first REST API
The first goal is a small API that returns and saves data, so you can see a request travel from the client to the database and back.
- Create a project at Spring Initializr with the Spring Web and Spring Data JPA dependencies.
- Write a class that holds the data, such as a Student with a name and course.
- Write a
@RestControllerwith a GET method that returns all students as JSON and a POST method that saves a new one. - Run the application and test GET in a browser and POST with Postman.
@RestController
@RequestMapping("/api/students")
public class StudentController {
private final StudentService service;
public StudentController(StudentService service) { this.service = service; }
@GetMapping
public List<Student> all() { return service.findAll(); }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Student create(@RequestBody Student s) { return service.save(s); }
}The controller receives its service through the constructor: that is dependency injection, and it makes the controller easy to test. Keep the first version small; once it works, add validation, error messages and a test for one endpoint. For a complete validation exercise, follow the Spring Boot request validation task API project.
3. MySQL basics for Java developers
Most Java Full Stack applications store data in a relational database such as MySQL. A table stores one kind of thing, each row is one record, a primary key (such as customer_id) identifies each row, and a foreign key links a row to another table, such as an order belonging to a customer.
The SQL a Java developer uses most is CREATE TABLE, INSERT, UPDATE and DELETE, SELECT with WHERE and JOIN, and indexes on columns used in searches. Even when JPA writes the SQL for you, check the queries it generates when a page is slow. Practice: design books, members and loans tables for a small library, then write queries for overdue loans and the most borrowed books. For deeper SQL, see our SQL guide.
4. Connecting MySQL with Spring Data JPA
Add Spring Data JPA and the MySQL driver, then configure the connection in application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/coursedb
spring.datasource.username=appuser
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=updateRead the password from an environment variable rather than writing it in the file. ddl-auto=update is convenient while learning; real projects use migration tools such as Flyway. Then define an entity and a repository:
@Entity
public class Course {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private int durationMonths;
// getters and setters
}
public interface CourseRepository extends JpaRepository<Course, Long> {
List<Course> findByTitleContaining(String text);
}You write no SQL for basic operations: save(), findById(), findAll() and deleteById() come free, and Spring builds queries from method names such as findByTitleContaining. Inject the repository into a service and call the service from the controller, keeping database logic out of controllers. Common errors: “Communications link failure” (MySQL not running or wrong host/port), “Access denied” (wrong credentials or rights) and “Table not found” (entity and table names differ).
5. Hibernate and JPA explained
JPA is the Java standard for mapping classes to tables, and Hibernate is the library that implements it behind Spring Data. A class marked @Entity becomes a table, each object a row and each field a column; @Id marks the primary key.
The lazy-loading trap catches most beginners: related data is often loaded only when you use it, so reading it outside a transaction causes errors, and reading it in a loop causes many extra queries. Turn on SQL logging while learning and watch what runs. Practice: map Customer and Order classes, save one customer with three orders, read them back and print the SQL.
6. Entity relationships: @OneToMany and @ManyToOne
A course has many enrollments, and each enrollment belongs to one course. JPA maps this to a foreign key:
@Entity
public class Enrollment {
@Id @GeneratedValue private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "course_id")
private Course course;
}
@Entity
public class Course {
@Id @GeneratedValue private Long id;
@OneToMany(mappedBy = "course")
private List<Enrollment> enrollments = new ArrayList<>();
}The many side owns the foreign key. mappedBy tells Hibernate the key is managed by the course field in Enrollment; without it, Hibernate creates an unnecessary join table. Prefer LAZY fetching; EAGER can pull far more data than you need.
- LazyInitializationException: lazy data accessed outside a transaction. Load what you need inside the service method, with a fetch join or an entity graph.
- N+1 queries: looping over courses and touching each one’s enrollments fires one query per course. Use
JOIN FETCHin a repository query. - Infinite JSON recursion: returning entities with two-way relationships from an API loops forever. Return DTOs or records instead.
- When adding a child, update both sides in memory with a helper method.
7. Exception handling with @ControllerAdvice
When something goes wrong, an API should return a clear error with the right HTTP status, not a stack trace. First, a custom exception thrown from the service layer:
public class CourseNotFoundException extends RuntimeException {
public CourseNotFoundException(Long id) { super("Course not found: " + id); }
}
// in the service:
repository.findById(id).orElseThrow(() -> new CourseNotFoundException(id));Then one global handler for every controller:
@RestControllerAdvice
public class ApiErrorHandler {
@ExceptionHandler(CourseNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, String> notFound(CourseNotFoundException ex) {
return Map.of("error", ex.getMessage());
}
}Handle MethodArgumentNotValidException in the same class to return 400 Bad Request with each invalid field and its message, so the front end can show it beside the right input. Add a fallback for Exception.class that returns 500 with a generic message and logs the real error on the server. Never send stack traces or database details to the client.
8. Profiles and application properties
Your laptop uses a local database; production uses another with real passwords. Settings live in application.properties (or .yml), and you can add your own keys such as app.page-size=20, read with @Value("${app.page-size}") or, for groups of settings, a @ConfigurationProperties(prefix = "app") class.
Create one file per environment, such as application-dev.properties and application-prod.properties, and activate one with spring.profiles.active=dev or java -jar app.jar --spring.profiles.active=prod. Profile settings override the shared file, and @Profile("dev") creates a bean only in that profile, for example a sample-data loader. Never commit real passwords: reference environment variables such as ${DB_PASSWORD}, which is also how cloud platforms configure apps. Watch for forgetting to activate a profile and for typos in property names, which Spring silently ignores.
9. Spring Security basics
Add Spring Security and every endpoint suddenly asks for a login. Two ideas make it manageable: authentication (who are you?) and authorisation (what may you do?). Every request passes through a filter chain that you configure:
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/courses/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}Disabling CSRF is common for stateless token-based APIs; keep it for browser forms with sessions. Never store plain passwords: use BCryptPasswordEncoder and load users through UserDetailsService. Many APIs use JWTs sent in an Authorization: Bearer header, with short lifetimes and a secret signing key. Typical beginner problems: every request returns 401 (no rule permits the endpoint), 403 on POST (CSRF still on), and roles not matching because hasRole("ADMIN") expects the stored authority ROLE_ADMIN.
10. Testing with Mockito and MockMvc
Unit-test service logic with Mockito by replacing the repository with a mock, so tests run in milliseconds without a database:
@ExtendWith(MockitoExtension.class)
class CourseServiceTest {
@Mock CourseRepository repository;
@InjectMocks CourseService service;
@Test
void throwsWhenCourseMissing() {
when(repository.findById(99L)).thenReturn(Optional.empty());
assertThrows(CourseNotFoundException.class, () -> service.getCourse(99L));
}
}Test controllers with @WebMvcTest(CourseController.class), which starts only the web layer; mock the service and send fake requests:
mockMvc.perform(get("/api/courses/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Java Full Stack"));Test the error paths too: a missing course should return 404 and an invalid body 400. Start with business rules in services, then each endpoint’s success and main failure responses, then edge cases. Name tests after the behaviour, such as returns404WhenCourseMissing, and run them in your CI pipeline on every push.
11. Java backend interview questions
- What is dependency injection? Spring supplies a class with the objects it depends on, usually through the constructor, which also makes the class easy to test.
- What is a REST controller? A class that maps HTTP requests to Java methods and returns data Spring serialises as JSON.
- What is a repository? The component that reads and writes stored records, such as finding a product by ID.
- What is a DTO? A data transfer object defining the fields an API receives or sends, keeping internal entity fields out of responses.
- What is a path variable? Part of the URL path read by the controller: in
/products/42, 42 identifies the product. - Which status codes matter most? 201 Created for a new resource (with a Location header), 400 for invalid input, 404 for a missing record, and 500 with a generic message for unexpected errors.
- What does Bean Validation check? Declared constraints such as a required name or a minimum quantity; business rules such as available stock need separate checks.
- What does a transaction protect? Related operations, such as updating stock and recording a sale, succeed or roll back together.
- What is optimistic locking? A version field detects conflicting updates, so a stale update fails instead of overwriting newer data.
- What is an enum? A fixed set of named values such as PENDING, PAID and CANCELLED, which can also have fields and methods.
- Unit test vs integration test? A unit test checks one piece in isolation; an integration test checks that components such as a controller and the database layer work together.
- Why paginate responses? To control response size, using a stable sort so records appear in a predictable order across pages.
For a longer set of questions across Java, Spring Boot, databases and testing, see the Java Full Stack questions and answers.
Learn Spring Boot with ScholarLogic
Spring Boot, JPA, MySQL and testing are taught through projects in the Java Full Stack course in Bangalore at ScholarLogic, BTM Layout. Book a free demo class and a counsellor will share the fee and the next batch dates. To book, call 78923 93639.
