Showing posts with label Spring Framework. Show all posts
Showing posts with label Spring Framework. Show all posts

Saturday, 27 July 2019

Spring boot - How to get all loaded beans with Class Type information?

Dive into Spring Boot: Discover All Loaded Beans by Class Type!

🚀 Enjoying this content? Don't miss out on more Java and Spring Boot tips!

SUBSCRIBE TO RAM N JAVA

Introduction to Spring Beans

If you're working with Spring Boot, you've likely heard of "Beans." In simple terms, a Bean is just an object that is managed by the Spring Framework. The Spring IoC (Inversion of Control) container is responsible for creating, configuring, and managing these beans throughout their lifecycle.

Why Find Beans by Class Type?

Sometimes, your application might have multiple implementations of an interface, or you just want to verify exactly which beans of a specific type are currently loaded in your ApplicationContext. Knowing how to filter and find these beans programmatically is a powerful debugging and configuration tool.

How it Works in Spring Boot

Spring provides the ListableBeanFactory interface, which allows you to fetch all beans that match a specific class or interface type. This returns a Map where the keys are the bean names and the values are the actual bean instances.

Map<String, MyClass> beans = applicationContext.getBeansOfType(MyClass.class);

Check out more from Ram N Java:

Spring Boot - Multiple CommandLineRunner and @Order Annotation | Spring Boot tutorial

Mastering Spring Boot: Manage Multiple CommandLineRunners

🚀 Boost your Java skills today!

SUBSCRIBE TO RAM N JAVA

Handling Multiple Startup Tasks

In a real-world Spring Boot application, you often have more than one task that needs to run right after startup. Whether it's loading initial data, setting up a cache, or validating external services, you might find yourself with multiple classes implementing the CommandLineRunner interface.

The Importance of Execution Order

By default, Spring Boot doesn't guarantee the order in which these runners execute. If "Task B" depends on "Task A" being finished, you need a way to control the sequence. This is where the @Order annotation comes to the rescue. It allows you to specify exactly which runner goes first, second, and so on.

Step-by-Step Implementation

To force an order, simply add the @Order annotation to your component classes. The lower the number, the higher the priority (meaning 1 runs before 2).

@Component @Order(1) public class FirstRunner implements CommandLineRunner { ... } @Component @Order(2) public class SecondRunner implements CommandLineRunner { ... }

Pro Tip: Safe Execution

Remember that if an exception is thrown inside a run() method and not caught, it will cause the entire ApplicationContext to close. Always wrap your startup logic in a try-catch block to ensure your application remains stable even if a startup task hits a snag.


Explore More from Ram N Java:

Thursday, 4 July 2019

Spring Boot - How to schedule a task at a fixed delay? | Spring Boot - Schedule task

🚀 Love Java and Spring Boot? 🚀

SUBSCRIBE to Ram N Java for more tutorials!

Understanding Fixed Delays in Spring Boot

In the world of Spring Boot, scheduling tasks is a powerful feature that allows you to run specific blocks of code automatically at set intervals. One of the most useful ways to do this is by using a Fixed Delay.

What is a Fixed Delay?

A Fixed Delay ensures that there is a specific amount of time between the end of the last execution and the start of the next one. This is different from a "fixed rate" where tasks start on a schedule regardless of when the previous one finished.

Think of it like this: If you are washing dishes, a fixed delay means you wait 5 minutes after you finish the last plate before you start the next one. This prevents tasks from overlapping!

How to Implement It

To get started, you simply need the @Scheduled annotation. Here is a basic example of how it looks in your code:

@Scheduled(fixedDelay = 5000)
public void runTask() {
    // Your logic here
    System.out.println("Task executed after a 5-second delay!");
}

Why Use Fixed Delay?

  • Prevents Overlap: Ideal for long-running tasks that shouldn't run simultaneously.
  • Better Resource Management: Gives your system a "breather" between heavy operations.
  • Simple Configuration: Just one annotation and you're ready to go!

Check Out More Tutorials

If you found this helpful, you might enjoy these other videos from the Ram N Java channel:

Monday, 10 June 2019

How to Send/Receive Product object to/from Queue(Spring + JMS + RabbitMQ Example with Annotations)?

🚀 Master Spring Messaging!

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

SUBSCRIBE TO OUR CHANNEL

Spring JMS & RabbitMQ with Annotations

Using annotations makes Spring development faster and cleaner. In this tutorial, we "simplify" the process of sending and receiving Product Objects using Spring JMS and RabbitMQ, leveraging the power of annotations for a modern configuration.

Simplified Annotation-Driven Config

Forget the XML boilerplate. We show you how to set up your messaging infrastructure using clean Java configuration and specialized annotations:

  • @EnableJms: Activating JMS listener capabilities within your Spring configuration classes.
  • @JmsListener: Defining your consumer methods directly with annotations to automatically process messages from specific queues.
  • JmsTemplate: Using the template to easily convert and send Java objects without manual serialization.

Handling Custom Objects

We walk through a practical example of a producer sending a Product object and a consumer receiving it. You'll learn how Spring JMS works behind the scenes with RabbitMQ to handle the translation between Java objects and AMQP messages, ensuring your data arrives intact and ready for processing.

Why Annotations?

Mastering the annotation-driven approach in Spring JMS is crucial for building maintainable, modern Microservices. It keeps your code concise and allows you to focus on business logic rather than infrastructure setup. This is a must-know skill for any Java Developer working with enterprise messaging systems.

📥 Download the Source Code!

The complete Java source code and PowerPoint presentation for this annotation-based messaging tutorial are available! Check the download links in the YouTube video description above to get started.

Saturday, 20 April 2019

Spring Cache Tutorial with EhCache (How to use @CacheConfig Annotation?)

🚀 Level Up Your Java Skills! Subscribe to Ram N Java 🔔

Don't miss out on the latest Spring tutorials and coding tips!

Understanding the @CacheConfig Annotation

When working with Spring Cache, especially with providers like EhCache, you often find yourself repeating the same cache names across multiple methods. This is where the @CacheConfig annotation comes to the rescue! Let's explore how it simplifies your code.

1. What is @CacheConfig?

The @CacheConfig annotation is a class-level annotation that allows you to share common cache-related settings across all methods within that class. Instead of specifying the cacheNames attribute in every @Cacheable or @CacheEvict method, you can define it once at the top.

2. Reducing Boilerplate Code

Imagine a DAO or Service class with ten different methods, all needing to use the "employeeCache". Without @CacheConfig, you'd have to type (value="employeeCache") ten times. By adding @CacheConfig(cacheNames={"employeeCache"}) to the class declaration, your methods become much cleaner and easier to read.

3. Key Benefits for Beginners

  • Centralized Configuration: Change the cache name in one place instead of searching through every method.
  • Improved Readability: Your method annotations remain focused on their specific logic (like keys or conditions).
  • Consistency: Ensures all methods in the class are using the correct cache instance without manual errors.

4. Real-World Application

In this tutorial, we demonstrate how to apply this to an EmployeeDAO class. We see how the methods for fetching, updating, and deleting employees all benefit from this shared configuration, making the overall Spring Cache implementation much more professional.

Spring Cache Tutorial with EhCache | Spring Cache | Spring Tutorial

🚀 Level Up Your Java Career!

Join the Ram N Java family for professional-grade coding tutorials that are easy to follow.

SUBSCRIBE NOW

Mastering EhCache in Spring: Boost Performance

Slow applications frustrate users. If your Spring-based application is struggling with heavy database calls or complex calculations, it's time to implement Effective Caching with EhCache.

Why Choose EhCache?

EhCache is one of the most widely used Java-based caches because it's fast, lightweight, and scales beautifully. When integrated with Spring Cache, it allows you to store frequently accessed data in memory, reducing load times significantly.

The Goal: Stop doing the same work twice. If a user asks for data that hasn't changed, pull it from EhCache instead of hitting your database!

Key Implementation Steps

  • Configuration: Set up your ehcache.xml to define cache names and expiration times.
  • Spring Integration: Configure the EhCacheCacheManager in your Spring context.
  • Annotation Power: Use @Cacheable on methods to start saving results automatically.

Related Tutorials from Ram N Java

Level up your Spring expertise with these related videos:

How to Send an Email with Inline Resource using Annotations configuration? | Spring Java Mail

🚀 Boost Your Java Expertise!

Join the Ram N Java community for deep dives into Spring and Java development. Subscribe today!

SUBSCRIBE NOW

Sending Emails with Inline Images in Java

Standard text emails can be boring. If you want to make your email notifications stand out, adding images directly into the body of the message (inline resources) is the way to go. In this tutorial, we explore how to achieve this using Annotation-based configuration in Java Mail.

Why Inline Resources?

Unlike regular attachments that appear at the bottom of an email, inline resources allow images like logos or icons to be placed exactly where you want them in the HTML content. This provides a more professional and integrated look for your application's communication.

The Annotation Approach

Using annotations simplifies the configuration of your mail sender. By defining your JavaMailSender bean with the necessary properties (like host, port, and credentials), you create a robust foundation for sending both simple and complex messages.

How It Works: MimeMessageHelper

The key to inline images is the MimeMessageHelper. You must set the "multipart" flag to true. Once you've added your HTML text, you use the addInline() method, passing a Content-ID (CID) that matches the src="cid:..." attribute in your HTML. This tells the email client exactly where to render the image data.

Pro Tip: Keep your inline images small in file size. Large images can slow down the loading of the email and might get flagged by spam filters!


More Spring Tutorials from Ram N Java

How to Send an Email with an attachment using Annotations Configuration? | Spring Java Mail

🚀 Boost Your Spring Skills!

Join the Ram N Java family for more in-depth Java and Spring tutorials. Subscribe today!

SUBSCRIBE TO RAM N JAVA

Sending Emails with Attachments in Spring

Sending simple text emails is easy, but often you need to send files like PDFs, images, or log files as attachments. In this guide, we'll walk through how to send emails with attachments using Spring Java Mail and Annotation-based configuration.

Why Use Annotations?

Using Java-based configuration with annotations like @Configuration and @Bean makes your Spring application much more modern and readable. It eliminates the need for bulky XML files and allows you to manage your mail sender properties directly within your Java code.

Setting Up the JavaMailSender

To begin, you need to define a JavaMailSender bean. This object contains all the server details like your SMTP host, port, username, and password. By using annotations, Spring will automatically manage this bean and make it available whenever you need to send an email.

Adding Attachments with MimeMessageHelper

The MimeMessageHelper is your best friend when it comes to complex emails. To add an attachment, you simply create a new MimeMessage, wrap it in the helper, and call the addAttachment() method. You can pass a name for the file and a FileSystemResource pointing to the file on your disk.

Step-by-Step Implementation

The process is straightforward: initialize the helper with "multipart" mode enabled, set the recipient and subject, add your text body, and finally attach your file. Spring handles all the heavy lifting of encoding the file and ensuring it reaches its destination correctly.

Pro Tip: Always use a try-catch block when sending emails to handle potential MessagingExceptions, and ensure the file path you're attaching is correct!


More Spring Tutorials from Ram N Java

Friday, 5 April 2019

How to Send an Email using spring java mail with Annotations Configuration?

🚀 Elevate Your Java Journey!

Master Spring Boot and modern backend development with Ram N Java. Subscribe today for more expert guides!

SUBSCRIBE TO RAM N JAVA

Mastering Email in Spring with Annotation Configuration

Communicating with users via email is a core requirement for almost any modern application. While there are many ways to handle this, using Spring Java Mail with Annotation-based configuration provides a clean, maintainable, and modern approach for Java developers.

The Power of Java-Based Configuration

Gone are the days of complex XML files for bean management. By using the @Configuration and @Bean annotations, you can define your JavaMailSender directly in Java code. This approach offers better type safety, easier debugging, and aligns perfectly with modern Spring Boot standards.

Core Components: JavaMailSender

The heart of the operation is the JavaMailSender interface. When you configure this bean, you specify your SMTP server details—such as the host (e.g., smtp.gmail.com), port, username, and password. This central configuration allows your entire application to send emails seamlessly by simply injecting the sender bean wherever it's needed.

SimpleMailMessage vs. MimeMessage

For basic text alerts, SimpleMailMessage is incredibly easy to use. However, if you need to send HTML content or add attachments, you'll step up to the MimeMessage. Spring's utilities make it simple to switch between these depending on your project's specific needs.

Implementation Steps

Setting this up involves three main steps: adding the spring-context-support dependency, creating your configuration class to define the mail sender properties, and then using that sender in your service layer to dispatch messages. It’s a robust workflow that works perfectly for both small projects and enterprise applications.

Quick Tip: If you're using Gmail to test, remember to use an "App Password" rather than your main account password to keep your credentials secure!


Top Spring Boot Tutorials for You

How to Send an email in Spring by Server provided by host provider?

🚀 Level Up Your Tech Skills!

Master Java, Spring, and Networking with Ram N Java. Subscribe now for easy-to-follow tutorials!

SUBSCRIBE TO RAM N JAVA

Sending Emails in Spring Using Your Host's Server

While testing emails with Gmail or Outlook is great for development, moving to production often requires using the SMTP server provided by your actual hosting provider. In this guide, we'll look at how to configure Spring Java Mail to work seamlessly with your host's specific email infrastructure.

Why Use Your Host's SMTP Server?

Hosting providers often offer dedicated SMTP services that are optimized for their own networks. Using these can lead to better deliverability and fewer issues with spam filters compared to using a third-party personal account for high-volume application emails. It also keeps your branding consistent by sending emails from your own domain (e.g., info@yourdomain.com).

Step 1: Gather Your Server Details

Before you start coding, you'll need three key pieces of information from your hosting dashboard: the SMTP Host (like mail.yourdomain.com), the Port (usually 465 for SSL or 587 for TLS), and your Email Credentials. Most hosts provide these in their "Email Accounts" or "Help" sections.

Step 2: Configuration in Spring

In your Spring configuration, you'll set these properties on the JavaMailSenderImpl object. It's important to enable authentication and set the correct protocol (like smtps for SSL). This ensures that your application can talk to the server securely and that your emails are accepted for delivery.

Step 3: Troubleshooting Deliverability

If your emails aren't going through, double-check your security settings. Some hosts require specific Java properties to be set for SSL handshakes to work correctly. Always look at your application logs to see exactly where the connection might be failing—Spring Java Mail provides excellent debug info if you enable the mail.debug property.

Pro Tip: Many hosting providers block external SMTP traffic on port 25. Always try port 587 (TLS) or 465 (SSL) first for a reliable connection!


Master Networking Basics

Understanding how servers communicate starts with the basics. Check out these essential guides on IP addresses and ports:

How to Send an Email with an attachment?

🚀 Elevate Your Coding Skills!

Want to master Spring and Java development? Subscribe to Ram N Java for simplified tutorials and expert tips!

SUBSCRIBE TO OUR CHANNEL

Sending Email Attachments in Spring: A Complete Guide

In many enterprise applications, simply sending a text email isn't enough. You often need to send reports, invoices, or images as attachments. In this tutorial, we dive into the world of Spring Java Mail to see how easily you can handle file attachments in your Java applications.

Understanding the Basics

To send an email with an attachment in Spring, we move beyond the basic SimpleMailMessage. Instead, we use the MimeMessage class. This allows us to create "multipart" messages that can contain both text and binary data (like your files).

The Role of MimeMessageHelper

Spring provides a fantastic utility called MimeMessageHelper. This helper makes the complex task of building a multipart message much simpler. When you initialize it, you just need to set the multipart flag to true, and you're ready to start adding files!

Step-by-Step Implementation

The process is straightforward:

  • Create a MimeMessage using your JavaMailSender.
  • Wrap it in a MimeMessageHelper.
  • Set your recipient, subject, and body text.
  • Use the addAttachment() method to attach your file (using a FileSystemResource or InputStreamSource).
  • Call the send() method.

Pro Tip: Always ensure that the files you are attaching exist and are accessible by your application to avoid runtime exceptions!


Master Database Basics: What is CRUD?

After you've sent your email reports, you might need to manage the data behind them. Learn the fundamentals of database operations with these guides:

How to Send an Email based on the Email template?

🚀 Boost Your Developer Skills!

Master Spring, Java, and modern web tech with Ram N Java. Subscribe today for more professional tutorials!

SUBSCRIBE TO OUR CHANNEL

Sending Professional Emails Using Templates in Spring

Consistency is key when building a brand. Instead of hard-coding your email content into your Java classes, using Email Templates allows you to manage your layouts separately and update them without touching your code. In this tutorial, we explore how to integrate templates with Spring Java Mail.

The Benefit of Templates

By using templates (like those from FreeMarker or Thymeleaf), you can design beautiful HTML emails with CSS and placeholders. This separation of concerns means your Java code stays clean, focusing only on the logic of sending, while your template handles the presentation and branding.

Dynamic Data Injection

The real magic happens when you inject dynamic data into your templates. Whether it's a customer's name, a unique order number, or a personalized greeting, Spring allows you to pass a map of objects that the template engine uses to fill in the blanks before the email is sent.

How It Works in Spring

Typically, you'll use a template engine configuration bean alongside your JavaMailSender. Your service layer will load the template, merge it with the data model, and then set the resulting string as the content of a MimeMessage. This workflow is robust and scales perfectly for enterprise-level applications.

Pro Tip: Store your templates in a dedicated resources folder to keep your project organized and make them easy to locate for future design updates!


Optimize Your Web Performance with CDN

Once your emails are looking great, make sure your website is just as fast! Learn all about Content Delivery Networks (CDNs) with these guides:

How to Send an Email via Gmail SMTP server using MimeMessagePreparator?

🚀 Master Modern Java Development!

Level up your backend skills with Ram N Java. Subscribe now for deep dives into Spring and System Design!

SUBSCRIBE TO RAM N JAVA

Mastering Email with MimeMessagePreparator

When working with Spring Java Mail, there are several ways to construct and send messages. While many use the helper classes, the MimeMessagePreparator interface offers a more "functional" and callback-oriented approach to message creation. In this guide, we'll see how to use it with the Gmail SMTP server.

What is MimeMessagePreparator?

The MimeMessagePreparator is a callback interface for the JavaMailSender. Instead of creating a message manually and passing it to the sender, you provide an implementation of this interface. Spring then handles the creation of the MimeMessage and passes it into your prepare() method.

The Benefits of This Approach

Using a preparator allows for better error handling and cleaner code structure. It ensures that the message creation logic is encapsulated. It also simplifies the process when you're dealing with complex exceptions that can occur during the setup of a MIME message.

Configuring the Gmail SMTP Server

To send emails through Gmail, you must configure your JavaMailSenderImpl with the correct properties. This includes the host (smtp.gmail.com), the port (587), and enabling STARTTLS. Remember, for security, always use an App Password rather than your standard account password.

Step-by-Step Implementation

In your code, you'll call mailSender.send(new MimeMessagePreparator() { ... }). Inside the prepare method, you can use the MimeMessageHelper to set the sender, recipient, subject, and the body of the email. This pattern is particularly powerful when sending automated notifications from your Spring Boot applications.

Pro Tip: When using MimeMessagePreparator, you can take advantage of lambda expressions in modern Java to make your code even more concise!


Learn from the Giants: Netflix System Design

Want to see how the world's biggest platforms handle their backend? Check out these deep dives into Netflix architecture:

Spring Java Mail - How to Send an Email via Gmail SMTP server to multiple receivers?

🚀 Master Modern Development!

Stay updated with the latest in Spring, Java, and digital productivity. Subscribe to Ram N Java today!

SUBSCRIBE TO OUR CHANNEL

Spring Java Mail: Sending to Multiple Recipients

Automating notifications often means reaching more than just one person. Whether it's a team alert or a newsletter blast, knowing how to send an email to multiple recipients efficiently is a vital skill. In this guide, we'll walk through how to achieve this using Spring Java Mail and the Gmail SMTP server.

Understanding CC and BCC

When sending to multiple people, you have options. You can use the primary To field, CC (Carbon Copy), or BCC (Blind Carbon Copy). Spring's mail utilities make it incredibly simple to set these fields by passing an array of email addresses instead of just a single string.

Configuring for Gmail

To use Gmail as your service provider, ensure your JavaMailSenderImpl is correctly configured with smtp.gmail.com and port 587. Crucially, you must use an App Password if you have 2-Step Verification enabled on your Google account to allow your Spring application to connect securely.

The Implementation Logic

The code involves creating a SimpleMailMessage or a MimeMessage. By using the setTo(), setCc(), or setBcc() methods and providing a String[] of addresses, Spring handles the formatting required by the SMTP server to ensure every recipient gets their copy of the message.

Pro Tip: When sending to a large list of recipients, consider using BCC to protect user privacy so recipients can't see each other's email addresses!


Optimize Your Communication with WhatsApp

Beyond email, WhatsApp is an essential tool for staying connected. Check out these helpful guides for your PC:

How to Send an Email via Gmail SMTP server with MailSender?

🚀 Boost Your Cloud & Java Expertise!

Stay ahead in the tech world with Ram N Java. Subscribe today for the best tutorials on Spring Boot, AWS, and more!

SUBSCRIBE TO RAM N JAVA

Sending Emails in Spring with Gmail SMTP

In this guide, we'll walk through the essentials of using the MailSender interface in Spring to send emails through the Gmail SMTP server. This is a fundamental skill for any Java developer looking to add notification features to their applications.

Understanding the MailSender Interface

The MailSender is the top-level interface in Spring's mail abstraction. It provides basic functionality for sending simple emails. For more advanced features like HTML content or attachments, you'll often use its sub-interface, JavaMailSender, but understanding the core MailSender is where every developer should start.

Setting Up Gmail for SMTP

To use Gmail as your provider, you need to configure specific server properties. This includes the host (smtp.gmail.com), the port (587 for TLS), and enabling authentication. Crucially, if you have 2-Step Verification enabled, you must generate and use an App Password to allow your Spring app to connect securely.

Core Implementation Steps

The workflow is simple:

  • Add the spring-boot-starter-mail dependency to your project.
  • Configure your Gmail credentials in the application properties.
  • Inject the MailSender bean into your service.
  • Create a SimpleMailMessage, set the recipient and content, and call send().

Pro Tip: Always handle the MailException to ensure your application can gracefully deal with network issues or incorrect credentials!


Master the Cloud with AWS

Ready to move your local apps to the cloud? Check out these essential AWS tutorials from my channel:

Friday, 29 March 2019

Spring 4 + Hibernate 4 + MySQL 8 + Maven Integration example using XML Configuration

🚀 Level Up Your Java Skills!

Subscribe to Ram N Java for easy-to-understand tutorials on Spring, Hibernate, and more!

CLICK HERE TO SUBSCRIBE

Mastering Spring 4 and Hibernate 4 Integration

Integrating powerful frameworks like Spring and Hibernate is a core skill for any Java developer. In this guide, we walk through a complete example of how to connect these frameworks using MySQL 8 and Maven with a classic XML-based configuration.

1. Why XML Configuration?

While annotations are popular, understanding XML configuration is essential for maintaining legacy systems and understanding how the "magic" happens behind the scenes. It provides a clear, centralized place to manage your beans and database settings.

2. The Role of Maven

Maven acts as your project manager. Instead of manually searching for JAR files, we define our dependencies in the pom.xml. This ensures that Spring, Hibernate, and the MySQL connector all work together seamlessly.

3. Setting Up MySQL 8

MySQL 8 introduced new security and performance features. We'll show you the exact properties you need in your configuration to ensure a stable connection between your Java application and the database.

Key Takeaways for Beginners:

  • How to structure a Maven project.
  • Defining DataSources and SessionFactories in XML.
  • Performing basic CRUD operations.

Spring 4 + Hibernate 4 + MySQL 8 + Maven Integration example using Annotations Configuration

🚀 Master Java Development with Us!

Enjoyed this tutorial? Don't miss out on more deep dives into Spring and Hibernate.

SUBSCRIBE TO RAM N JAVA

Spring 4 and Hibernate 4 Integration Guide

Welcome! In this tutorial, we explore how to integrate Spring 4 with Hibernate 4 using MySQL 8 and Maven. This guide is perfect for beginners who want to understand how these technologies work together using modern annotation-based configurations.

1. Setting Up Your Database

First, we start with a simple Employee table. This table includes essential columns such as:

  • ID: Unique identifier
  • Name: Employee name
  • Joining Date: When the employee started
  • Salary: Compensation details
  • SSN: Social Security Number for identification

2. Project Structure & Dependencies

Using Maven, we manage all necessary dependencies in the pom.xml file. A critical tip: Always ensure your MySQL Connector version is compatible with the MySQL server installed on your machine to avoid connection issues.

3. Configuration Classes

We move away from bulky XML files and use Java Annotations. We create a HibernateConfiguration class where we define:

  • DataSource: Contains the URL, username, and password for your database.
  • SessionFactory: Manages Hibernate sessions.
  • TransactionManager: Handles database transactions smoothly.

4. Performing CRUD Operations

In the tutorial, we demonstrate how to perform the core database actions (CRUD):

  • Create: Saving a new employee record.
  • Read: Fetching all employees or searching by SSN.
  • Update: Modifying existing data (like changing a salary).
  • Delete: Removing records from the table.

Watch and Learn More

Check out these other helpful videos from Ram N Java to keep growing your skills:

Sunday, 24 March 2019

Spring 3 + hibernate 3 + Maven integration example

🔥 Level Up Your Coding Skills!

Join thousands of developers on Ram N Java. Get the latest tutorials delivered to you!

SUBSCRIBE TO RAM N JAVA

Mastering Spring 3 and Hibernate 3 Integration

Are you looking to build robust Java applications? Integrating Spring 3 with Hibernate 3 is a classic yet powerful approach. In this comprehensive guide, we walk through a complete integration example using Maven to manage your dependencies.

Why Use Spring with Hibernate?

Spring provides excellent support for Hibernate by handling the boilerplate code. It manages the session factory, transaction management, and simplifies data access through the DAO pattern.

Key Components of the Project

In the video, we cover several critical areas for a successful setup:

  • Maven Project Structure: How to organize your folders and source files.
  • The pom.xml File: Adding dependencies for Spring Core, Spring ORM, Hibernate, and the MySQL Connector.
  • Application Context: Configuring the DataSource, SessionFactory, and Transaction Manager in XML.
  • Entity Mapping: Mapping your Java classes to database tables using Hibernate XML mappings.

Step-by-Step Implementation

We start by creating a simple Employee model. From there, we build the DAO (Data Access Object) layer to handle database interaction. You will see how the HibernateTemplate or SessionFactory makes database queries clean and efficient.

Check Out These Other Videos

Enjoyed this tutorial? You might also find these videos from my channel helpful:

Tuesday, 5 March 2019

Spring + JdbcTemplate + How to retrieve auto-generated keys

🚀 Enjoyed the tutorial? Support "Ram N Java" by Subscribing to our YouTube Channel for more Java deep dives!

How to Retrieve Auto-Generated Keys using Spring JdbcTemplate

When working with relational databases, it is very common to have primary keys that are automatically generated (like AUTO_INCREMENT in MySQL or SERIAL in PostgreSQL). After performing an insert operation, you often need that specific ID to use it in subsequent logic.

The Challenge

Normally, a standard update or insert query returns only the number of rows affected. To get the actual key that the database just created, we need a more specialized approach within the Spring framework.

The Solution: GeneratedKeyHolder

Spring JDBC provides a handy interface called KeyHolder and its primary implementation, GeneratedKeyHolder. This object acts as a container for the keys returned by the database.

Step-by-Step Implementation

  1. Create a KeyHolder: Instantiate a new GeneratedKeyHolder().
  2. Use PreparedStatementCreator: Instead of a simple SQL string, you provide a callback that defines how the statement is created and specifies which columns are auto-generated.
  3. Execute the Update: Pass both the PreparedStatementCreator and the KeyHolder to the jdbcTemplate.update() method.
  4. Extract the Key: Access the ID using keyHolder.getKey().

Why is this useful?

This method is cleaner and more reliable than trying to query for the "last inserted ID" manually, which can cause issues in high-traffic environments where multiple users are inserting data at the same time.


Continue Learning

Check out these other Spring JDBC tutorials from the channel:


Click here to watch on Youtube:
https://www.youtube.com/watch?v=rbi3TkO0q5U&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge:

Spring + JdbcTemplate + How to retrieve auto-generated keys

Employee.sql

CREATE DATABASE org_db;


CREATE TABLE `employee` (
  `EMPLOYEE_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(100) NOT NULL,
  `AGE` INT(10) NOT NULL,
  `SALARY` INT(10) DEFAULT NULL,
  PRIMARY KEY (`EMPLOYEE_ID`)
) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ram.core</groupId>
    <artifactId>SpringDemo</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringDemo</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>5.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring 5 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

    </dependencies>

</project>

EmployeeDAO.java

package com.ram.employee.dao;

public interface EmployeeDAO
{
    public void retriveAutoGeneratedKey();
}

EmployeeDAOImpl.java

package com.ram.employee.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.ram.employee.dao.EmployeeDAO;

public class EmployeeDAOImpl
        extends JdbcDaoSupport implements EmployeeDAO
{

    public void retriveAutoGeneratedKey()
    {
        final String INSERT_SQL = "INSERT INTO EMPLOYEE "
                + "(NAME, AGE,SALARY) VALUES (?, ?, ?)";

        KeyHolder keyHolder = new GeneratedKeyHolder();
        getJdbcTemplate().update(new PreparedStatementCreator()
        {
            public PreparedStatement createPreparedStatement(
                    Connection connection) throws SQLException
            {
                PreparedStatement ps = connection.prepareStatement(
                        INSERT_SQL, new String[] { "id" });
                ps.setString(1, "Rob");
                ps.setInt(2, 12);
                ps.setInt(3, 9090);
                return ps;
            }
        }, keyHolder);

        System.out.println(
                "Auto generated Key is = " + keyHolder.getKey());
    }

}

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">


    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/org_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="employeeDAO" class="com.ram.employee.dao.impl.EmployeeDAOImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>
 
</beans>

App.java

package com.ram.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ram.employee.dao.EmployeeDAO;

public class App
{
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        EmployeeDAO employeeDAO = (EmployeeDAO) context
                .getBean("employeeDAO");
        employeeDAO.retriveAutoGeneratedKey();
    }
}

Output:

Feb 20, 2019 10:36:51 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@736e9adb: startup date [Wed Feb 20 10:36:51 IST 2019]; root of context hierarchy
Feb 20, 2019 10:36:52 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Feb 20, 2019 10:36:52 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Wed Feb 20 10:36:53 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Auto generated Key is = 10

Click the below link to download the code:
https://sites.google.com/site/javaspringram2019/java_spring_2019/SpringDemo_Retrive_auto_key.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java_Spring_2019/tree/master/Spring_2019/SpringDemo_Retrive_auto_key

Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/8f8b5563b7f2921ed260908e4906103995d9c6cc/Spring_2019/SpringDemo_Retrive_auto_key/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • Tutorials