You can use Jackson's ObjectMapper library to achieve this. In order for this to work you must have getters declared in both EntityA and EntityB class, as well as a default (empty) constructor.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
 * Function converts list of objects to another list of objects
 * which' type is specified by the clazz attribute. Clazz attribute
 * must not be null, or it will throw a NullPointerException.
 * 
 * @param list List of target objects
 * @param clazz Class to map list objects to
 * @param <T> Target class
 * @param <F> From class
 * @return F.class List converted to T.class List
 */
public static <T, F> List<T> convertList(List<F> list, Class<T> clazz) {
    Objects.requireNonNull(clazz);
    ObjectMapper mapper = new ObjectMapper();

    // Important: this must be declared so mapper doesn't throw 
    // an exception for all properties which it can't map.
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return Optional.ofNullable(list)
            .orElse(Collections.emptyList())
            .stream()
            .map(obj -> mapper.convertValue(obj, clazz))
            .collect(Collectors.toList());
}
public void insertListItems(List<EntityA> entityAList) {
    List<EntityB> entityBList = convertList(entityAList, EntityB.class);
    // Continue with table insert operation
}
Answer from BrunoT on Stack Overflow
🌐
Medium
medium.com › thefreshwrites › guide-to-object-mapping-with-modelmapper-in-java-1dd8f517faf2
Guide to Object Mapping with ModelMapper in Java
February 18, 2023 - Object mapping is a process of transforming data from one object to another. In Java, it can be a tedious task that requires a lot of boilerplate code to map data between two objects with different structures.
🌐
Baeldung
baeldung.com › home › java › java collections › java map › converting object to map in java
Converting Object To Map in Java | Baeldung
January 8, 2024 - The following example shows how we can convert a Java object (employee) into a map using Jackson: @Test public void givenJavaObject_whenUsingJackson_thenConvertToMap() { ObjectMapper objectMapper = new ObjectMapper(); Map<String, Object> map = objectMapper .convertValue(employee, new TypeReference<Map<String, Object>>() {}); Assert.assertEquals(employee.getName(), map.get("name")); Assert.assertEquals(employee.getAge(), map.get("salary")); }
Top answer
1 of 4
2

You can use Jackson's ObjectMapper library to achieve this. In order for this to work you must have getters declared in both EntityA and EntityB class, as well as a default (empty) constructor.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
 * Function converts list of objects to another list of objects
 * which' type is specified by the clazz attribute. Clazz attribute
 * must not be null, or it will throw a NullPointerException.
 * 
 * @param list List of target objects
 * @param clazz Class to map list objects to
 * @param <T> Target class
 * @param <F> From class
 * @return F.class List converted to T.class List
 */
public static <T, F> List<T> convertList(List<F> list, Class<T> clazz) {
    Objects.requireNonNull(clazz);
    ObjectMapper mapper = new ObjectMapper();

    // Important: this must be declared so mapper doesn't throw 
    // an exception for all properties which it can't map.
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return Optional.ofNullable(list)
            .orElse(Collections.emptyList())
            .stream()
            .map(obj -> mapper.convertValue(obj, clazz))
            .collect(Collectors.toList());
}
public void insertListItems(List<EntityA> entityAList) {
    List<EntityB> entityBList = convertList(entityAList, EntityB.class);
    // Continue with table insert operation
}
2 of 4
0

You could try to get a Map like this Map<String, List<String> columns;

The first value (key) is the column name and the second value (value) is a list of all values of this column.

Then you can just use if statements for selecting a column or not.

So:

  1. Load all columns and their values
  2. Use a loop with if statements.
  3. In this loop, you could also integrate a list of Strings, which are the unallowed or allowed column names.
🌐
Medium
medium.com › @salvipriya97 › objectmapper-and-its-methods-examples-in-java-4a4cab75cb6b
ObjectMapper and its methods examples in Java | by Priya Salvi | Medium
June 25, 2024 - Purpose: Converts an object of one type to another. ... import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; public class Main { public static void main(String[] args) { ObjectMapper objectMapper = new ObjectMapper(); Person person = new Person("John", 30); try { Map<String, Object> map = objectMapper.convertValue(person, Map.class); System.out.println(map); // Output: {name=John, age=30} } catch (Exception e) { e.printStackTrace(); } } }
🌐
Medium
medium.com › @ajitmanware5 › mastering-object-mapping-in-java-a-comprehensive-guide-to-modelmapper-e99f6827b12e
Mastering Object Mapping in Java: A Comprehensive Guide to ModelMapper | by Ajit Manware | Medium
November 20, 2023 - Object mapping, the process of transforming data from one object to another, is a common task in Java development. It becomes particularly crucial when dealing with different layers of an application, such as mapping between DTOs (Data Transfer Objects) and domain entities.
🌐
javathinking
javathinking.com › blog › convert-one-object-to-another-java-objectmapper
Converting One Object to Another with Java ObjectMapper — javathinking.com
It acts as a central component for reading and writing JSON data. When it comes to object conversion, ObjectMapper can map the properties of one Java object to another based on their names.
🌐
Oodlestechnologies
oodlestechnologies.com › blogs › object-cloning-and-its-mapping-using-object-mapper
Object Cloning and its Mapping Using Object Mapper
February 14, 2020 - public void getStudentDTO(){ Student student = new Student("pradeep",25,"SRCEM"); StudentDTO studentDTO = copyPropertiesByMapper(student,StudentDTO.class); } public static <E extends Object,T extends Object> T copyPropertiesByMapper(E object,Class<T> valueType,String... fields){ ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JavaTimeModule javaTimeModule = new JavaTimeModule(); SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept(fields); FilterProvider filters = new SimpleFilterProvi
🌐
How to do in Java
howtodoinjava.com › home › java basics › convert an object to map in java
Convert an Object to Map in Java
September 19, 2022 - Employee employee = new Employee(1, "Alex", LocalDate.of(1995, 1, 2), List.of("Delhi", "Nevada"), List.of(new Role(11, "Finance"), new Role(12, "HR"))); System.out.println(convertObjectToMapUsingObjectMapper(employee)); //The conversion method static Map<String, String> convertObjectToMapUsingObjectMapper(Employee employee) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); return objectMapper.convertValue(employee, Map.class); } The program output. { id=1, name=Alex, dateOfBirth=1995-01-02, locations=[Delhi, Nevada], roles=[ {id=11, name=Finance}, {id=12, name=HR} ] } Note that this method converts the associated and nested classes (such as Role) also into LinkedHashMap. Another interesting solution is to convert the Object to Properties.
Find elsewhere
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java Object to Object Mapper
October 7, 2013 - Modelbridge: Modelbridge is an Eclipse plugin that lets you copy data between Java objects. omapper: This project aims at providing a simple library to ease the process of mapping objects or beans from one design layer to another design layer, using annotations.
🌐
YouTube
youtube.com › gain java knowledge
How to Map one Object to another in Spring Boot - YouTube
Hi Friends, #GainJavaKnowledgeWelcome to this channel Gain Java Knowledge. We are providing best content of Java in vide...
Published: April 2, 2023
Views: 1K
Top answer
1 of 9
413

There are some libraries around there:

  • Commons-BeanUtils: ConvertUtils -> Utility methods for converting String scalar values to objects of the specified Class, String arrays to arrays of the specified Class.

  • Commons-Lang: ArrayUtils -> Operations on arrays, primitive arrays (like int[]) and primitive wrapper arrays (like Integer[]).

  • Spring framework: Spring has an excellent support for PropertyEditors, that can also be used to transform Objects to/from Strings.

  • Dozer: Dozer is a powerful, yet simple Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.

  • ModelMapper: ModelMapper is an intelligent object mapping framework that automatically maps objects to each other. It uses a convention based approach to map objects while providing a simple refactoring safe API for handling specific use cases.

  • MapStruct: MapStruct is a compile-time code generator for bean mappings, resulting in fast (no usage of reflection or similar), dependency-less and type-safe mapping code at runtime.

  • Orika: Orika uses byte code generation to create fast mappers with minimal overhead.

  • Selma: Compile-time code-generator for mappings

  • JMapper: Bean mapper generation using Annotation, XML or API

    • seems dead, last update in 2023
  • Smooks: The Smooks JavaBean Cartridge allows you to create and populate Java objects from your message data (i.e. bind data to) (suggested by superfilin in comments).

    • No longer under active development
  • Commons-Convert: Commons-Convert aims to provide a single library dedicated to the task of converting an object of one type to another. The first stage will focus on Object to String and String to Object conversions.

    • seems dead, last update in 2010
  • Transmorph: Transmorph is a free java library used to convert a Java object of one type into an object of another type (with another signature, possibly parameterized).

    • seems dead, last update in 2013
  • EZMorph: EZMorph is simple java library for transforming an Object to another Object. It supports transformations for primitives and Objects, for multidimensional arrays and transformations with DynaBeans

    • seems dead, last update in 2008
  • Morph: Morph is a Java framework that eases the internal interoperability of an application. As information flows through an application, it undergoes multiple transformations. Morph provides a standard way to implement these transformations.

    • seems dead, last update in 2008
  • Lorentz: Lorentz is a generic object-to-object conversion framework. It provides a simple API to convert a Java objects of one type into an object of another type.

    • seems dead
  • OTOM: With OTOM, you can copy any data from any object to any other object. The possibilities are endless. Welcome to "Autumn".

    • seems dead
2 of 9
109

You could try Dozer.

Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.

Dozer supports simple property mapping, complex type mapping, bi-directional mapping, implicit-explicit mapping, as well as recursive mapping. This includes mapping collection attributes that also need mapping at the element level.

🌐
Java Code Geeks
javacodegeeks.com › home › core java
Casting Maps into Complex Objects in Java - Java Code Geeks
June 21, 2024 - In summary, the code initializes a map with values representing an employee’s details and uses Jackson’s ObjectMapper to convert this map into an Employee POJO.
🌐
ModelMapper
modelmapper.org
ModelMapper - Simple, Intelligent, Object Mapping.
Applications often consist of similar but different object models, where the data in two models may be similar but the structure and concerns of the models are different. Object mapping makes it easy to convert one model to another, allowing separate models to remain segregated.
🌐
GitHub
github.com › lbovolini › object-mapper
GitHub - lbovolini/object-mapper: Maps an object to another via getters and setters methods · GitHub
StudentDTO studentDTO = new ... studentDTO.setBirthday(birthday); studentDTO.setCourseId(courseId); Student student = ObjectMapper.map(studentDTO, Student.class);...
Author: lbovolini
🌐
Medium
gainjavaknowledge.medium.com › how-to-map-one-object-into-another-in-spring-boot-application-91dc7e8f6353
How To Map One Object into Another In Spring Boot Application | by Real World Java | Medium
April 2, 2023 - In this article, we will learn how to Map one Object into another using ModelMapper library that simplifies the object mapping process and…
🌐
Aerospike
aerospike.com › home › docs › develop › aerospike tutorial: java object mapper
Aerospike Tutorial: Java Object Mapper | Aerospike Documentation
1 week ago - The object mapper handles circular references in the object graph. Self-referencing classes are a special case of circular reference. A class that has references to other instances of the same class is often needed. For example, a Person object with a spouse field that is a reference to another Person, and similarly with a children field.
🌐
javaspring
javaspring.net › blog › java-object-mapper
Java Object Mapper: A Comprehensive Guide — javaspring.net
import com.fasterxml.jackson.databind.ObjectMapper; // Define a simple Java class class User { private String name; private int age; // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class JacksonExample { public static void main(String[] args) throws Exception { // Create an ObjectMapper instance ObjectMapper objectMapper = new ObjectMapper(); // Serialization User user = new User(); user.setName("John"); user.setAge(30); String json
🌐
GitHub
gist.github.com › tcombs › bb823ba1cce00192709f64ee739ae96d
Use Gson to map from one object to another. · GitHub
ObjectMapper.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ·
🌐
Spring Framework Guru
springframework.guru › home › how to the jackson object mapper with json
How to The Jackson Object Mapper with JSON - Spring Framework Guru
October 22, 2024 - From the output you can see we have a proper JSON object whose property names are inherited from the Map keys. Jackson’s objectMapper can also easily produce JSON arrays from Java lists.
🌐
DevQA
devqa.io › map-json-string-to-java-object
How to Map a JSON String to a Java Object
July 11, 2023 - Using the readValue() method, we pass the JSON string and the target Java class (Person.class) to map the JSON string to a Person object. Finally, we can access the properties of the mapped object.