Saturday, 19 February 2022

Spring boot - Cross Origin AJAX HTTP Requests | What is CORS? | Cross Origin Resource Sharing

Spring boot - How to use Java Persistence Query Language(JPQL)? | RESTful Web Services

🚀 Master Spring Boot & JPA!

Subscribe to Ram N Java for the most simplified Java & Spring tutorials!

SUBSCRIBE TO OUR CHANNEL

How to Implement JPQL in Spring Boot REST Services

When building robust RESTful Web Services with Spring Boot, you often need more than just the default CRUD operations. JPQL (Java Persistence Query Language) allows you to write complex database queries using entity objects instead of database tables.

What is JPQL?

JPQL is a platform-independent object-oriented query language defined as part of the Java Persistence API (JPA) specification. Key benefits include:

  • Object-Oriented: You write queries against your Java entities and their properties.
  • Database Independent: JPA translates JPQL into the specific SQL dialect of your database.
  • Simplicity: It looks very similar to SQL, making it easy for developers to learn.

Using @Query with JPQL

In Spring Data JPA, you can easily use JPQL by using the @Query annotation in your Repository interfaces. For example:

@Query("SELECT u FROM User u WHERE u.email = ?1")
User findByEmail(String email);

Why use JPQL in REST APIs?

Using JPQL in your REST services allows you to handle specific business requirements like complex filtering, joining multiple entities, or performing custom aggregations that the standard findBy... methods cannot handle alone.

📥 Download Slides & Source Code!

I’ve shared the full source code and PowerPoint presentation for this JPQL implementation! Check out the download links in the YouTube video description.

Spring boot - How to use Native SQL Queries? | RESTful Web Services

🚀 Boost Your Backend Skills!

Subscribe to Ram N Java for simplified Java, Spring, and Cloud tutorials!

SUBSCRIBE TO OUR CHANNEL

Mastering Native SQL Queries in Spring Boot

While JPA and JPQL are excellent for most tasks, sometimes you need the full power and performance of Native SQL Queries. Whether you're working with complex database-specific features or optimizing performance, knowing how to execute raw SQL in Spring Boot is a vital skill for any developer.

What are Native SQL Queries?

Native SQL queries are raw SQL statements that are executed directly against your database (MySQL, PostgreSQL, Oracle, etc.). Unlike JPQL, which queries Java entities, Native SQL queries work directly with database tables and columns.

  • Performance: Fine-tune your queries for maximum speed.
  • Flexibility: Use database-specific keywords and functions.
  • Control: Complete control over the generated SQL.

Implementing @Query with nativeQuery=true

In your Spring Data JPA Repository, you can mark a query as native by setting the nativeQuery attribute to true:

@Query(value = "SELECT * FROM users WHERE status = :status", nativeQuery = true)
List<User> findByStatusNative(@Param("status") String status);

When to Use Native SQL?

Use Native SQL when you need to perform complex joins, use specialized database functions (like window functions), or when JPQL doesn't support the specific syntax required for your data access layer optimization.

📥 Download Slides & Source Code!

I’ve made the full source code and PowerPoint presentation for this tutorial available! Head over to the YouTube video description to find the download links.

Sunday, 6 February 2022

Spring boot - JUnit Integration Test. Testing JWT Tokens and UserId | RESTful Web Services

🚀 Become a Testing Pro!

Subscribe to Ram N Java for simplified tutorials on Spring Boot and Cloud security!

SUBSCRIBE TO OUR CHANNEL

JUnit Testing: Verifying JWT Tokens & User IDs in Spring Boot

Testing is a vital part of building secure and reliable RESTful Web Services. In this guide, we dive into how to use JUnit to verify that your Spring Boot application is correctly returning JWT tokens and the expected user IDs during the authentication process.

Why Test JWT & User Identity?

Security is the backbone of any enterprise application. Ensuring that your identity provider (IDP) or authentication service works as expected prevents unauthorized access and data leaks. JUnit testing allows you to:

  • Automate Security Checks: Verify authentication logic every time you change your code.
  • Validate Response Structure: Ensure your API returns the correct JSON format with the JWT token.
  • Confirm User Logic: Guarantee that the returned User ID matches the authenticated user.

Implementing the Test

We use MockMvc to simulate an authentication request and JsonPath to inspect the resulting JSON response. Here’s a conceptual look at how we assert the presence of a token:

.andExpect(jsonPath("$.token").exists())
.andExpect(jsonPath("$.userId").value(expectedUserId))

The Role of Assertions

Using assertTrue, assertNotNull, and assertEquals, we can programmatically confirm that our security layer is behaving exactly as designed, providing peace of mind before any production deployment.

📥 Get the Full Code & Slides!

I have shared the complete source code and PowerPoint presentation for this testing tutorial! Check out the download links in the YouTube video description.

Spring boot - What is H2 In-memory Database and Why Using It? | RESTful Web Services

🚀 Accelerate Your Development!

Subscribe to Ram N Java for simplified tutorials on Spring Boot and Database magic!

SUBSCRIBE TO OUR CHANNEL

Why H2 In-Memory Database is a Game Changer for Spring Boot

When you're in the early stages of development or writing unit tests, setting up a full-scale database like MySQL or Oracle can be overkill. That's where the H2 In-Memory Database shines. It’s fast, lightweight, and requires zero installation.

What is H2 Database?

H2 is an open-source SQL database written in Java. Its "in-memory" mode means that the data is stored in the system's RAM rather than on the disk. When the application stops, the data is cleared, making it the perfect tool for:

  • Rapid Prototyping: Test your JPA entities and logic instantly.
  • Unit Testing: Run your tests in an isolated, clean environment every time.
  • Zero Setup: Just add a dependency and you're ready to go.

The Magic of the H2 Console

One of the best features of H2 is the built-in web-based H2 Console. By enabling it in your application.properties, you can visualize your tables and run SQL queries directly from your browser while your Spring Boot app is running.

spring.h2.console.enabled=true

Why It Stands Out

H2 stands out because of its compatibility. It can emulate other databases like PostgreSQL or MySQL, allowing you to develop with H2 locally while using a different database in production with minimal configuration changes.

📥 Grab the Slides & Source Code!

I’ve made the PowerPoint presentation and Spring Boot source code available for free! Head over to the YouTube video description to find the download links.

Spring boot - Testing Rest Controller Methods with JUnit 5 | RESTful Web Services

🚀 Master Spring Boot Testing!

Subscribe to Ram N Java for the most simplified and practical tech tutorials!

SUBSCRIBE TO OUR CHANNEL

Testing Spring Boot REST Controllers with JUnit 5

Ensuring your API endpoints behave as expected is a critical step in professional software development. This guide focuses on testing REST Controller methods in Spring Boot using the power of JUnit 5 and MockMvc.

Why Test Your Controllers?

Controllers are the entry points to your application. Testing them allows you to verify:

  • HTTP Status Codes: Ensure you return 200 OK, 201 Created, or 404 Not Found correctly.
  • Response Body: Validate that the JSON returned contains the right data.
  • Request Mapping: Confirm that URLs and HTTP methods (GET, POST, etc.) are correctly mapped.

Key Tools: MockMvc & JUnit 5

Spring Boot provides MockMvc to simulate HTTP requests without starting a full server. Combined with JUnit 5 assertions, it becomes a powerful way to write fast, reliable tests.

mockMvc.perform(get("/users"))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$.name").value("Ram"));

Best Practices

Always aim for high test coverage but focus on meaningful scenarios. Mock your service layer using @MockBean to isolate your controller logic, making your tests truly unit-level and incredibly fast.

📥 Get the Full Source Code!

I always share the complete project source code and PowerPoint presentation for my tutorials! You can find the download links in the YouTube video description.

Saturday, 5 February 2022

Spring boot - Testing Service Layer Code with JUnit 5 & Mockito | RESTful Web Services

🚀 Master Backend Testing!

Subscribe to Ram N Java for the most simplified Java & Spring Boot tutorials!

SUBSCRIBE TO OUR CHANNEL

Testing Service Layer with JUnit 5 & Mockito

In a Spring Boot application, the Service Layer is where your core business logic lives. Testing this layer in isolation is crucial. This guide explains how to use JUnit 5 and Mockito to write fast, reliable unit tests that don't depend on a database or external services.

Why Mock the Repository?

Unit tests should be isolated. By using Mockito's @Mock, we create a "fake" version of our Repository. This allows us to:

  • Speed up tests: No need to wait for a database to start.
  • Avoid side effects: Tests won't change your actual data.
  • Test edge cases: Easily simulate scenarios like "user not found" or "database error."

Key Annotations

To set up your service layer tests, you'll primarily use these three annotations:

  • @Mock: Creates a mock instance of a dependency (like your Repository).
  • @InjectMocks: Creates an instance of the class being tested and injects the mocks into it.
  • @BeforeEach: A method that runs before every test case, usually to initialize the mocks.

Asserting Exceptions

A great test doesn't just check for success; it also verifies that your code handles errors correctly. With JUnit 5, you can use assertThrows to ensure your service throws the right exception when it encounters bad data.

assertThrows(UsernameNotFoundException.class, () -> {
    userService.getUser("wrong@email.com");
});

📥 Download the Full Code!

I’ve provided the complete Java source code and PowerPoint presentation for this Service Layer tutorial! You can find the direct download links in the description of the YouTube video above.

Tutorials