将一个实体转换为Java中的另一个实体

发布于 2025-01-23 08:17:42 字数 847 浏览 0 评论 0原文

我有2个不同的实体类,如下:

@Table(name = "tableA")
public class EntityA{

    @PartitionKey
    @Column(name = "age")
    int age;

    @PartitionKey
    @Column(name = "class")
    int class;

    @Column(name = "rollNo")
    int rollNo;

}

@Table(name = "tableB")
public class EntityA{

    @PartitionKey
    @Column(name = "class")
    int class;

    @Column(name = "rollNo")
    int rollNo;

    // one column less 
}

现在,基于某种条件,我需要将数据持续到两个表中。

在我的服务层中,我有一个eNtitya :: list< entitya>的列表,我将传递给daoimpl方法,在其中我插入数据如下:

public void insertListItems(List<EntityA> entityAList) {
    // here I need to convert the List<EntityA>  to List<EntityB>
    // before table insert operation.
}

我如何在eNitityB中进行转换,少列。我不想为转换编写样板代码,因为我的实体课程实际上很大。而是使用一些有助于映射的库。

I have 2 different Entity Class as below :

@Table(name = "tableA")
public class EntityA{

    @PartitionKey
    @Column(name = "age")
    int age;

    @PartitionKey
    @Column(name = "class")
    int class;

    @Column(name = "rollNo")
    int rollNo;

}

@Table(name = "tableB")
public class EntityA{

    @PartitionKey
    @Column(name = "class")
    int class;

    @Column(name = "rollNo")
    int rollNo;

    // one column less 
}

Now based on some condition I need to persist the data in both the tables.

In my service layer I have a List of EntityA :: List<EntityA> which I am passing to the DAOImpl method where I insert the data as below :

public void insertListItems(List<EntityA> entityAList) {
    // here I need to convert the List<EntityA>  to List<EntityB>
    // before table insert operation.
}

How I can make that conversion where in the EnitityB I have one column less. I don't want to write boilerplate code for the conversion as my entity class is big in actual. Instead use some library that helps with the mapping.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

如梦初醒的夏天 2025-01-30 08:17:42

您可以使用杰克逊的库来实现这一目标。为了使此工作,您必须在entityaentityb类中都有Geters,以及deff(emptale)构造函数。

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
}

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
}
只为守护你 2025-01-30 08:17:42

您可以尝试获取这样的地图,例如map&lt; string,list&lt; string&gt;列;

第一个值(键)是列名,第二个值(值)是此列的所有值的列表。

然后,您可以使用IF语句选择是否选择列。

因此:

  1. 加载所有列及其值
  2. 使用if语句的循环。
  3. 在此循环中,您还可以集成一个字符串列表,这些字符串是未允许或允许的列名称。

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.
心如荒岛 2025-01-30 08:17:42

如果目的纯粹是存储数据,我认为最好不转换编写本机SQL。

If the purpose is purely to store data, I feel that it is better to write native SQL without converting.

漆黑的白昼 2025-01-30 08:17:42

这创建了一个ObjectMapper的实例,该实例是用于将Java对象序列化的Jackson库中的类,并将JSON逐序化为Java对象。

然后,它将Java ObjectOne序列化为JSON字符串。本质上,它将对象的状态转换为JSON格式字符串。

ObjectMapper.ReadValue(...,Objecttwo.Class):此部分将JSON字符串归还回Java对象。但是,它没有将其重新化为原始类类型(ObjectOne),而是将其反应为Objecttwo的实例。这意味着对objectOne的JSON字符串表示必须与objecttwo的构造函数,设置器或字段兼容。

ObjectMapper objectMapper = new ObjectMapper();

ObjectTwo objectTwo = objectMapper.readValue(objectMapper.writer().writeValueAsString(objectOne), ObjectTwo.class);

This creates an instance of ObjectMapper, which is a class from the Jackson library used for serializing Java objects to JSON and deserializing JSON to Java objects.

Then it serializes the Java object objectOne into a JSON string. Essentially, it converts the state of objectOne into a JSON format string.

objectMapper.readValue(..., ObjectTwo.class): This part deserializes the JSON string back into a Java object. However, instead of deserializing it back to its original class type (ObjectOne), it deserializes it into an instance of ObjectTwo. This implies that the JSON string representation of objectOne must be compatible with the constructor, setters, or fields of ObjectTwo.

ObjectMapper objectMapper = new ObjectMapper();

ObjectTwo objectTwo = objectMapper.readValue(objectMapper.writer().writeValueAsString(objectOne), ObjectTwo.class);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文