Showing posts with label XML Configuration. Show all posts
Showing posts with label XML Configuration. Show all posts

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.

Sunday, 20 January 2019

JAXB marshalling and unmarshalling | JAXB tutorial | Spring and JAXB XML binding framework - Playlist

XML Marshalling and UnMarshalling using Spring and JAXB XML binding framework - XML Config

Want to Level Up Your Java & Spring Skills?

Subscribe to Ram N Java for clean, step-by-step programming guides and hands-on developer tutorials!

🔔 Subscribe Now

What is Object-XML Mapping (OXM) in Spring?

Spring's Object/XML Mapping (OXM) framework provides an abstraction layer over standard XML binding libraries like JAXB, Castor, and XStream. It allows developers to seamlessly convert between Java objects and XML structures:

  • Marshalling: Serializing a Java entity into structured XML data.
  • Unmarshalling: Deserializing XML data back into a usable Java object.

Configuring JAXB via Spring XML Configuration

Using an XML configuration file allows you to configure your Spring beans declaratively. By defining Jaxb2Marshaller inside your application context XML, you separate mapping configuration from Java source code, making it straightforward to manage across different environments.

Key Steps Demonstrated in This Guide

  1. Bean Definitions: Declaring the Jaxb2Marshaller bean inside applicationContext.xml.
  2. Class Binding: Setting up domain model classes with required JAXB mappings.
  3. Marshalling Process: Passing a Java object to the marshaller to generate XML output.
  4. Unmarshalling Process: Reading the generated XML and reconstructing the original Java object.

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

Click the below Image to Enlarge:

XML Marshalling and UnMarshalling using Spring and JAXB XML binding framework - XML Config


XML Marshalling and UnMarshalling using Spring and JAXB XML binding framework - XML Config


XML Marshalling and UnMarshalling using Spring and JAXB XML binding framework - XML Config

XML Marshalling and UnMarshalling using Spring and JAXB XML binding framework - XML Config

XML Marshalling and UnMarshalling using Spring and JAXB XML binding framework - XML Config
XML Marshalling and UnMarshalling using Spring and JAXB XML binding framework - XML Config
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.1.1.RELEASE</spring.version>
    </properties>

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

        <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-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
</project>

Company.java

package com.ram.core.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "CompanyInfo", namespace = "com.ram.core")
@XmlAccessorType(XmlAccessType.NONE)
public class Company
{
    @XmlAttribute(name = "Id")
    private Integer id;

    @XmlElement(name = "CompanyName")
    private String companyName;

    @XmlElement(name = "CEO_Name")
    private String ceoName;

    @XmlElement(name = "Number_Of_Employees")
    private Integer numberOfEmployees;

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public String getCompanyName()
    {
        return companyName;
    }

    public void setCompanyName(String companyName)
    {
        this.companyName = companyName;
    }

    public String getCeoName()
    {
        return ceoName;
    }

    public void setCeoName(String ceoName)
    {
        this.ceoName = ceoName;
    }

    public Integer getNumberOfEmployees()
    {
        return numberOfEmployees;
    }

    public void setNumberOfEmployees(Integer numberOfEmployees)
    {
        this.numberOfEmployees = numberOfEmployees;
    }

    @Override
    public String toString()
    {
        return "Company [id=" + id + ", companyName=" + companyName
                + ", ceoName=" + ceoName + ", numberOfEmployees="
                + numberOfEmployees + "]";
    }

}

XMLConverter.java

package com.ram.core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

public class XMLConverter
{
    private Marshaller marshaller; 
    private Unmarshaller unmarshaller;

    public Marshaller getMarshaller()
    {
        return marshaller;
    }

    public void setMarshaller(Marshaller marshaller)
    {
        this.marshaller = marshaller;
    }

    public Unmarshaller getUnmarshaller()
    {
        return unmarshaller;
    }

    public void setUnmarshaller(Unmarshaller unmarshaller)
    {
        this.unmarshaller = unmarshaller;
    }

    public void convertFromObjectToXML(Object object, String filepath)
            throws IOException
    {

        FileOutputStream os = null;
        try
        {
            os = new FileOutputStream(filepath);
            getMarshaller().marshal(object, new StreamResult(os));
        }
        finally
        {
            if (os != null)
            {
                os.close();
            }
        }
    }

    public Object convertFromXMLToObject(String xmlfile)
            throws IOException
    {
        FileInputStream is = null;
        try
        {
            is = new FileInputStream(xmlfile);
            return getUnmarshaller().unmarshal(new StreamSource(is));
        }
        finally
        {
            if (is != null)
            {
                is.close();
            }
        }
    }

}

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="XMLConverter" class="com.ram.core.XMLConverter">
        <property name="marshaller" ref="jaxbMarshaller" />
        <property name="unmarshaller" ref="jaxbMarshaller" />
    </bean>
    <bean id="jaxbMarshaller"
        class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="packagesToScan" value="com.ram.core.model" />

        <property name="marshallerProperties">
            <map>
                <entry key="jaxb.formatted.output">
                    <value type="boolean">true</value>
                </entry>
            </map>
        </property>

    </bean>

</beans>

App.java

package com.ram.core;

import java.io.IOException;

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

import com.ram.core.model.Company;

public class App
{
    private static final String XML_FILE_NAME = "company.xml";

    public static void main(String[] args) throws IOException
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        XMLConverter converter = (XMLConverter) context
                .getBean(XMLConverter.class);

        // Perform Marshaling
        Company company = new Company();
        company.setId(201);
        company.setCompanyName("Google");
        company.setCeoName("Peter");
        company.setNumberOfEmployees(50000);

        // from object to XML file
        converter.convertFromObjectToXML(company, XML_FILE_NAME);
        System.out.println("Converted Object to XML!");

        // from XML to object
        Company company2 = (Company) converter
                .convertFromXMLToObject(XML_FILE_NAME);
        System.out.println(company2);
        System.out.println("Converted XML to Object!");
       
    }
}

Output:

Converted Object to XML!
Company [id=201, companyName=Google, ceoName=Peter, numberOfEmployees=50000]
Converted XML to Object!

company.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:CompanyInfo xmlns:ns2="com.ram.core" Id="201">
    <CompanyName>Google</CompanyName>
    <CEO_Name>Peter</CEO_Name>
    <Number_Of_Employees>50000</Number_Of_Employees>
</ns2:CompanyInfo>

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/f045a9157b562b3c9ebf2a959f4b1cf324cce850/Spring_2019/SpringDemo_JAXB_XML_Config/?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
  • Saturday, 8 December 2018

    Spring AOP AspectJ Around Advice example using XML configuration | Spring Tutorial

    🚀 Master Spring Framework!

    Join the Ram N Java community for practical, step-by-step tutorials that make complex coding concepts simple.

    SUBSCRIBE TO RAM N JAVA

    Mastering Spring AOP: Around Advice with XML

    Aspect-Oriented Programming (AOP) allows developers to handle "cross-cutting concerns" like logging and security separately from main business logic. Among all advice types, Around Advice is the most powerful and flexible.

    What is Around Advice?

    Around Advice surrounds a method execution. It gives you full control, allowing you to perform actions both before and after the method runs. You can even decide whether the method should execute at all or provide your own custom return value.

    Why Use XML Configuration?

    While annotations are popular, XML configuration keeps your Java classes clean and completely decoupled from AOP logic. This is especially useful in legacy systems or when you want a centralized place to manage all your application's aspects without touching the source code.

    Practical Use Cases

    Around Advice is perfect for performance monitoring. You can start a timer, let the method run, stop the timer, and log the total execution time—all in one place! It’s also ideal for caching and complex security checks.

    Key Takeaway: Around Advice provides the ultimate level of control over method execution, making your Spring applications more modular and powerful.


    Check Out More From Ram N Java

    Keep your momentum going with these top-rated tutorials from my channel:


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

    Click the below Image to Enlarge:
    Spring AOP AspectJ Around Advice example using XML configuration | Spring Tutorial

    Spring AOP AspectJ Around Advice example using XML configuration | Spring Tutorial

    Spring AOP AspectJ Around Advice example using XML configuration | Spring Tutorial


    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>

            <!-- Spring AOP + AspectJ -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
           
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjrt</artifactId>
                <version>1.9.1</version>
            </dependency>
           
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.1</version>
            </dependency>

        </dependencies>

    </project>

    EmployeeService.java

    package com.ram.service;

    public class EmployeeService
    {
        public String addEmployee(String name)
        {
            System.out
                    .println("addEmployee(String name) method is called");
            return "Employee Peter information is added successfully";
        }

        public void modifyEmployee()
        {
            System.out.println("modifyEmployee() is called");
        }

        public void deleteEmployee()
        {
            System.out.println("deleteEmployee() is called");
        }

    }

    LoggingAspect.java

    package com.ram.Aspect;

    import java.util.Arrays;

    import org.aspectj.lang.ProceedingJoinPoint;

    public class LoggingAspect
    {
        public void logAround(ProceedingJoinPoint proceedingJoinPoint)
                throws Throwable
        {

            System.out.println("logAround() is running!");
            System.out.println("hijacked method = "
                    + proceedingJoinPoint.getSignature().getName());
            System.out.println("hijacked arguments = "
                    + Arrays.toString(proceedingJoinPoint.getArgs()));

            System.out.println("Around before is running!");
            proceedingJoinPoint.proceed(); // continue on the intercepted
                                            // method
            System.out.println("Around after is running!");

            System.out.println("******");
        }

    }

    applicationContext.xml

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


        <bean id="employeeService" class="com.ram.service.EmployeeService"></bean>

        <!-- Aspect -->
        <bean id="logAspect" class="com.ram.Aspect.LoggingAspect" />

        <aop:config>
            <aop:aspect id="aspectLoggging" ref="logAspect">
                <!-- @Around -->
                <aop:pointcut id="pointCutAround"
                    expression="execution(* com.ram.service.EmployeeService.addEmployee(..)))" />

                <aop:around method="logAround" pointcut-ref="pointCutAround" />
            </aop:aspect>

        </aop:config>

    </beans>

    App.java

    package com.ram.core;

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

    import com.ram.service.EmployeeService;

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

            System.out.println("---------------------------------------");

            EmployeeService employeeService = context
                    .getBean("employeeService", EmployeeService.class);

            employeeService.addEmployee("Peter");

            employeeService.modifyEmployee();

            employeeService.deleteEmployee();

        }

    }

    Output

    Nov 15, 2018 10:41:50 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@32709393: startup date [Thu Nov 15 10:41:50 IST 2018]; root of context hierarchy
    Nov 15, 2018 10:41:50 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
    ---------------------------------------
    logAround() is running!
    hijacked method = addEmployee
    hijacked arguments = [Peter]
    Around before is running!
    addEmployee(String name) method is called
    Around after is running!
    ******
    modifyEmployee() is called
    deleteEmployee() is called

    Click the below link to download the code:
    https://sites.google.com/site/ramj2eev2/java_basics/SpringDemo_aspectj_around_advise_XML_Config.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/javaee/tree/master/Spring_2018/SpringDemo_aspectj_around_advise_XML_Config

    Bitbucket Link:
    https://bitbucket.org/ramram43210/spring/src/0989e369f77ed192b0b224588ebfcdeb2019a6a2/Spring_2018/SpringDemo_aspectj_around_advise_XML_Config/?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