Showing posts with label Annotation. Show all posts
Showing posts with label Annotation. Show all posts

Tuesday, 8 January 2013

Spring Selenium Tests With Annotations

This post describes how to implement Selenium tests in Java. It is inspired from the post by Alex Collins, with annotations. The code is available on GitHub in the Spring-Selenium-Test directory. Some alternative and much lighter techniques are available to unit test a Spring MVC application. To unit test services, see here.

Page, Configuration & Controller

We create a simple page with 'Hello World':
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Welcome !!!</title>
</head>
<body>
  <h1>
   Hello World !
  </h1>
</body>
</html>
We keep our controller very simple:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

}
and our controller too:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

}

For Selenium Testing

We create a configuration for testing. It provides the URL to open the application locally. The application is opened with Firefox:
@Configuration
public class TestConfig {

    @Bean
    public URI getSiteBase() throws URISyntaxException {
        return new URI("http://localhost:10001/spring-selenium-test-1.0.0");
    }

    @Bean(destroyMethod="quit")
    public FirefoxDriver getDrv() {
        return new FirefoxDriver();
    }

}
We also define an abstract class as a basis for all tests. It automatically closes Firefox after the test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ TestConfig.class })
public abstract class AbstractTestIT {

    @Autowired
    protected URI siteBase;

    @Autowired
    protected WebDriver drv;

    {
        Runtime.getRuntime().addShutdownHook(new Thread() {
           @Override
           public void run() {
                drv.close();
           }
        });
    }

}
And we implement a selenium test where we make sure our page contains 'Hello World':
public class SeleniumTestIT extends AbstractTestIT {

    @Test
    public void testWeSeeHelloWorld() {
        drv.get(siteBase.toString());
        assertTrue(drv.getPageSource().contains("Hello World"));
    }

}
The maven dependencies are the same as those described in Alex Collins's post.

Building The Application

If you build the application, it will open and close firefox automatically. The test will be successful.

Sunday, 18 November 2012

Spring Internationalization Example (with Annotations)

Spring InternationalizationThis post describes how to implement message internationalization in Spring. The code example is available from GitHub in the Spring-MVC-Internationalization directory. It is based on the Spring MVC with annotations example.

Internationalization

We define two resource bundles (setA and setB) containing string translations for German, French and English. These are created in the src/main/resources maven directory.

Configuration

We need to create:
  • a ResourceBundleMessageSource bean to load the string translations
  • a LocaleChangeInterceptor bean which will intercept requests and extract a parameter value (if available) to detect language changes
  • a SessionLocaleResolver bean to store the user's locale preference in the session
  • to register the LocaleChangeInterceptor in the interceptor registry
 We extend our web configuration:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    ...

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource result
            = new ResourceBundleMessageSource();

        String[] basenames = {
            "i18n.setA.setA",
            "i18n.setB.setB"
        };

        result.setBasenames(basenames);

        return result;

    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor result = new LocaleChangeInterceptor();
        result.setParamName("lang");

        return result;

    }

    @Bean
    public LocaleResolver localeResolver() {

        SessionLocaleResolver result = new SessionLocaleResolver();
        result.setDefaultLocale(Locale.ENGLISH);

        return result;

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

}

Controller

We simply our controller a lot:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

}

JSP Page

We only keep the index.jsp page, where we add links to change the language of displayed messages:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<!doctype html>
<html lang="en">
<head>
  <title>Welcome To Spring MVC Internationalization !!!</title>
</head>
<body>
  <h1>Spring MVC Internationalization !!!</h1>
  <p>Choose:
      <a href="<c:url value='?lang=en'/>">English</a>
      | <a href="<c:url value='?lang=fr'/>">French</a>
      | <a href="<c:url value='?lang=de'/>">German</a>
  </p>

  <p>Greetings: <spring:message code="greetings" text="missing" /></p>
  <p>Text 2: <spring:message code="text2" text="missing" /></p>
  <p>Current: <c:out value="${pageContext.response.locale}" /></p>
</body>
</html>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8383/spring-mvc-internationalization/

The main page will be displayed:


If you click on German, the German text is displayed:


More Spring related posts here.

Spring Bean XML To Annotation Configuration

Here is an example of converting an XML based bean configuration to a annotation based configuration.

Assuming an XML files contain the following:
<bean id="localeChangeInterceptor"
    class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
</bean>
<bean id="handlerMapping"
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
   <property name="interceptors">
       <ref bean="localeChangeInterceptor" />
   </property>
</bean>
The second beans refers to the first one for initialization.

The corresponding Java with annotation configuration is:
@Configuration
public class MyConfig {

    // ...

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor result
            = new LocaleChangeInterceptor();

        result.setParamName("lang");

        return result;

    }

    @Bean
    public DefaultAnnotationHandlerMapping handlerMapping() {

        DefaultAnnotationHandlerMapping result
            = new DefaultAnnotationHandlerMapping();

        Object[] interceptors = {
            localeChangeInterceptor()
        };

        result.setInterceptors(interceptors);

        return result;

    }

}

More Spring related posts here.

Sunday, 11 November 2012

Introduction To Spring Data Commons Features

This post is a quick introduction to Spring Data Common's (SDC) features.

Features

This Spring module provides a set of interfaces to manipulate data in repositories:
  • Repository - This is a marker interface indicating which object are going to access the repository.
  • CrudRepository<T, ID extends Serializable> - This interface extends Repository and provides a set of CRUD (Create, Read, Update, Delete) methods to manipulate T objects having ID as a key.
  • PageAndSortingRepository<T, ID extends Serializable> - This interface extends CrudRepository and provides method to fetch T objects in a sorted way or using pages.
  • Pageable & PageRequest - The Pageable interface is implemented by PageRequest. Page requests are created to indicate which page and page sizes should be used to fetch objects from the PageAndSortingRepository interface.
  • Page<T> - This interface contains the fetched objects returned for a given page request.
The above repository interfaces can expose too many methods for some developers. For example, one may not be comfortable with the idea of exposing write methods. The solution is to create your own customized repository interface and annotate it with:

    @RepositoryDefinition(
        domainClass=MyClass.class,
        idClass=MyClassID.class)

Then, copy the the repository methods you want to expose in this customized interface and Spring will deal with them.

There are situations where developers want to implement their own repository interfaces by extending the repository interfaces available in SDC. However, these interfaces should not be instantiated in their applications. To prevent this, they can use the @NoRepositoryBean on these customized interfaces.

More Spring related posts here.

Monday, 29 October 2012

Returning a JSON in Spring (With Annotations)

This post provides the simplest example to return a JSON from a Spring controller. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-Returning-A-JSON directory.

For a full Spring MVC REST calls with Ajax example, see here.

Dependencies

On top of current dependencies, we add the Jackson mapper dependency:
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.10</version>
</dependency>
This dependency enables the conversion of Java objects into a JSON representation.

Data

For this example, we use a simple SomeData class:
public class SomeData {

    private String name;
    private long time;

    public SomeData(String name, long time) {
        this.name = name;
        this.time = time;
    }

    public SomeData() {
        name = "";
        time = System.currentTimeMillis();
    }

    // Setters & Getters

}

Controller

We modify our controller as following:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

    @RequestMapping(value="/getJSON/{name}", method = RequestMethod.GET)
    public @ResponseBody SomeData getJSON(@PathVariable String name) {

        SomeData result
            = new SomeData(name, System.currentTimeMillis());

        return result;

    }

}
The getJSON() method has special annotations usage:
  • @RequestMapping's value contains {name} which will be extracted by Spring an inserted as the parameter value in the method.
  • @ResponseBody's indicates that the body of the response to the user's request must be filled with what is returned by the method. Here, we return a SomeData object. Since we have added the Jackson dependency, Spring will automatically detect it and perform the conversion of this object into its JSON representation.
  • @PathVariable extracts the parameter's name from the URL's {name} and sets its as the parameter value in the getJSON() method.

JSP Index Page

Our index page remains very simple:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Welcome !!!</title>
</head>
<body>
    <h1>
    Welcome To Spring Returning A JSON !!!
    </h1>
    <a href="<c:url value='/getJSON/Arthur'/>">Get JSON for Arthur !!!</a>
</body>
</html>
It contains a link making a call to /getJSON/Arthur.

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8383/spring-returning-a-json/.

The home page will display:


Click on the link to retrieve the JSON:



More Spring related posts here.

Monday, 17 September 2012

Spring Security And Annotation Configuration Example

This post is the mix between the Spring MVC with Annotations Example and the Spring Security Configuration Introduction. The code example is available on Github in the Spring-Security-And-Annotation-Config directory.

We are going to add a mandatory login page before one can access the main page of the Spring MVC with Annotations example.

Configuration

First, we create a MyServlet-security.xml file:
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="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-3.0.xsd

    http://www.springframework.org/schema/security

    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  <http auto-config="true">
    <intercept-url pattern="/*" access="ROLE_USER"/>
  </http>

  <authentication-manager alias="authenticationManager">
    <authentication-provider>
      <user-service>
        <user authorities="ROLE_USER" name="guest" password="guest"/>
      </user-service>
    </authentication-provider>
  </authentication-manager>

</beans:beans>
We rely on the automatic configuration of Spring security, and we request that one must login with ROLE_USER privilege to access any to page of the website. We set an authentication manager and create a simple guest user login, with the guest password.

We add the security filters under contextConfigLocation:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  </context-param>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      com.jverstry.Configuration
    </param-value>
  </context-param>

  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>
      org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
  </filter>

  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value></param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file></welcome-file>
  </welcome-file-list>

</web-app>
At last we add one @ImportSource line in our WebConfig configuration class:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
@ImportResource("/WEB-INF/MyServlet-security.xml")
public class WebConfig extends WebMvcConfigurerAdapter {

  @Bean
  public ViewResolver getViewResolver() {

    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("WEB-INF/pages/");
    resolver.setSuffix(".jsp");

    return resolver;

  }

}

Running The Example

After compiling the project, one can run it using the maven tomcat:run goal. Then, browse:

  http://localhost:9191/spring-mvc-with-annotations/

Login with guest guest:


 ...and access the main page:


More Spring related posts here.

Saturday, 15 September 2012

Spring Security Configuration Introduction

This post describes the basic Spring security configuration steps all Spring applications must implement.

Setting Filters

Spring security relies on user request filters. These must be configured in the web.xml file under the contextConfigLocation elements:
<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Security Configuration

A <name>-security.xml file must be created in /WEB-INF with this initial structure:
<beans:beans
  xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="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-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    ...
</beans:beans>
<name> must be the name of the servlet as configured in web.xml.

Spring configuration can only be performed with XML documents. However, one can mix Java configuration and Spring XML configuration like this when using MVC:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "my.packages")
@ImportResource("WEB-INF/<name>-security.xml")
public class WebConfig extends WebMvcConfigurerAdapter {
    ...
}
The above imports the Spring security configuration.

REM: the tutorial available here recommends configuring the <name>-security.xml file in the contextConfigLocation section of web.xml. However, it does not work when using Java configuration. One must use @ImportResource as described above.

Maven Dependencies

The following maven dependencies are required for Spring security:
<properties>
    ...
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>
...
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>${spring.version}</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>${spring.version}</version>
</dependency>

For a concrete Spring Security example, click here • More Spring related posts here.

How To Mix Spring XML And Java Configuration?

The @Configuration Spring annotation allows one to perform Spring configuration from Java (such as bean declaration for example). It is possible to implement a Spring application without any XML configuration (see here). It is even possible to get rid of the web application web.xml file too.

However, some Spring modules, such as the security module, still require plain XML configuration. Some applications may refer to old legacy code which has not been converted to Java configuration too.

In this case, one needs to mix Spring XML and Java configuration. This can be achieved with the @ImportResource Spring annotation:
@Configuration
@ImportResource({"classpath:/WEB-INF/spring-security.xml",
"classpath:/WEB-INF/legacy-config.xml"})
public class Config {

    @Bean
    MyBean MyBean() {
        return new MyBean();
    }

}
The above imports two XML files and declares a bean using Java.

More Spring related posts here.

Wednesday, 29 August 2012

Spring MVC with Annotations Example

This post describes a simple Spring MVC application example with annotation configuration. This example is available from Github in the Spring-MVC-With-Annotations directory. Typically, a complete application's architecture includes several layers: MVC, Service, DAO, Persistence Layer.

Configuration

In our previous example, we still use a servlet-context.xml file. In this example, we get rid of it using the @EnableWebMvc annotation.

The web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.jverstry.Configuration</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file></welcome-file>
    </welcome-file-list>

</web-app>
We do not set a default welcome file. It is delegated to our controller.

The Java configuration class:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {

        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("WEB-INF/pages/");
        resolver.setSuffix(".jsp");

        return resolver;

    }

}
The @ComponentScan annotation tells Spring to scan the content of packages for Spring annotated classes.

JSP pages

We have two JSP pages in  the WEB-INF/pages/ directory.

index.jsp
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Welcome !!!</title>
</head>
<body>
  <h1>
    Welcome To Spring MVC With Annotations !!!
  </h1>
</body>
</html>
getTime.jsp 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Get Time !!!</title>
    </head>
    <body>
        The time in milliseconds is: <c:out value="${TimeIs}" /> !
    </body>
</html>

Controller & Service

Our controller:
@Controller
public class MyController {

    private MyService myService;

    @Autowired
    public void setMyService(MyService myService) {
        this.myService = myService;
    }

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

    @RequestMapping(value = "/getTime")
    public String helloWorld(Model model) {
        model.addAttribute("TimeIs", myService.getCurrentTimeInMilliseconds());
        return "getTime";
    }

}
The above, maps index.jsp to '/' user requests.

Our service and implementation:
public interface MyService {
    long getCurrentTimeInMilliseconds();
}

public class MyServiceImpl implements MyService {

    @Override
    public long getCurrentTimeInMilliseconds() {
        return System.currentTimeMillis();
    }

}

@Configuration
public class MyServicesConfiguration {

    private MyService myService = new MyServiceImpl();

    @Bean
    public MyService getMyService() {
        return myService;
    }

}

Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>2.2</version>
        </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

Running The Example

After compiling the project, one can run it using the maven tomcat:run goal. Then, browse:

  http://localhost:8383/spring-mvc-with-annotations/getTime

It will display something similar to:

  The time in milliseconds is: 1346261454171 !

For the same example with Spring Security, click here • More Spring related posts here.

Saturday, 25 August 2012

Spring IoC Container with Annotations (Standalone)

Spring's implementation of dependency injection and inversion of control is called the IoC container. Since version 3.0, it is possible to perform Java-based configuration instead of XML-based configuration using annotations.

Inversion of Control

Beans can be declared in classes annotated with @Configuration:
@Configuration
public class ConfigurationClass {

    private MyService myService = new MyService() {

        @Override
        public long getData() {
            return System.currentTimeMillis();
        }

    };

    @Bean
    public MyService getMyService() {
        return myService;
    }

}

public interface MyService {

    public long getData();

}
The above declares an implementation for the MyService interface.

Spring requires a special version of the application context to process annotations:
AnnotationConfigApplicationContext ctx =
    new AnnotationConfigApplicationContext();
ctx.scan("com.jverstry");
ctx.refresh();
After creating the application context, we scan all packages starting with com.jverstry for annotations. This detects the ConfigurationClass.

Dependency Injection

Other beans classes will want to use declared beans. For example:
@Component
public class MyServices {

    private MyService myService;

    @Autowired
    public void setMyService(MyService myService) {
        this.myService = myService;
    }

    public MyService getMyService() {
        return this.myService;
    }

}
Using @AutoWired tells springs to inject the implementation of MyService in MyServices. This is detected in the package scanning too.
MyServices mcs = ctx.getBean(MyServices.class);
System.out.println("Data: " + mcs.getMyService().getData());
The above retrieves an instance of MyServices and calls the injected MyService. The generated output is:
Data: 1345873585387

Dependencies

Spring annotation processing requires the cglib dependency:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>2.2.2</version>
</dependency>
The above example is available from Github in the Spring-IoC-Container.

More Spring related posts here.

Monday, 20 August 2012

JPA Lifecycle Annotations

This post illustrates how to use JPA's life cycle annotations. These can be used on method to perform actions before or after CRUD operations. The code example is available from Github in the JPA directory.

We define two classes, one with annotations WithLifeCycleAnnotations and one without annotations NoLifeCycleAnnotations. This example operates Hibernate JPA in a standalone in-memory mode.

With annotations:
@Entity
public class WithLifeCycleAnnotations {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long ID;

    private String name = "";

    @PostLoad
    public void postLoad() {
        System.out.println("Post Load called !!!");
    }

    @PostPersist
    public void postPersist() {
        System.out.println("Post Persist called !!!");
    }

    @PostRemove
    public void postRemove() {
        System.out.println("Post Remove called !!!");
    }

    @PostUpdate
    public void postUpdate() {
        System.out.println("Post Update called !!!");
    }

    @PrePersist
    public void prePersist() {
        System.out.println("Pre Persist called !!!");
    }

    @PreRemove
    public void preRemove() {
        System.out.println("Pre Remove called !!!");
    }

    @PreUpdate
    public void preUpdate() {
        System.out.println("Pre Update called !!!");
    }

    // Setters & Getters...

}
The following:
NoLifeCycleAnnotations nlca = new NoLifeCycleAnnotations();
nlca.setName("AAA");

System.out.println("Saving NO lifecycle annotations");
JPA.INSTANCE.save(nlca);

System.out.println("Reading NO lifecycle annotations");
NoLifeCycleAnnotations nlcaRetr =
    JPA.INSTANCE.get(NoLifeCycleAnnotations.class, nlca.getID());

System.out.println("Updating NO lifecycle annotations");
nlca.setName("BBB");
JPA.INSTANCE.update(nlca);

System.out.println("Deleting NO lifecycle annotations");
nlca.setName("BBB");
JPA.INSTANCE.delete(nlca);


WithLifeCycleAnnotations wlca = new WithLifeCycleAnnotations();
wlca.setName("AAA");

System.out.println("Saving WITH lifecycle annotations:");
JPA.INSTANCE.save(wlca);

System.out.println("Reading WITH lifecycle annotations:");
WithLifeCycleAnnotations wlcaRetr =
    JPA.INSTANCE.get(WithLifeCycleAnnotations.class, wlca.getID());

System.out.println("Updating WITH lifecycle annotations:");
wlca.setName("BBB");
JPA.INSTANCE.update(wlca);

System.out.println("Deleting WITH lifecycle annotations:");
wlca.setName("BBB");
JPA.INSTANCE.delete(wlca);
Generates the following output:
Saving NO lifecycle annotations
Reading NO lifecycle annotations
Updating NO lifecycle annotations
Deleting NO lifecycle annotations

Saving WITH lifecycle annotations:
Pre Persist called !!!
Post Persist called !!!
Reading WITH lifecycle annotations:
Updating WITH lifecycle annotations:
Pre Update called !!!
Post Update called !!!
Deleting WITH lifecycle annotations:
Pre Remove called !!!
Post Remove called !!
For some reason, @PostLoad is not invoked when using JPA/Hibernate in standalone mode.

Sunday, 12 August 2012

JPA Entity, Embeddable and Authorized Types

Introduction

JPA stands for Java Persistence API.  It is a mean by which developers can easily describe how to persist the data contained in Java objects using some annotations and a configuration file called persistence unit. This API is made available in the javax.persistence package. Typically, JPA is used in combination with an implementing framework (such as Hibernate for example).

This post is the first of a series introducing JPA with practical examples. It can be read like a reminder too. The code examples are are available from Github in the JPA directory. We will start with some basic annotations first.

@Entity

An entity creates a relationship between a Java class and (typically) a database table.
  • An entity class must have at least a public or protected constructor with no argument.
  • An entity class must have an @Id.
  • An entity class must not be final or have final variables.
  • The variables (or attributes) of an entity class to be persisted must be private, protected or package-private, and must be accessed via setter and getters from outside the class.
  • An entity class must implement Serializable in order to be transmittable in a detached status.

@Embeddable

An embeddable class is nearly an entity class, except that it cannot be persisted by itself alone. It can be used as a 'component' containing data to be persisted, in another entity.
Embeddable example:
@Embeddable
public class SomeEmbeddable implements Serializable {

    private String s;

    public SomeEmbeddable() { }

    public String getS() { return s; }
    public void setS(String s) { this.s = s; }

}

Authorized Types

The following entity example regroups the authorized types for persistence:
@Entity
public class AuthorizedTypes implements Serializable {

    @Id
    private long id;

    // Primitives

    private boolean bool;
    private Boolean bool2;
    private byte byt;
    private Byte byt2;
    private char c;
    private Character c2;
    private double dou;
    private Double dou2;
    private float floa;
    private Float floa2;
    private int i;
    private Integer i2;
    private long l;
    private Long l2;
    private short s;
    private Short s2;

    // Serializable types

    private String str;
    private BigInteger bi;
    private BigDecimal bd;
    private Serializable userDefined;
    private byte[] ba;
    private Byte[] ba2;
    private char[] ca;
    private Character[] ca2;

    public enum Color { WHITE, BLACK, RED; }
    private Color col;

    // Other entities and embeddables

    @OneToOne
    private OtherEntity otherEntity;

    private SomeEmbeddable someEmbeddable;

    @ElementCollection
    private Collection<SomeEmbeddable> coll;

    @ElementCollection
    private Set<SomeEmbeddable> st;

    @ElementCollection
    private List<SomeEmbeddable> list;

    @ElementCollection
    private Map<String, Serializable> mpp;

    // Time-related

    // Keeps date only
    @Temporal(TemporalType.DATE)
    private java.util.Date MyDate;

    // Keeps time only
    @Temporal(TemporalType.TIME)
    private java.util.Date MyTime;

    // Keeps date and time
    @Temporal(TemporalType.TIMESTAMP)
    private java.util.Date MyTimestamp;

    @Temporal(TemporalType.TIMESTAMP)
    private java.util.Calendar cal;

    // Keeps date only
    private java.sql.Date sqlDate;

    // Keeps time only
    private java.sql.Time sqlTime;

    // Keeps date and time
    private java.sql.Timestamp sqlTimeStamp;

    // Setters & Getters....

}
These are the basic persistence elements one can use and combine in entities. The above needs more configuration to be fully operational. It is only an illustration of concepts.

Thursday, 9 August 2012

JAXB Annotation - XmlAdapter, Map, Special Types Annotations

Code examples are available from Github in the JAXB-JSON-XML-Marshalling directory.

How to use XmlAdapter and @XmlJavaTypeAdapter to handle Map in JAXB?

In situations where JAXB cannot handle unknown types, the solution is to create an XmlAdapter and use the @XmlJavaTypeAdapter in the class referring to the unknown type to indicate JAXB how to deal with it. A Java map is a good example.

We are going to illustrate this with an example. Assuming an object containing a generic map:
@XmlRootElement
public class ObjectWithGenericMap<K, V> {

    private Map<K,V> map;

    @XmlElement
    @XmlJavaTypeAdapter(JaxbMapAdaptor.class)
    public Map<K,V> getMap() {
        return map;
    }

    public void setMap(Map<K,V> map) {
        this.map = map;
    }

}
We are going to need an adaptor:
public class JaxbMapAdaptor<K, V>
        extends XmlAdapter<JaxbMapToList<K, V>, Map<K, V>> {

    @Override
    public Map<K, V> unmarshal(JaxbMapToList<K, V> v)
            throws Exception {
        HashMap<K, V> result = new HashMap<K, V>();
        for (JaxbMapToListEntry<K, V> jme : v.getList()) {
            result.put(jme.getKey(), jme.getValue());
        }
        return result;
    }

    @Override
    public JaxbMapToList marshal(Map<K, V> v) throws Exception {
        JaxbMapToList<K, V> result = new JaxbMapToList<K, V>();
        for (Map.Entry<K, V> entry : v.entrySet()) {
            JaxbMapToListEntry<K, V> jme = new JaxbMapToListEntry<K, V>();
            jme.setKey(entry.getKey());
            jme.setValue(entry.getValue());
            result.getList().add(jme);
        }
        return result;
    }

}

Basically, the above adaptor converts a map into a list of entries (with key and value) when marshalling, and converts this list of entries back into a HashMap when unmarshalling.

The map-to-list and corresponding entries are:
public class JaxbMapToList <K, V> {

    private List<JaxbMapToListEntry<K, V>> list
        = new ArrayList<JaxbMapToListEntry<K, V>>();

    public JaxbMapToList() {}

    public JaxbMapToList(Map<K, V> map) {
        for (Map.Entry<K, V> e : map.entrySet()) {
            list.add(new JaxbMapToListEntry<K, V>(e));
        }
    }

    public List<JaxbMapToListEntry<K, V>> getList() {
        return list;
    }

    public void setList(List<JaxbMapToListEntry<K, V>> entry) {
        this.list = entry;
    }

}

public class JaxbMapToListEntry<K, V> {

    private K key;
    private V value;

    public JaxbMapToListEntry() { }

    public JaxbMapToListEntry(Map.Entry<K, V> e) {
        key = e.getKey();
        value = e.getValue();
    }

    @XmlElement
    public K getKey() {
        return key;
    }

    public void setKey(K key) {
        this.key = key;
    }

    @XmlElement
    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }

}
Assuming one instantiates the object with generic map with destination and transports:
@XmlRootElement
public class Destination {

    private String destination;

    public String getDestination() {
        return destination;
    }

    @XmlElement
    public void setDestination(String dest) {
        this.destination = dest;
    }

}

@XmlRootElement
public class Transport {

    private String transport;

    public String getTransport() {
        return transport;
    }

    @XmlElement
    public void setTransport(String transp) {
        this.transport = transp;
    }

}

public static void main(String[] args) throws JAXBException {

    JAXBContext jaxbContext = JAXBContext.newInstance(
        ObjectWithGenericMap.class,
        Destination.class, Transport.class);

    ObjectWithGenericMap<Destination,Transport> owgm
        = new ObjectWithGenericMap<Destination,Transport>();

    Map<Destination,Transport> map
        = new HashMap<Destination,Transport>();
    owgm.setMap(map);

    Destination d = new Destination();
    d.setDestination("Paris");

    Transport t = new Transport();
    t.setTransport("Plane");

    map.put(d,t);

    d = new Destination();
    d.setDestination("New-York");

    t = new Transport();
    t.setTransport("Boat");

    map.put(d,t);

    ObjectWithGenericMap<Destination,Transport> retr
        = marshallingUnmarshalling(jaxbContext, owgm);

    for (Entry<Destination, Transport> e : retr.getMap().entrySet() ){
        Destination retrd = e.getKey();
        System.out.print(retrd.getDestination());
        Transport retrt = e.getValue();
        System.out.println(" " + retrt.getTransport());
    }

}
The generated XML and verification is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithGenericMap>
    <map>
        <list>
            <key xsi:type="destination" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <destination>New-York</destination>
            </key>
            <value xsi:type="transport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <transport>Boat</transport>
            </value>
        </list>
        <list>
            <key xsi:type="destination" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <destination>Paris</destination>
            </key>
            <value xsi:type="transport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <transport>Plane</transport>
            </value>
        </list>
    </map>
</objectWithGenericMap>
Paris Plane
New-York Boat

How to use: @XmlList, @XmlEnum, @XmlAttribute, @XmlValue, @XmlMimeType, @XmlInlineBinaryData?


To annotate an enum:
@XmlEnum
public enum MyEnum {

    @XmlEnumValue("v1")
    VAL_1,

    @XmlEnumValue("v2")
    VAL_2;

}
To specify the xml tag value and attributes:
@XmlAccessorType(XmlAccessType.FIELD)
public class SpecialItem {

    @XmlValue
    private String val;

    @XmlAttribute
    private String attribute1;

    @XmlAttribute
    private String attribute2;

    // Setter & Getters...

}
For remaining annotations and usage of the above:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class MultipleTypes {

    @XmlElement
    private MyEnum myEnum;

    @XmlElement
    @XmlList
    private List<String> data;

    @XmlElement
    private List<SpecialItem> specialItems;

    @XmlMimeType("image/jpeg")
    private Image image;

    @XmlInlineBinaryData
    private byte[] byteArray;

    // Setter & Getters...

}
The generated XML and verification is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<multipleTypes>
    <myEnum>v2</myEnum>
    <data>tre pml xng</data>
    <specialItems attribute2="ffff" attribute1="aaaa">pppp</specialItems>
    <specialItems attribute2="pqgd" attribute1="mer">xxw</specialItems>
    <image>/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAALABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwCxBe6S1ha3ptg4MEYF29lGSXKA5JIznHvmuX1UaCmhapbwxW2023mxkWUSyedsbjPXaOTkdPX+9wieM/EEOlrpkeoEWS7SIfKQj5Rgfw88AflUb+JdVl0O7tHniMMkqbh9njDcq4Pzbcjj0PrXppRo3SuTVqVKrV7aH//Z</image>
    <byteArray>AQL9/A==</byteArray>
</multipleTypes>
pppp aaaa ffff
xxw mer pqgd
VAL_2
tre, pml, xng, 
1 2 -3 -4
Image is available: true

Remark

We have not covered all JAXB annotations, especially those related to XML schemas, but this tutorial should be enough to get one started and accomplish most objectives with JXTA.

JAXB to XMLJAXB to JSONJAXB Annotations Tutorial Table Of Content

Tuesday, 7 August 2012

JAXB Annotation - Can't Handle Interfaces

JAXB Can't Handle Interfaces in Generics

If you have a class with a List<Vehicle> and Vehicle is an interface, JAXB will throw an Exception at runtime:
my.package.MyInterface is an interface,
    and JAXB can't handle interfaces
The solution is to maket the interface an abstract class. For example:
public abstract class Vehicle {

    public abstract String getType();

}

@XmlRootElement
public class Bus extends Vehicle {

    private String type;

    public Bus() { };

    public Bus(String type) {
        this.type = type;
    }

    @XmlElement
    @Override
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}

@XmlRootElement
public class Car extends Vehicle {

    private String type;

    public Car() {};

    public Car(String type) {
        this.type = type;
    }
 
    @XmlElement
    @Override
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}

@XmlRootElement
public class ObjectWithListOfVehicles {

    private List<Vehicle> list;

    @XmlElementWrapper(name="MyVehicleList")
    @XmlElement
    public List<Vehicle> getList() {
        return list;
    }

    public void setList(List<Vehicle> list) {
        this.list = list;
    }

}
Assuming the following JAXB context:
public static void interfaceExamples() throws JAXBException {

    List<Vehicle> l = new ArrayList<Vehicle>();
    l.add(new Bus("Large bus"));
    l.add(new Bus("Small bus"));
    l.add(new Car("Ferrari"));

    // Object with generic list
    ObjectWithListOfVehicles owgl
        = new ObjectWithListOfVehicles();
    owgl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(
        Bus.class, Car.class,
        ObjectWithListOfVehicles.class);

    ObjectWithListOfVehicles retr
        = marshallUnmarshall(owgl, jc);

    for (Vehicle s : retr.getList()) {
        System.out.println(
            s.getClass().getSimpleName()
            + " - " + s.getType());
    } System.out.println(" ");

}

public static <O> O marshallUnmarshall(O o, JAXBContext jc)
        throws JAXBException {

    // Creating a Marshaller
    Marshaller jaxbMarshaller = jc.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter result = new StringWriter();
    jaxbMarshaller.marshal(o, result);

    // Printing XML
    String xml = result.toString();
    System.out.println(xml);

    // Creating an Unmarshaller
    Unmarshaller jaxbUnmarshaller = jc.createUnmarshaller();
    StringReader sr = new StringReader(xml);

    O retr = (O) jaxbUnmarshaller.unmarshal(sr);

    return retr;

}
The generated XML and verification is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithListOfVehicles>
    <MyVehicleList>
        <list xsi:type="bus" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>Large bus</type>
        </list>
        <list xsi:type="bus" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>Small bus</type>
        </list>
        <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>Ferrari</type>
        </list>
    </MyVehicleList>
</objectWithListOfVehicles>

Bus - Large bus
Bus - Small bus
Car - Ferrari

Notice that JAXB is capable of recreating both Bus and Car instances.

Next

JAXB to XMLJAXB to JSONJAXB Annotations Tutorial Table Of Content

JAXB Annotation - JAXB Context, Generics

Understanding JAXB Context

In order to marshall and unmarshall JAXB annotated classes, one needs to create a JAXBContext. The instantiator method takes in a list of JAXB annotated Class.

By default, JAXB will include statically referenced classes in the list and inherited classes, but not transient or inheriting classes. The code examples are available from Github in the JAXB-JSON-XML-Marshalling directory.

Assuming:
@XmlRootElement
public class StaticallyReferenced {

    private String data;

    @XmlElement
    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
    
}

@XmlRootElement
public class StaticallyReferencedButTransient {
    
    private String data;

    @XmlElement
    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
    
}

@XmlRootElement
public class SomeA {
    
    private StaticallyReferenced sr;
    private StaticallyReferencedButTransient srbt;

    @XmlElement
    public StaticallyReferenced getSr() {
        return sr;
    }

    public void setSr(StaticallyReferenced sr) {
        this.sr = sr;
    }

    @XmlTransient
    public StaticallyReferencedButTransient getSrbt() {
        return srbt;
    }

    public void setSrbt(
            StaticallyReferencedButTransient srbt) {
        this.srbt = srbt;
    }

}

@XmlRootElement
public class InheritSomeA extends SomeA {
    
    private String moreData;

    @XmlElement
    public String getMoreData() {
        return moreData;
    }

    public void setMoreData(String moreData) {
        this.moreData = moreData;
    }
    
}
If one creates the following JAXB context:
JAXBContext jaxbContext =
    JAXBContext.newInstance(SomeA.class);
JAXB will only be able to process SomeA and StaticallyReferenced, not StaticallyReferencedButTransient or InheritSomeA.

How to use JAXB with Generics such as List, Set, etc...?

Assuming a simple example, where an object contains a List<String>:
@XmlRootElement
public class ObjectWithList {

    private List<String> list;

    @XmlElementWrapper(name="MyList")
    @XmlElement
    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

}
If the JAXB context is built as following (before a round trip):
public static void simpleExample() throws JAXBException {

    List<String> l = new ArrayList<String>();
    l.add("Somewhere");
    l.add("This and that");
    l.add("Something");

    // Object with list
    ObjectWithList owl = new ObjectWithList();
    owl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(ObjectWithList.class);
    ObjectWithList retr = marshallUnmarshall(owl, jc);

    for (String s : retr.getList()) {
        System.out.println(s);
    } System.out.println(" ");

}
The generated XML with verification is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithList>
    <MyList>
        <list>Somewhere</list>
        <list>This and that</list>
        <list>Something</list>
    </MyList>
</objectWithList>

Somewhere
This and that
Something
A more sophisticated example with a generic list:
@XmlRootElement
public class ObjectWithGenericList<T> {

    private List<T> myList;

    @XmlElementWrapper(name="MyGenericList")
    @XmlElement
    public List<T> getList() {
        return myList;
    }

    public void setList(List<T> list) {
        this.myList = list;
    }

}
used with the following JAXB context and verification:
public static void genericListExample()
        throws JAXBException {

    List<Car> l = new ArrayList<Car>();
    l.add(new Car("red car"));
    l.add(new Car("blue car"));
    l.add(new Car("green car"));

    // Object with generic list
    ObjectWithGenericList<Car> owgl
        = new ObjectWithGenericList<Car>();
    owgl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(
        ObjectWithGenericList.class, Car.class);
    ObjectWithGenericList<Car> retr
        = marshallUnmarshall(owgl, jc);

    for (Car s : retr.getList()) {
        System.out.println(
        s.getClass().getSimpleName() + " - " + s.getType());
    } System.out.println(" ");

}
generates the following XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithGenericList>
    <MyGenericList>
        <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>red car</type>
        </list>
        <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>blue car</type>
        </list>
        <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>green car</type>
        </list>
    </MyGenericList>
</objectWithGenericList>

Car - red car
Car - blue car
Car - green car
Notice that JAXB is capable of recreating Car instances.

Next

JAXB to XMLJAXB to JSONJAXB Annotations Tutorial Table Of Content

Monday, 6 August 2012

JAXB Annotation - Basic Annotations, Inheritance

JAXB (Java Architecture for XML Binding) enables the mapping of Java object into XML documents back and forth. This post is an introduction, tutorial and summary of JAXB annotations. It proceeds with operational code examples to describe each feature.

The code examples are available from Github in the JAXB-JSON-XML-Marshalling directory. Most examples rely on the following piece of code to create XML files from annotated Java objects:
    public static void createXML(Object o) throws JAXBException {
        
        // Creating a Marshaller
        JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 
        StringWriter result = new StringWriter();
        jaxbMarshaller.marshal(o, result);

        // Printing XML
        String xml = result.toString();
        System.out.println(xml);
        
    } 
In order to generate such XML documents, a JAXB context must be created. More details on this in part II.

@XmlRootElement

Defines the root element of the XML document. If not name is specified (like this for example: @XmlRootElement(name = "MyRootName"), the name of the element is taken from the class name.

This annotation can be used on a Class or on an enum. A Class does need a no parameter constructor or a factory method (more details in the @XmlType section).

For example:
@XmlRootElement(name="MyRootName")
public class A {

    private int a1 = 0;

    @XmlElement
    public int getA1() {
        return a1;
    }

    public void setA1(int a1) {
       this.a1 = a1;
    }

}
generates the following XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<MyRootName>
   <a1>28</a1>
</MyRootName>
One can also specify a namespace name for the XML element or a local name for the XML element.

Inheritance

When a class inherits of another annotated class, the root name is taken from the inheriting class:
@XmlRootElement
public class InheritsA extends A {

    private int b1 = 0;

    @XmlElement
    public int getB1() {
        return b1;
    }

    public void setB1(int b1) {
        this.b1 = b1;
    }

}
The generated XML is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<inheritsA>
    <a1>33</a1>
    <b1>66</b1>
</inheritsA>

@XmlElement / @XmlTransient

The @XmlElement indicates which element should be included in the XML conversion. If you want to annotate fields instead of getter methods, use the @XmlAccessorType(XmlAccessType.FIELD).

If you need to exclude a field from the generated XML, use the @XmlTransient annotation.
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class FieldAnnotation {

    @XmlElement
    private int a1 = 45;

    @XmlTransient
    private long a2 = 0;

    @XmlElement(nillable=true)
    private String xxx = null;

    @XmlElement(required=true)
    private String req;

    public int getA1() {
        return a1;
    }

    public void setA1(int a1) {
        this.a1 = a1;
    }

    public long getA2() {
        return a2;
    }

    public void setA2(long a2) {
        this.a2 = a2;
    }

    public String getXxx() {
        return xxx;
    }

    public void setXxx(String xxx) {
        this.xxx = xxx;
    }

    public String getReq() {
        return req;
    }

    public void setReq(String req) {
        this.req = req;
    }

} 
Assuming the following class creation:
FieldAnnotation fa = new FieldAnnotation();
fa.setA2(28);
fa.setReq("Some value");
generates:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<fieldAnnotation>
    <a1>45</a1>
    <xxx xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
    <req>Some value</req>
</fieldAnnotation>
One can also set a default string value, or set the XML Schema element name and the target namespace of the XML element via the @XmlElement annotation.

@XmlType

This annotation allows one to specify the order of items in the generated XML document. It can also be used to specify a factory class and/or a factory method (with no arguments) to create instances of the annotated class:
@XmlRootElement
@XmlType(propOrder={"a2", "a1"},
  factoryClass=OrderFactory.class,
  factoryMethod="myConstructor")
public class Order {

    private int a1 = 0;
    private int a2 = 0;

    @XmlElement
    public int getA1() {
        return a1;
    }

    public void setA1(int a1) {
        this.a1 = a1;
    }

    @XmlElement
    public int getA2() {
        return a2;
    }

    public void setA2(int a2) {
        this.a2 = a2;
    }

}
The factory class:
public class OrderFactory {
    public static Order myConstructor() {
        return new Order();
    }
}
The generated XML:
<order>
  <a2>99</a2>
  <a1>28</a1>
</order>
One can also set the XML Schema type and the target namespace of the XML Schema type with the @XmlType annotation.

@XmlSeeAlso

This annotation allows one to refer to other classes to include in the XML generation. In other words, if a referred class is not in the JAXB context, it will be taken into account anyway and won't trigger a runtime error. This annotation can be used as a safeguard when marshalling and unmarshalling.

This is best described with an example:
@XmlRootElement
public class Document {

    private String content = "";

    @XmlElement
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}
@XmlRootElement
public class Image {

    private String name = "";

    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String content) {
        this.name = content;
    }

}
@XmlRootElement
@XmlSeeAlso({Document.class,Image.class})
public class Folder {

    private Document document = null;
    private Image image = null;

    @XmlElement
    public Document getDocument() {
        return document;
    }

    public void setDocument(Document document) {
        this.document = document;
    }

    @XmlElement
    public Image getImage() {
        return image;
    }

    public void setImage(Image image) {
        this.image = image;
    }

}
The generated output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<folder>
    <document>
        <content>My content</content>
    </document>
    <image>
        <name>My image</name>
    </image>
</folder>

Next

JAXB to XMLJAXB to JSONJAXB Annotations Tutorial Table Of Content