如何将对象从一个JpaRepository转换为另一个JpaRepository

时间:2019-09-29 22:55:25

标签: java mysql spring spring-data-jpa

我的spring应用程序中的一个功能有问题。我在同一数据库中有2个表,两个表都包含相同类型的数据(ID,标题,描述和日期)。而且我可以从一张表中获取数据,但是不知道如何插入第二张表中。

在我的@Service层中,我可以从表A中获取数据。但是不知道如何转换为另一个类对象(两个类都包含samne数据)

注入的JpaRepositories

private TasksRepository theTasksRepository;

private TasksRepositoryArchive theTasksRepositoryArchive;

并且有代码从表A(TasksRepository-JpaRepository)中获取对象

    public Tasks findById(int theId) {

        //Check if value is null or not null
        Optional<Tasks> result = theTasksRepository.findById(theId);

        Tasks theTask = null;
        if (result.isPresent())
        {
            //if value is not null
            theTask = result.get();
        }
        else
        {
            //if value is null
            throw new RuntimeException("Task with given ID couldn't be found " +theId );
        }

        return theTask;
    }

1 个答案:

答案 0 :(得分:1)

1)定义2个实体,每个表一个。要复制数据,请创建第二个类型的实例,然后复制属性保存。要复制属性,可以采用多种方法:您不能手动调用每个getter和setter,可以使用Dozer或MapStruct等库。不要忘记将ID设置为null。

2)如果要保存更改存档,请使用有助于实施更改的库。例如,考虑使用Enverse