Backend (Spring Boot) Flashcards

1
Q

What is DBeaver?

A

A free and open source universal database tool for developers and database administrators.

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

What is Maven (with command mvn)?

A

Maven is a build automation tool used primarily for Java projects. Unlike earlier tools like Apache Ant, it uses conventions for the build procedure, and only exceptions need to be written down. An XML file describes the software project being built, its dependencies on other external modules and components, the build order, directories, and required plug-ins.

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

What is the JVM (Java Virtual Machine)?

A

It is a specification that provides runtime environment in which java bytecode can be executed. A JVM is platform dependent because configuration of each OS differs.

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

What is the JRE (Java Runtime Environtment)?

A

It is the implementation of JVM. It physically exists. It contains a set of libraries and other files that JVM uses at runtime.

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

What is the JDK (Java Development Kit)?

A

It is a software development environment used for developing Java applications and applets. It includes the JRE, an interpreter/loader (Java), a compiler (Javac), an archiver (Jar), a documentation generator (Javadoc) and other tools needed in Java development.

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

What is Spring?

A

It is a framework that helps build web applications. It takes care of dependency injection, handles transactions, implements an MVC framework and provides foundation for the other Spring frameworks (including Spring Boot).

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

What is Spring Boot?

A

While you can do everything in Spring without Spring Boot, Spring Boot helps you get things done faster:

  • Simplifies Spring dependencies, no more version collisions.
  • Can be run straight from a command line without an application container.
  • Build more with less code: no need for XML, auto-configuration
  • Useful tools for running in production, database initialization, environment specific config files, collecting metrics.

Simply put: Spring Boot = (Spring Framework) + (Embedded HTTP servers e.g. Tomcat, Jetty) - (XML <bean> configuration or @Configuration)</bean>

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

What is a POM?

A

A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects.

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

What are the development requirements for Spring?

A
  • Java JDK: $ java -version and $ javac -version
  • Maven: $ mvn -v
  • Gradle: $ gradle -v
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is Spring Initializr?

A

Spring Initializr provides an extensible API to generate quickstart projects. It provides a simple web UI to configure the project to generate and endpoints that you can use via plain HTTP.

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

What is the mvnw file which comes in the Spring Initializr zip file?

A

A maven wrapper used to run some commands without having maven installed on the system.

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

$ mvn spring-boot:run

A

Compile and run an application using maven’s run goal.

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

What is the Super POM?

A

The Super POM is Maven’s default POM. All POMs extend the Super POM unless explicitly set, meaning the configuration specified in the Super POM is inherited by the POMs you created for your projects.

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

What is the use of parent POMs?

A

Maven also supports the notion of a parent POM. A parent POM enables you to define an inheritance style relationship between POMs. POM files at the bottom of the hierarchy declare that they inherit from a specific parent POM. The parent POM can then be used to share certain properties and details of configuration.

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

What is JPA?

A

Java Persistence API, the official API and ORM (Object Relational Mapping) for working with relational data in Java. It is only a specification and not a concrete implementation.

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

What are implementations of JPA?

A
  • Hibernate with commercial support from Red Hat (72% marketshare)
  • EclipseLink: reference implementation (13% marketshare)
  • OpenJPA (2% marketshare)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the use of JPA?

A

One API will support many relational databases so that developers get database independence.

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

How to register a Java class to JPA persistence?

A

JPA classes are required to:

  1. Be identified as being a JPA entity class with @Entity.
  2. Have a default constructor.
  3. At least have one property defined as the primary key.

Example:

import javax.persistence.*;

@Entity

public class Author {

    @Id

    @GeneratedValue(strategy = GenerationType.AUTO)

    private Long id;

    private String firstName;

    private String lastName;

    public Author(String firstName, String lastName) {

        this. firstName = firstName;
        this. lastName = lastName;

    }

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

Define relationships with JPA.

A

Must be defined on two JPA classes:

  • @OnetoOne
  • @ManyToOne
  • @OneToMany
  • @ManyToMany

Example: many-to-many relationship between authors and books with a single join table.

@ManyToMany(mappedBy = "authors")
private Set books = new HashSet();
...
@ManyToMany
@JoinTable(name = "author_book", joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name = "author_id"))
private Set authors = new HashSet();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the equals() and hashcode() methods from java.lang.Object?

A

For comparing objects:

  • equals(Object obj): indicates whether some other object passed as an argument is “equal to” the current instance. The default implementation provided by the JDK is based on memory location — two objects are equal if and only if they are stored in the same memory address.
  • hashcode(): returns an integer representation of the object memory address. By default, this method returns a random integer that is unique for each instance, even between several executions of a program.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is advised to Java developers as for the equals() and hashcode() methods for large projects?

A

The default implementation is not enough to satisfy business needs. As per the Java documentation, developers should override both methods in order to achieve a fully working equality mechanism regardless of the memory addresses — it’s not enough to just implement the equals() method.

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

What is the relation between equals() and hashcode()?

A

If two objects are equal according to the equals(Object) method, then calling the hashcode()method on each of the two objects must produce the same integer result.

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

What are Spring Data repositories?

A

A Spring Data repository has methods for retrieving domain objects. These methods delegate to a specialized Repository object such that alternative storage implementations may be interchanged.

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

What is the purpose of Spring Data repositories?

A

Allow to easily subsitute the persistence layer.

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

What is the difference between a directory and a package in a Java project?

A

If configured correctly, adding a folder inside src/ is the same as adding a package from File > New Package using an IDE.

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

How is defined the name of a package?

A

When you create a package/directory under src/ the package name starts from the first subdirectory after src/. So, src/com/sub/test will be package com.sub.test.

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

How to create a Spring Data repository?

A

In the app directory, create a repositories/ directory. To inject Spring Data into a particular model, create a public interface like the following:

(Note: IdType can be Long, Int…)

package ###.repositories
import ####.model.MyModel
import org.springframework.data.repository.CrudRepository

public interface MyModelRepository extends CrudRepository < MyModel, IdType > { }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

How to populate the database with some initial data to play with during the development phase?

A

Create a bootstrap directory in the app directory, then create a DevBootstrap.java file. Example with Authors and Books:

(Note: InitData() is a function where data is created and saved to the database).

@Component
public class DevBootstrap implements ApplicationListener {

    private AuthorRepository authorRepository;
    private BookRepository bookRepository;
public DevBootstrap(AuthorRepository authorRepository, BookRepository bookRepository) {
    this.authorRepository = authorRepository;
    this.bookRepository = bookRepository;
} ~~~

@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    initData();
}

private void initData() { ... } } ~~~
29
Q

What is the Spring Web MVC framework designed around?

A

The Spring Web MVC is designed around a DispatcherServlet that handles all HTTP requests and responses.

30
Q

What is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet?

A
  1. After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.
  2. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.
  3. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request.
  4. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser.
31
Q

How to configure a controller in Spring?

A
  1. Annotate Controller class with @Controller.
  2. Map methods and/or class to HTTP request paths using @RequestMapping.

Example:

@Controller
public class HelloController { 
   private BookRepository = bookRepository;

public BookController(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
~~~

@RequestMapping(value = “/books”, method = RequestMethod.GET)
public String getBooks(Model model) {
model.addAttribute(“books”, bookRepository.findAll());
return “books”;
}
}
~~~

32
Q

What does the @Table annotation means? If not used, what happen?

A

@Table(name=table_name) maps the entity with the table. If no @Table is defined, the default value is used: the class name of the entity.

33
Q

What does the @Id annotation means?

A

@Id declares the identifier property of the entity.

34
Q

What does the @JoinColumn means?

A

@JoinColumn indicates the entity is the owner of the relationship: the corresponding table has a column with a foreign key to the referenced table.

35
Q

What does the mappedBy attribute means in a relationship e.g. @ManyToMany()?

A

mappedBy indicates the entity is the inverse of the relationship.

36
Q

What are the three most common generation strategies for the @GeneratedValue field annotation? Describe them succinctly.

A
  1. @GeneratedValue(strategy = GenerationType.AUTO): lets the persistence provider choose the generation strategy. E.g. Hibernate usually selects GenerationType.Sequence.
  2. @GeneratedValue(strategy = GenerationType.IDENTITY): auto-incremented value, very efficient from a database POV but prevent Hibernate to use some optimization techniques like JDBC batching.
  3. @GeneratedValue(strategy = GenerationType.SEQUENCE): get the next value from a database sequence. Requires few additional SQL select statements.
37
Q

How to add a unique constraint to a field?

A
@Entity
@Table(name = "users", 
       uniqueConstraints = {
           @UniqueConstraint(columnNames = {
               "username"
        })
})
38
Q

What does the @NotBlank field annotation does?

A

It validates that the annotated string is not null or empty.

39
Q

What is the difference between @NotBlank and @NotEmpty?

A

@NotEmpty ignores trailing whitespaces.

40
Q

What is the difference between the FetchType.LAZY and FetchType.EAGER for relationships?

A

Suppose you have two entities and there is a relationship between them.

Now when you load entity1 from the database, JPA loads its fields. But you have two options for entity2: to load it together with the rest of the fields (i.e. eagerly) or to load it on-demand (i.e. lazily) when you call the entity1’s getSomeField() method.

41
Q

In which cases is it preferable to use lazy loading over eager loading?

A
  • When an entity has many other entities through @OneToMany or @ManyToMany, it is not efficient to load all the other entities when they are not needed.
  • For @OneToOne, eager loading is generally used.
42
Q

What is the difference between the @Column length attribute, the @Size annotation and the @length annotation?

A
  1. @Column is a JPA annotation and the length attribute is used by the schema generation tool to set the associated SQL column length.
  2. @Size is a Bean Validation annotation that validates that the associated String has a value whose length is bounded by the minimum and maximum values. It is preferable to @Length as it is more generic.
  3. @Length is a Hibernate specific annotation and has the same meaning as @Size.
43
Q

What is the Optional<t> type? What is its purpose?</t>

A

It is a container type for a value which may be absent. It helps deal with NullPointerException when a developer does not add a null check in the code.

44
Q

When is Optional most commonly used?

A

To check if an entity is present in a database: e.g. Optional<user> findUserById(String userId);</user>

45
Q

How to return a default value if Optional is empty?

A
  1. Using orElse(): User finalUser = optionalUser.orElse(new User(“Unknown User”));
  2. Using orElseget(): User finalUser = optionalUser.orElseGet(() -> { return new User(“0”, “Unknown User”); });
46
Q

How to throw an exception when Optional is empty?

A

Using orElseThrow():

optionalUser.orElseThrow( () -> new ResourceNotFoundException("User not found with userId " + userId); );
47
Q

What is the purpose of a JSON Web Token (JWT)?

A

Used to prove that the sent data was actually created by an authentic source.

48
Q

How is a JWT composed?

A

It is composed of a header, a payload and a signature. The data inside a JWT is encoded and signed, not encrypted. So JWT do not guarantee any security for sensitive data.

49
Q

How are JWT used?

A
50
Q

What does the @EnableWebSecurity annotation means?

A

Primary Spring Security annotation used to enable web security in a project.

51
Q

What does the @EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true) annotation means?

A

Used to enable method level security based on annotations: @Secured, @RolesAllowed, @PreAuthorize and @PostAuthorize.

52
Q

What does the security annotation @Secured means and how to use it?

A

Used to protect controller/service methods like the following:

@Secured("ROLE_ADMIN")
Some method...

@Secured({"ROLE_USER", "ROLE_ADMIN"})
Some method...

@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
Some method...
53
Q

How to use the @RolesAllowed security annotation?

A
@RolesAllowed("ROLE_ADMIN")
Some method...
54
Q

What is the purpose of the @PreAuthorize and @PostAuthorize security annotations?

A
  • @PreAuthorize(): decide whether a method can actually be invoked or not.
  • @PostAuthorize(): less commonly used, perform access-control check after the method has been invoked.
55
Q

What is the WebSecurityConfigurerAdapter from Spring Security?

A

This class implements Spring Security’s WebSecurityConfigurer interface. It provides default security configurations and allows other classes to extend it and customize the security configurations by overriding its methods.

56
Q

What is the purpose of having a CustomUserDetailsService that implements UserDetailsService interface and provides the implementation for loadUserByUsername() method?

A

To authenticate a user or perform various role-based checks, Spring Security needs to load users details.

57
Q

What does the loadUserByUsername() method of the CustomUserDetailsService class should return?

A

A custom UserDetails class that implements the Spring Security UserDetails interface, extended by a UserPrincipal class used by Spring Security to perform authentication and authorization.

58
Q

What is the custom JwtAuthenticationEntryPoint class?

A
  • This class is used to return a 401 unauthorized error to clients that try to access a protected resource without proper authentication.
  • Its commence() method is called whenever an exception is thrown due to an unauthenticated user trying to access a resource that requires authentication.
  • It implements Spring Security’s AuthenticationEntryPoint interface.
59
Q

What is the custom JwtAuthenticationFilter class?

A

Use to implement a filter that:

  • reads JWT authentication token from the Authorization header of all the requests,
  • validates the token,
  • loads the user details associated with that token,
  • sets the user details in Spring Security’s SecurityContext.
60
Q

What is the Spring Security’s SecurityContext used for?

A
  • Spring Security uses the user details to perform authorization checks.
  • We can also access the user details stored in the SecurityContext in our controllers to perform our business logic.
61
Q

What is the AuhtenticationManagerBuilder class?

A

AuthenticationManagerBuilder is used to create an AuthenticationManagerinstance which is the main Spring Security interface for authenticating a user.

You can use AuthenticationManagerBuilder to build in-memory authentication, LDAP authentication, JDBC authentication, or add your custom authentication provider such as customUserDetailsService and passwordEncoder.

62
Q

What is the HttpSecurity class from Spring Security?

A

The HttpSecurity configurations are used to configure security functionalities like csrf, sessionManagement, and add rules to protect resources based on various conditions.

For example, we can permit access to static resources, few other public APIs to everyone, authorize custom JWT security filter and restricting access to other APIs to authenticated users only.

63
Q

What does @Transactional means?

A

The transactional annotation itself defines the scope of a single database transaction. The database transaction happens inside the scope of a persistence context.

64
Q

What is the persistence context in JPA?

A

The persistence context is in JPA the EntityManager, implemented internally using an Hibernate Session (when using Hibernate as the persistence provider).

The persistence context is just a synchronizer object that tracks the state of a limited set of Java objects and makes sure that changes on those objects are eventually persisted back into the database.

65
Q

What is the JwtTokenProvider class?

A

A utility class used to generate a JWT after a user logs in successfully, and validating the JWT sent in the Authorization header of the requests.

The utility class reads the JWT secret and expiration time from application.properties.

66
Q

What is a JWT secret?

A

The secret is a symmetric key known by both the sender and the receiver.

The secret can an arbitrary string of bytes. It can be generated or purposely chosen.

It is negotiated and distributed out of band to the intended recipient of the token.

67
Q

What is the purpose of the @AuthenticationPrincipal annotation?

A

It is used to access the currently authenticated user in the controllers. The CurrentUser annotation is a wrapper around the @AuthenticatedPrincipal to reduce the dependency on SpringSecurity in case we remove it.

68
Q

What are @GetMapping and @PostMapping?

A

They are shortcuts for @RequestMapping(method = RequestMethod.GET) to handle HTTP GET requests and They are shortcuts for @RequestMapping(method = RequestMethod.POST) to handle HTTP POST requests.

69
Q
A