Orika Mapper Example

Orika Mapper Example

In this post, we will see Orika Mapper Example from scratch. Orika is used to copy data from one object to another object.

Simple Orika mapper Example – Default mapping.

maven dependency.

<dependencies>

    <!-- https://mvnrepository.com/artifact/ma.glasnost.orika/orika-core -->
    <dependency>
        <groupId>ma.glasnost.orika</groupId>
        <artifactId>orika-core</artifactId>
        <version>1.5.4</version>
    </dependency>
</dependencies>

Student.java

public class Student {
	private String name;
	private String id;
	//getter-setter
}

StudentDto.java

public class StudentDTO {
	private String name;
	private String id;
	//getter-setter
}

OrikaConfig.java

public class OrikaConfig extends ConfigurableMapper {

	protected void configure(MapperFactory factory) {
		factory.classMap(Student.class, StudentDTO.class).byDefault().register();
	}

}

Note – We can use field() method to define field name. Since both class(Student.java & StudentDto.java contains same field name, by defaut Orika will map these). The below code will give the same output.

	protected void configure(MapperFactory factory) {
		factory.classMap(Student.class, StudentDTO.class)
		.field("name", "name")
		.field("id", "id")
		.byDefault().register();
	}

OrikaExample.java

package javaorikamapperexample;

import ma.glasnost.orika.MapperFacade;

public class OrikaExample {
	public static void main(String[] args) {
		MapperFacade facade = new OrikaConfig();
		Student s = new Student();
		s.setId("1");
		s.setName("John");

		StudentDTO studentDto = facade.map(s, StudentDTO.class);
		System.out.println(studentDto.getId());
		System.out.println(studentDto.getName());
	}
}

Output –

Orika Mapper Example

Map fields with different names

Student.java

public class Student {
	private String name;
	private String id;
	//getter-setter
}

StudentDto.java


public class StudentDTO {
	private String studentName;
	private String studentId;
	//getter-setter
}

OrikaConfig.java

package javaorikamapperexample;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

public class OrikaConfig extends ConfigurableMapper {

	protected void configure(MapperFactory factory) {
		factory.classMap(Student.class, StudentDTO.class)
		.field("name", "studentName")
		.field("id", "studentId")
		.byDefault().register();
	}

}

OrikaExample.java

package javaorikamapperexample;

import ma.glasnost.orika.MapperFacade;

public class OrikaExample {
	public static void main(String[] args) {
		MapperFacade facade = new OrikaConfig();
		Student s = new Student();
		s.setId("1");
		s.setName("John");

		StudentDTO studentDto = facade.map(s, StudentDTO.class);
		System.out.println(studentDto.getStudentId());
		System.out.println(studentDto.getStudentName());
	}
}

Map fields with different names

Map Fields for Nested Objects.

Address.java

package javaorikamapperexample;

public class Address {
	String cityName;
	//getter-setter
}

Student.java

package javaorikamapperexample;

public class Student {
	private String name;
	private String id;
	private Address address;
        // getter-setter
}
package javaorikamapperexample;

public class StudentDTO {
	private String name;
	private String id;
	private String cityName;
	// getter-setter
}

OrikaConfig.java

package javaorikamapperexample;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

public class OrikaConfig extends ConfigurableMapper {

	protected void configure(MapperFactory factory) {
		factory.classMap(Student.class, StudentDTO.class)
		.field("name", "name")
		.field("id", "id")
		.field("address.cityName", "cityName")
		.byDefault().register();
	}
}

OrikaExample.java

package javaorikamapperexample;

import ma.glasnost.orika.MapperFacade;

public class OrikaExample {
	public static void main(String[] args) {
		MapperFacade facade = new OrikaConfig();
		Student s = new Student();
		s.setId("1");
		s.setName("John");
		Address address = new Address();
		address.setCityName("France");
		s.setAddress(address);

		StudentDTO studentDto = facade.map(s, StudentDTO.class);
		System.out.println(studentDto.getName());
		System.out.println(studentDto.getId());
		System.out.println(studentDto.getCityName());
	}
}

Output –

Orika mapper list example

mapAsList() example

OrikaConfig.java

package javaorikamapperexample;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

public class OrikaConfig extends ConfigurableMapper {

	protected void configure(MapperFactory factory) {
		factory.classMap(Student.class, StudentDto.class)
		.byDefault().register();
	}
}

OrikaExample.java

package javaorikamapperexample;

import java.util.ArrayList;
import java.util.List;

import ma.glasnost.orika.MapperFacade;

public class OrikaExample {
	public static void main(String[] args) {
		MapperFacade facade = new OrikaConfig();
		Student s = new Student();
		s.setId("1");
		s.setName("John");
		List<Student> students = new ArrayList<Student>();
		students.add(s);
		List<StudentDto> studentDtos = facade.mapAsList(students, StudentDto.class);
		System.out.println(studentDtos.get(0).getId());
		System.out.println(studentDtos.get(0).getName());
	}
}

Orika list type field example

Student.java


package javaorikamapperexample;

import java.util.List;

public class Student {
	private List<String> names;

	public List<String> getNames() {
		return names;
	}

	public void setNames(List<String> names) {
		this.names = names;
	}
}

StudentDto.java

package javaorikamapperexample;

public class StudentDto {
	private String firstName;
	private String lastName;
	//getter & setter

}

OrikaConfig.java

package javaorikamapperexample;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

public class OrikaConfig extends ConfigurableMapper {

	protected void configure(MapperFactory factory) {
		factory.classMap(Student.class, StudentDto.class)
		.field("names[0]", "firstName")
	     .field("names[1]", "lastName").register();
	}
}

OrikaExample.java

package javaorikamapperexample;

import java.util.ArrayList;
import java.util.List;

import ma.glasnost.orika.MapperFacade;

public class OrikaExample {
	public static void main(String[] args) {
		MapperFacade facade = new OrikaConfig();
		List<String> names = new ArrayList<String>();
		names.add("jack");
		names.add("sparrow");
		Student s = new Student();
		s.setNames(names);
		StudentDto studentDto=  facade.map(s, StudentDto.class);
		System.out.println(studentDto.getFirstName());
		System.out.println(studentDto.getLastName());
	}
}

Excluding field – exclude() method example

Student.java

package javaorikamapperexample;

public class Student {
	private String name;
	private String id;
	private String rollNumber;
	//getter-setter example
}

StudentDto.java

package javaorikamapperexample;

public class StudentDto {
	private String name;
	private String id;
	private String rollNumber;
	//getter & setter
	
}

OrikaConfig.java

package javaorikamapperexample;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

public class OrikaConfig extends ConfigurableMapper {

	protected void configure(MapperFactory factory) {
		factory.classMap(Student.class, StudentDto.class).exclude("rollNumber").byDefault().register();
	}
}

OrikaExample.java

package javaorikamapperexample;

import ma.glasnost.orika.MapperFacade;

public class OrikaExample {
	public static void main(String[] args) {
		MapperFacade facade = new OrikaConfig();

		Student s = new Student();
		s.setName("jack");
		s.setId("1");
		s.setRollNumber("10");
		StudentDto studentDto = facade.map(s, StudentDto.class);
		System.out.println(studentDto.getName());
		System.out.println(studentDto.getId());
		System.out.println(studentDto.getRollNumber());
	}
}

StudentDto object is created using facade.map() method. All Student attributes are getting populated to StudentDto object.

Orika mapper custom converter Example

Defining orika custom converter extending Converter class

package javaorikamapperexample;

import java.util.Date;

import ma.glasnost.orika.CustomConverter;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.metadata.Type;

public class MyCustomConverter extends CustomConverter<Date, MyCustomDate> {

	
	public MyCustomDate convert(Date date, Type<? extends MyCustomDate> destinationType,
			MappingContext mappingContext) {
		MyCustomDate myCustomDate = new MyCustomDate();
		myCustomDate.setDateOfBirthDay(date.getDate());
		myCustomDate.setDateOfBirthMonth(date.getMonth());
		myCustomDate.setDateOfBirthYear(date.getYear());
		return myCustomDate;
	}

}

Registering Converters Globally

package javaorikamapperexample;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.converter.ConverterFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

public class OrikaConfig extends ConfigurableMapper {

	protected void configure(MapperFactory factory) {

		factory.classMap(Student.class, StudentDto.class).byDefault().register();
		ConverterFactory converterFactory = factory.getConverterFactory();
		converterFactory.registerConverter(new MyCustomConverter());
	}
}

Let’s see complete example.

Directory structure.

Orika mapper custom converter Example

Student.java

package javaorikamapperexample;

import java.util.Date;

public class Student {
	private String name;
	private String id;
	private Date dateOfBirth;
	//getter & setter

}

StudentDto.java

package javaorikamapperexample;

public class StudentDto {
	private String name;
	private String id;
	private MyCustomDate dateOfBirth;
	//getter & setter
	
}

OrikaConfig.java

package javaorikamapperexample;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.converter.ConverterFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

public class OrikaConfig extends ConfigurableMapper {

	protected void configure(MapperFactory factory) {

		factory.classMap(Student.class, StudentDto.class).byDefault().register();
		ConverterFactory converterFactory = factory.getConverterFactory();
		converterFactory.registerConverter(new MyCustomConverter());
	}
}

OrikaExample.java

MyCustomConverter.java


package javaorikamapperexample;

import java.util.Date;

import ma.glasnost.orika.CustomConverter;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.metadata.Type;

public class MyCustomConverter extends CustomConverter<Date, MyCustomDate> {

	
	public MyCustomDate convert(Date date, Type<? extends MyCustomDate> destinationType,
			MappingContext mappingContext) {
		MyCustomDate myCustomDate = new MyCustomDate();
		myCustomDate.setDateOfBirthDay(date.getDate());
		myCustomDate.setDateOfBirthMonth(date.getMonth());
		myCustomDate.setDateOfBirthYear(date.getYear());
		return myCustomDate;
	}

}

MyCustomDate.java

package javaorikamapperexample;

public class MyCustomDate {
	private int dateOfBirthDay;
	private int dateOfBirthMonth;
	private int dateOfBirthYear;
	public int getDateOfBirthDay() {
		return dateOfBirthDay;
	}
	public void setDateOfBirthDay(int dateOfBirthDay) {
		this.dateOfBirthDay = dateOfBirthDay;
	}
	public int getDateOfBirthMonth() {
		return dateOfBirthMonth;
	}
	public void setDateOfBirthMonth(int dateOfBirthMonth) {
		this.dateOfBirthMonth = dateOfBirthMonth;
	}
	public int getDateOfBirthYear() {
		return dateOfBirthYear;
	}
	public void setDateOfBirthYear(int dateOfBirthYear) {
		this.dateOfBirthYear = dateOfBirthYear;
	}

}
package javaorikamapperexample;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import ma.glasnost.orika.MapperFacade;

public class OrikaExample {
	public static void main(String[] args) throws ParseException {
		MapperFacade facade = new OrikaConfig();

		Student s = new Student();
		s.setName("jack");
		s.setId("1");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = sdf.parse("1980-07-26");
		s.setDateOfBirth(date);
		StudentDto studentDto = facade.map(s, StudentDto.class);
		System.out.println(studentDto.getName());
		System.out.println(studentDto.getId());
		System.out.println(studentDto.getDateOfBirth().getDateOfBirthDay());
		System.out.println(studentDto.getDateOfBirth().getDateOfBirthMonth());
		System.out.println(studentDto.getDateOfBirth().getDateOfBirthYear());
	}
}

Output

Spring Boot Orika mapper MySql Example

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – springbootorikaexample, ArtifactId – springbootorikaexample, and name – springbootorikaexample) and click on finish. Keep packaging as the jar.

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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>springbootorikaexample</groupId>
	<artifactId>springbootorikaexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springbootorikaexample</name>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>	
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/ma.glasnost.orika/orika-core -->
		<dependency>
			<groupId>ma.glasnost.orika</groupId>
			<artifactId>orika-core</artifactId>
			<version>1.5.4</version>
		</dependency>		
	</dependencies>

</project>

Directory structure.

Spring Boot orika mapper example

Define entity class – Student.java

package com.springbootorikaexample.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	@Column(name = "name")
	private String name;

	@Column(name = "roll_number")
	private String rollNumber;

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public String getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(String rollNumber) {
		this.rollNumber = rollNumber;
	}

}

Define DTO – StudentDto.java

package com.springbootorikaexample.dto;

public class StudentDto {
	private Long id;
	private String name;
	private String rollNumber;

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public String getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(String rollNumber) {
		this.rollNumber = rollNumber;
	}

}

Define Repository interface.

package com.springbootorikaexample.repository;

import java.io.Serializable;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.springbootorikaexample.entity.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {

}

Define service interface.

package com.springbootorikaexample.service;

import org.springframework.stereotype.Component;

import com.springbootorikaexample.entity.Student;

@Component
public interface StudentService {
	public Student save(Student student);
	public Student get(Long id);
}

Define StudentServiceImpl.java class.

package com.springbootorikaexample.serviceimpl;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.springbootorikaexample.entity.Student;
import com.springbootorikaexample.repository.StudentRepository;
import com.springbootorikaexample.service.StudentService;

@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@Transactional
	public Student save(Student student) {
		Student createResponse = studentRepository.save(student);
		return createResponse;
	}

	@Transactional
	public Student get(Long id) {
		Optional<Student> response = studentRepository.findById(id);
		Student getResponse = response.get();
		return getResponse;
	}


}

Define controller class – StudentController.java

package com.springbootorikaexample.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.springbootorikaexample.dto.StudentDto;
import com.springbootorikaexample.entity.Student;
import com.springbootorikaexample.service.StudentService;

import ma.glasnost.orika.MapperFacade;

@RestController
@RequestMapping("/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@Autowired
	private MapperFacade facade;

	@PostMapping("/create")
	public Student createStudent1(@RequestBody Student student) {
		Student createResponse = studentService.save(student);
		return createResponse;
	}

	@GetMapping("/{id}")
	public StudentDto getStudent(@PathVariable Long id) {
		Student entity = studentService.get(id);
		StudentDto response = facade.map(entity, StudentDto.class);
		return response;
	}

}

JpaConfig.java

package com.springbootorikaexample.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import ma.glasnost.orika.MapperFacade;

@Configuration
@EnableJpaRepositories(basePackages = "com.springbootorikaexample.repository")
public class JpaConfig {
	@Bean
	public MapperFacade mapperFacade() {
		MapperFacade facade = new OrikaConfig();
		return facade;
	}
}

OrikaConfig.java

package com.springbootorikaexample.config;

import com.springbootorikaexample.dto.StudentDto;
import com.springbootorikaexample.entity.Student;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

public class OrikaConfig extends ConfigurableMapper {

	protected void configure(MapperFactory factory) {
		factory.classMap(Student.class, StudentDto.class).byDefault().register();
	}

}

SpringMain.java

package com.springbootorikaexample.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.springbootorikaexample.*")
@EntityScan("com.springbootorikaexample.*")
public class SpringMain {
	public static void main(String[] args) {
		SpringApplication.run(SpringMain.class, args);
	}
}

application.yml

spring:
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: create
  datasource:
    url: jdbc:mysql://localhost:3306/springbootcrudexample
    username: root
    password: root
server:
   port: 9091       

Let’s Run the application.

Create Student using below API.

http://localhost:9091/student/create

Now perform GET operation.

http://localhost:9091/student/1

Spring Boot orika mapper example

That’s all about Orika Mapper Example.

You may like.

Summary – We have seen about Orika Mapper Example.

Download the Source Code of Orika Mapper Example from GitHub.

See Orika Docs here.