spring-data-jpa 更新子实体

qfe3c7zg  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(247)

这有点长,但是一个简单的概念问题。请花一些时间阅读:)
我有两个表,它们的列完全相同,只是主键不同。所以我创建了一个具有公共列的@MappedSuperclass,并使用@Entity对子类进行了注解

@MappedSuperclass
public abstract class AbstractCorporateAction {

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "ticker_serial", nullable = false, insertable = false, updatable = false)
    @ToString.Exclude
    private Ticker ticker;

    @Column(name = "corp_act_type", nullable = false, precision = 4)
    private BigInteger corpActType;

    @Column(name = "number_of_shares", precision = 20)
    private BigInteger numberOfShares;
}

下面是子类:

@Entity
@Table(name = "corporate_actions", schema = "dfn_content_data")
public class ContentDataCorporateAction extends AbstractCorporateAction {

    @Id
    @Column(name = "action_id", precision = 10)
    private BigInteger id;
}

@Entity
@Table(name = "corporate_actions", schema = "dfn_ms_history")
public class MsHistoryCorporateAction extends AbstractCorporateAction {

    @Id
    @Column(name = "id")
    private BigInteger id;

    @Column(name = "source_action_id", length = 20, unique = true)
    private String sourceActionId;
}

你可以看到一个子类的主键是action_id,而另一个只是id。我的任务是从这两个子类中检索行,做一些计算,更新相应的字段并推回。
除了最后一部分推回到DB之外,我都做了。现在我有了一个数据列表:List<AbstractCorporateAction>,我想推回去。
1.我尝试通过扩展extends JpaRepository<AbstractCorporateAction, BigInteger>来创建DAO。但是失败了,因为AbstractCorporateAction中没有@Id属性
org.springframework.beans.factory.BeanCreationException:创建在www.example.com _adjustments.repository.calculation中定义的名为“abstractCorporateActionDao”的Bean时出错。com.gtn.ca在CalculationPersistenceConfiguration上声明的@EnableJpaRepositories中定义的abstractCorporateActionDao:调用init方法失败;嵌套的异常是java.lang.IllegalArgumentException:此类[类com.gtn.ca_adjustments.实体.计算.抽象公司操作]未定义标识类
1.然后我尝试将其转换为继承表
@实体@继承(策略= InheritanceType.TABLE_PER_CLASS)公共抽象类AbstractCorporateAction { }
再次失败,因为没有公用ID。
我现在能做什么?
我试过:

interface ContentDataCorporateActionDao extends JpaRepository<ContentDataCorporateAction, BigInteger> {

}

interface MsHistoryCorporateActionDao extends JpaRepository<MsHistoryCorporateAction, BigInteger> {

}

@Repository
public class AbstractCorporateActionDao {

    // Autowire both
    private final ContentDataCorporateActionDao contentDataCorporateActionDao;

    private final MsHistoryCorporateActionDao msHistoryCorporateActionDao;

    @Transactional
    public void saveAll(List<AbstractCorporateAction> abstractCorporateActions) {

        // 1. filter all actions belong to first child class into a list
        // 2. filter all actions belong to second child class into another list

        // 3. for each list -> saveALl() to corresponding dao

    }
}

这是唯一的方法吗?这似乎太多的任务。

ukqbszuj

ukqbszuj1#

您可以通过以下方式对此进行简化:

iterate over the list.
    foreach:
        do an instanceof check
        save with the matching repository.

因此,不需要创建中间列表。因为您的JPA实现将延迟更新,所以使用saveAll没有任何好处。

相关问题