Week 10 Flashcards

1
Q

What is Spring Data?

A

Spring Data is a part of the Spring Framework that simplifies data access and makes working with databases easier. It provides a consistent model to interact with a wide range of data storage technologies, including relational databases (e.g., MySQL, PostgreSQL) and NoSQL databases (e.g., MongoDB, Cassandra).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the main goals of Spring Data?

A

Simplify data access and persistence.
Provide a consistent programming model for different types of databases.
Minimize boilerplate code in data access layers.
Offer integration with various data stores (relational and NoSQL).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does Spring Data simplify data access in Java applications?

A

Spring Data abstracts common persistence operations, like saving, deleting, and querying, through repository interfaces, eliminating the need to write complex SQL queries or boilerplate code. It generates implementation code based on method names and annotations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the role of repositories in Spring Data?

A

Repositories provide an interface-based abstraction for data access operations. They handle CRUD (Create, Read, Update, Delete) operations and allow querying by automatically generating SQL based on method names.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can Spring Data work with databases other than relational ones? Name examples.

A

Yes, Spring Data works with both relational and NoSQL databases. Examples include:

Relational: MySQL, PostgreSQL
NoSQL: MongoDB, Cassandra, Redis, Couchbase

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is JPA, and how does it differ from Hibernate?

A

JPA (Java Persistence API) is a specification that defines how Java objects should be mapped to database tables. Hibernate is an implementation of JPA, providing additional features beyond the specification. While JPA defines the API, Hibernate offers concrete tools for working with persistence.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How is Hibernate related to JPA?

A

Hibernate is an implementation of JPA. It adheres to the JPA standard while also offering extended features like custom caching mechanisms and native SQL support.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What role does Spring Data JPA play in the persistence layer?

A

Spring Data JPA provides the glue between Spring’s repository abstraction and the JPA implementation. It automates many common data access tasks and provides features like query methods and pagination with minimal code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What benefits does Spring Data JPA provide over using plain JPA?

A

Reduces boilerplate code with auto-generated repository methods.
Simplifies query creation using method names.
Adds additional features like pagination and sorting.
Provides default implementation of common data access operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Can Spring Data JPA work with ORM frameworks other than Hibernate?

A

Yes, Spring Data JPA can work with other JPA-compliant ORM frameworks, like EclipseLink and OpenJPA, though Hibernate is the most commonly used implementation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is CrudRepository in Spring Data?

A

CrudRepository is a Spring Data interface that provides methods for basic CRUD operations like save(), findById(), findAll(), deleteById(), etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is JpaRepository in Spring Data?

A

JpaRepository is an interface in Spring Data JPA that extends CrudRepository and provides additional JPA-specific methods, such as batch operations and flushing changes to the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How does JpaRepository extend CrudRepository?

A

JpaRepository extends CrudRepository by adding JPA-specific functionality, such as support for batch operations, pagination, sorting, and finer control over persistence context flushing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Which repository provides pagination and sorting methods by default?

A

JpaRepository provides pagination and sorting methods by default.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

When would you choose to use CrudRepository over JpaRepository?

A

You would use CrudRepository when you only need basic CRUD operations and do not require advanced JPA-specific features like pagination and sorting.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are property expressions in Spring Data?

A

Property expressions are used to define query methods in Spring Data repositories. The method names contain field names and operations that Spring Data translates into SQL queries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How does Spring Data generate queries from method names?

A

Spring Data parses the method names of repository interfaces and converts them into queries by identifying property names and keywords like findBy, countBy, deleteBy, and logical operators (e.g., And, Or).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are some examples of property expressions used in repository method names?

A

findByLastName(String lastName)
findByAgeGreaterThan(Integer age)
countByStatus(String status)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How can you use the And and Or keywords in property expressions?

A

You can chain properties using And and Or keywords to create complex queries. For example:
findByFirstNameAndLastName(String firstName, String lastName)
findByAgeGreaterThanOrAgeLessThan(Integer minAge, Integer maxAge)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Can property expressions handle relationships between entities (e.g., nested properties)?

A

Yes, Spring Data can handle nested properties in entity relationships. For example, findByAddressCity(String city) can be used if Address is an entity linked to the main entity with a city field.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the purpose of the @Entity annotation in JPA?

A

The @Entity annotation is used to mark a class as a JPA entity, indicating that it should be mapped to a database table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does the @Id annotation signify in JPA?

A

The @Id annotation marks a field as the primary key of the entity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the role of the @GeneratedValue annotation?

A

The @GeneratedValue annotation is used to indicate that the value of the primary key should be automatically generated by the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How does the @Table annotation help in mapping entities?

A

The @Table annotation is used to specify the table name in the database to which the entity is mapped. It can also define schema and other table-level constraints.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the difference between @OneToMany and @ManyToOne annotations?

A

@OneToMany defines a one-to-many relationship, where one entity is related to many entities of another type.
@ManyToOne defines a many-to-one relationship, where many entities are related to one entity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the @Transactional annotation used for in Spring?

A

The @Transactional annotation is used to mark a method or class as transactional, meaning that all operations within the transaction are treated as a single unit and will either complete successfully or be rolled back in case of failure.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What does the propagation attribute in @Transactional control?

A

The propagation attribute controls how transactions are propagated when a method is called within an existing transaction. For example, Propagation.REQUIRED will reuse the existing transaction if present, while Propagation.REQUIRES_NEW will start a new transaction.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are the different isolation levels supported by @Transactional?

A

The supported isolation levels include:

READ_UNCOMMITTED
READ_COMMITTED
REPEATABLE_READ
SERIALIZABLE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How does @Transactional help ensure consistency in database operations?

A

By managing transactions automatically, @Transactional ensures that all operations within the transaction succeed or fail together, maintaining data consistency and preventing partial updates.

25
Q

Can @Transactional be applied at the method and class level? How does it differ?

A

Yes, @Transactional can be applied at both levels. If applied at the class level, it applies to all methods in the class. If applied at the method level, it applies only to that specific method. Method-level annotation can override class-level settings.

26
Q

What does ACID stand for in database transactions?

A

ACID stands for Atomicity, Consistency, Isolation, and Durability, which are properties that ensure reliable processing of transactions.

27
Q

What is the “Atomicity” property of a transaction?

A

Atomicity ensures that all operations within a transaction are completed successfully or none at all, meaning transactions are all-or-nothing.

28
Q

How does “Consistency” ensure data validity in transactions?

A

Consistency ensures that a transaction brings the database from one valid state to another, maintaining all defined rules and constraints.

28
Q

What is the significance of “Isolation” in transactions?

A

Isolation ensures that the intermediate state of a transaction is invisible to other transactions, preventing them from accessing partial results.

29
Q

What is meant by “Durability” in ACID properties?

A

Durability ensures that once a transaction is committed, its changes are permanently saved and survive system failures.

29
Q

What is transaction propagation in Spring?

A

Transaction propagation defines how transactions relate to each other when one method calls another. It controls whether a new transaction should be started or the existing one should be continued.

30
Q

What does Propagation.REQUIRED do in transaction management?

A

Propagation.REQUIRED reuses an existing transaction if present, or starts a new one if no transaction is ongoing.

31
Q

What is the difference between Propagation.REQUIRES_NEW and Propagation.REQUIRED?

A

Propagation.REQUIRES_NEW always starts a new transaction, suspending any existing ones, while Propagation.REQUIRED reuses the current transaction if it exists.

32
Q

What happens if a method with Propagation.NEVER is called within a transaction?

A

If Propagation.NEVER is used and the method is called within a transaction, an exception is thrown because the method should not be executed in a transactional context.

33
Q

How does Propagation.MANDATORY behave in transaction propagation?

A

Propagation.MANDATORY requires that a transaction must already be present. If there is no existing transaction, an exception is thrown.

33
Q

What is Spring Boot Actuator?

A

Spring Boot Actuator is a module in Spring Boot that provides production-ready features like monitoring, metrics, health checks, and application management.

34
Q

What are the main purposes of Spring Boot Actuator?

A

Monitor application health.
Expose operational information (metrics, health, environment).
Manage applications in production environments.

34
Q

How does Spring Boot Actuator help in monitoring and managing applications?

A

Actuator exposes a set of REST endpoints that provide details about application status, metrics, configuration, and environment. These endpoints allow developers and administrators to monitor and interact with the application.

35
Q

How can you enable or disable Actuator endpoints?

A

Actuator endpoints can be enabled or disabled in the application.properties or application.yml configuration files by setting properties like management.endpoint.<endpoint>.enabled.</endpoint>

36
Q

What are the default Actuator endpoints in a Spring Boot application?

A

Some default Actuator endpoints are:

/actuator/health
/actuator/info
/actuator/metrics
/actuator/env
/actuator/loggers

37
Q

What does the /actuator/health endpoint provide?

A

The /actuator/health endpoint provides a health status of the application, indicating whether it is running and functioning correctly.

38
Q

How does the /actuator/info endpoint work?

A

The /actuator/info endpoint exposes arbitrary application information defined by the developer, such as version, description, or other metadata.

38
Q

What information is exposed through the /actuator/metrics endpoint?

A

The /actuator/metrics endpoint exposes various application metrics like memory usage, CPU load, HTTP request statistics, and custom metrics.

39
Q

How can you customize Actuator endpoints?

A

Actuator endpoints can be customized by adding custom health indicators, info contributors, or metrics. You can also configure endpoint visibility, security, and format in the application configuration.

39
Q

Can you secure Actuator endpoints using Spring Security?

A

Yes, Actuator endpoints can be secured using Spring Security by configuring authentication and authorization policies for specific endpoints.

40
Q

What is the purpose of unit testing in the service layer?

A

Unit testing in the service layer ensures that individual business logic methods work as expected, independently of other layers like the database or controllers.

41
Q

How does Mockito help in testing service layer methods?

A

Mockito helps in testing service methods by allowing you to mock dependencies (like repositories) so that you can focus on testing the logic of the service itself without worrying about the actual data source.

42
Q

What are the common annotations used in Mockito (@Mock, @InjectMocks)?

A

@Mock is used to create mock objects for dependencies.
@InjectMocks injects the mock dependencies into the class under test.

43
Q

How can you test a method that depends on another service or repository?

A

By using @Mock to create mock objects for the dependent service or repository, and Mockito.when() to define the behavior of the mock.

44
Q

What is the role of Mockito.when() in writing unit tests?

A

Mockito.when() is used to define the behavior of a mock object when a specific method is called, allowing you to control the return values during the test.

44
Q

What is integration testing, and how does it differ from unit testing?

A

Integration testing tests how different components of an application work together, including the interaction with external systems like databases or web services, while unit testing focuses on individual components in isolation

45
Q

Why is integration testing important in Spring applications?

A

Integration testing is important to verify that the components of a Spring application, like services, repositories, and controllers, work together as expected in a real environment.

46
Q

How can Spring’s @SpringBootTest annotation be used for integration tests?

A

@SpringBootTest sets up the entire Spring application context for integration testing, allowing you to test how different layers (like services and repositories) interact.

47
Q

What is the role of an embedded database in integration testing?

A

An embedded database, like H2, provides an in-memory database for running integration tests, ensuring that tests run quickly and independently of the actual production database.

48
Q

How do you handle database initialization for integration tests?

A

Database initialization for integration tests can be handled by using scripts (schema.sql, data.sql), or by leveraging Spring’s @DataJpaTest annotation to automatically configure an embedded database.

49
Q

What is MockMvc in Spring, and why is it used for testing?

A

MockMvc is a Spring testing utility that simulates HTTP requests and responses, allowing you to test controller endpoints without deploying the application to a web server.

50
Q

How can you test a GET request using MockMvc?

A

You can test a GET request using mockMvc.perform(get(“/url”)).andExpect(status().isOk()), specifying the endpoint and verifying the response.

51
Q

How can you test a POST request using MockMvc?

A

You can test a POST request using mockMvc.perform(post(“/url”).content(jsonBody).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isCreated()).

52
Q

What is RestTemplate, and how is it used in integration testing?

A

RestTemplate is a Spring class used to make HTTP requests to RESTful web services. It can be used in integration testing to perform actual HTTP requests and verify responses from REST APIs.

53
Q

How can you verify the status code and response body in MockMvc tests?

A

You can verify the status code using .andExpect(status().isOk()) and the response body using .andExpect(content().json(expectedJson)) in MockMvc tests.

54
Q

What is the purpose of testing database interactions in Spring applications?

A

Testing database interactions ensures that the application correctly retrieves, updates, and persists data according to business logic and database constraints.

55
Q

How can you use @DataJpaTest to test repository methods?

A

@DataJpaTest sets up a minimal context with only JPA components, allowing you to test repository methods using an embedded database like H2.

56
Q

What is the role of an in-memory database like H2 in testing?

A

An in-memory database like H2 is used in testing to simulate a production-like database environment without requiring an actual database server, allowing for fast, isolated tests.

56
Q

How do you verify database state changes after executing repository methods?

A

You can verify database state changes by querying the database after executing repository methods and checking if the expected data is present or if the state has changed as expected.

57
Q

Can transactions be rolled back after database interaction tests? How?

A

Yes, transactions can be rolled back after tests by using @Transactional on the test methods. This ensures that the database is in a clean state after each test execution.