JPA - 使用公共超类在2个不同实体之间复制数据

时间:2017-08-30 13:03:11

标签: jpa inheritance copy entity spring-data-jpa

我有这样的情况

@MappedSuperclass
public class BaseEntity {

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

   @Column(name = "COL_2)
   private String column2;
}

@Entity
@Table(name = "TABLE_A")
public class EntityA extends BaseEntity {
   @Id
   private Long idA;
}

@Entity
@Table(name = "TABLE_B")
public class EntityB extends BaseEntity {
   @Id
   private Long idB;
}

拥有EntityA的实例,我想要的是创建一个EntityB的新实例,其中所有属性都是从EntityA的实例“复制”继承自超类的,从而执行EntityB具体的。

有一种“聪明”的方法可以做到这一点而不做每一套/ get?

N.B。上面的代码只是一个例子,在我的实例中,超类有超过100个属性......

1 个答案:

答案 0 :(得分:0)

Apache Beanutils库具有此类功能。

https://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html#copyProperties-java.lang.Object-java.lang.Object-

package test;

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;

...
EntityA instanceA = ...
EntityB instanceB = ...
BeanUtils.copyProperties(instanceB, instanceA);
  // exceptions are thrown when some negative situation occur.
  // I have no knowledge r/o property (having only getter) is not set / thow exception

  //You should review, how this automatic task is executed in Your scenario. But it is auto 

...persist(instanceB);